diff --git a/.github/workflows/test.yml b/.github/workflows/pr.yml similarity index 55% rename from .github/workflows/test.yml rename to .github/workflows/pr.yml index 9bf4d078..953b7989 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/pr.yml @@ -2,7 +2,14 @@ name: Unit Test on: [pull_request] jobs: + lint-black: + name: 'Lint check (black)' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: psf/black@stable unit-test-postgres: + name: 'Unit tests (PostgreSQL)' runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 00000000..42cdea43 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,6 @@ +repos: + - repo: https://github.com/psf/black + rev: 23.1.0 + hooks: + - id: black + language_version: python3.10 diff --git a/Makefile b/Makefile new file mode 100644 index 00000000..b40cc8a2 --- /dev/null +++ b/Makefile @@ -0,0 +1,15 @@ +.PHONY: isort black test run + +format: isort black + +isort: + isort . + +black: + black . + +test: + pytest tests/ + +run: + poetry run gunicorn --worker-class server.AppUvicornWorker app.main:app \ No newline at end of file diff --git a/README.md b/README.md index ea8ae59e..c647edf9 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,11 @@ Install python packages with: $ poetry install --no-root --only main -E explorer ``` +### Install pre-commit hook +```bash +$ poetry run pre-commit install +``` + ### Setting environment variables The main environment variables are as follows. diff --git a/README_JA.md b/README_JA.md index 6cbd3e76..58010ef3 100644 --- a/README_JA.md +++ b/README_JA.md @@ -54,6 +54,11 @@ $ poetry install --no-root --only main -E explorer ``` +### pre-commit hookのインストール +```bash +$ poetry run pre-commit install +``` + ### 環境変数の設定 主要な環境変数は以下の通りです。 diff --git a/app/database.py b/app/database.py index 39c814a7..2a19f104 100644 --- a/app/database.py +++ b/app/database.py @@ -19,11 +19,7 @@ from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker -from config import ( - DATABASE_URL, - DATABASE_SCHEMA, - DB_ECHO -) +from config import DATABASE_SCHEMA, DATABASE_URL, DB_ECHO options = { "pool_recycle": 3600, @@ -31,7 +27,7 @@ "pool_timeout": 30, "pool_pre_ping": True, "max_overflow": 30, - "echo": DB_ECHO + "echo": DB_ECHO, } engine = create_engine(DATABASE_URL, **options) SessionLocal = sessionmaker(autocommit=False, autoflush=True, bind=engine) diff --git a/app/exceptions.py b/app/exceptions.py index 372471d0..ed83e194 100644 --- a/app/exceptions.py +++ b/app/exceptions.py @@ -28,7 +28,6 @@ class SendTransactionError(Exception): class ContractRevertError(Exception): - def __init__(self, code_msg: str): code, message = error_code_msg(code_msg) self.code = code @@ -50,5 +49,6 @@ class ServiceUnavailableError(Exception): class AuthTokenAlreadyExistsError(Exception): pass + class ResponseLimitExceededError(Exception): pass diff --git a/app/log.py b/app/log.py index f950d49e..ec6f4e89 100644 --- a/app/log.py +++ b/app/log.py @@ -16,21 +16,14 @@ SPDX-License-Identifier: Apache-2.0 """ -import sys import logging +import sys import urllib from datetime import datetime -from fastapi import ( - Request, - Response -) - -from config import ( - LOG_LEVEL, - APP_ENV, - AUTH_LOGFILE, - ACCESS_LOGFILE -) + +from fastapi import Request, Response + +from config import ACCESS_LOGFILE, APP_ENV, AUTH_LOGFILE, LOG_LEVEL logging.basicConfig(level=LOG_LEVEL) LOG = logging.getLogger("issuer_api") @@ -58,13 +51,17 @@ # Auth Log stream_handler_auth = logging.StreamHandler(open(AUTH_LOGFILE, "a")) - formatter_auth = logging.Formatter(INFO_FORMAT.format("[AUTH-LOG] "), TIMESTAMP_FORMAT) + formatter_auth = logging.Formatter( + INFO_FORMAT.format("[AUTH-LOG] "), TIMESTAMP_FORMAT + ) stream_handler_auth.setFormatter(formatter_auth) AUTH_LOG.addHandler(stream_handler_auth) # Access Log stream_handler_access = logging.StreamHandler(open(ACCESS_LOGFILE, "a")) - formatter_access = logging.Formatter(INFO_FORMAT.format("[ACCESS-LOG] "), TIMESTAMP_FORMAT) + formatter_access = logging.Formatter( + INFO_FORMAT.format("[ACCESS-LOG] "), TIMESTAMP_FORMAT + ) stream_handler_access.setFormatter(formatter_access) ACCESS_LOG.addHandler(stream_handler_access) @@ -77,13 +74,17 @@ # Auth Log stream_handler_auth = logging.StreamHandler(open(AUTH_LOGFILE, "a")) - formatter_auth = logging.Formatter(DEBUG_FORMAT.format("[AUTH-LOG] "), TIMESTAMP_FORMAT) + formatter_auth = logging.Formatter( + DEBUG_FORMAT.format("[AUTH-LOG] "), TIMESTAMP_FORMAT + ) stream_handler_auth.setFormatter(formatter_auth) AUTH_LOG.addHandler(stream_handler_auth) # Access Log stream_handler_access = logging.StreamHandler(open(ACCESS_LOGFILE, "a")) - formatter_access = logging.Formatter(INFO_FORMAT.format("[ACCESS-LOG] "), TIMESTAMP_FORMAT) # Same live's formatter + formatter_access = logging.Formatter( + INFO_FORMAT.format("[ACCESS-LOG] "), TIMESTAMP_FORMAT + ) # Same live's formatter stream_handler_access.setFormatter(formatter_access) ACCESS_LOG.addHandler(stream_handler_access) @@ -107,7 +108,13 @@ def output_access_log(req: Request, res: Response, request_start_time: datetime) http_version = req.scope.get("http_version", "") status_code = res.status_code response_time = (datetime.utcnow() - request_start_time).total_seconds() - access_msg = ACCESS_FORMAT % (method, url, http_version, status_code, response_time) + access_msg = ACCESS_FORMAT % ( + method, + url, + http_version, + status_code, + response_time, + ) address = "None" # Initial value headers = req.scope.get("headers", []) diff --git a/app/main.py b/app/main.py index f6797a90..407a633a 100644 --- a/app/main.py +++ b/app/main.py @@ -17,22 +17,21 @@ SPDX-License-Identifier: Apache-2.0 """ from datetime import datetime -from fastapi import ( - FastAPI, - Request, - status -) + +from fastapi import FastAPI, Request, status from fastapi.encoders import jsonable_encoder from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from pydantic import ValidationError from starlette.exceptions import HTTPException as StarletteHTTPException -from config import SERVER_NAME +from app.exceptions import * +from app.log import output_access_log from app.routers import ( - common, account, + bc_explorer, bond, + common, e2e_messaging, file, ledger, @@ -40,54 +39,21 @@ position, share, token_holders, - bc_explorer ) from app.utils.docs_utils import custom_openapi -from app.exceptions import * -from app.log import output_access_log - +from config import SERVER_NAME tags_metadata = [ - { - "name": "root", - "description": "" - }, - { - "name": "common", - "description": "Common functions" - }, - { - "name": "account", - "description": "Issuer account management" - }, - { - "name": "notification", - "description": "Notifications for accounts" - }, - { - "name": "token_common", - "description": "Common functions for tokens" - }, - { - "name": "bond", - "description": "Bond token management" - }, - { - "name": "share", - "description": "Share token management" - }, - { - "name": "utility", - "description": "Utility functions" - }, - { - "name": "messaging", - "description": "Messaging functions with external systems" - }, - { - "name": "blockchain_explorer", - "description": "Blockchain explorer" - } + {"name": "root", "description": ""}, + {"name": "common", "description": "Common functions"}, + {"name": "account", "description": "Issuer account management"}, + {"name": "notification", "description": "Notifications for accounts"}, + {"name": "token_common", "description": "Common functions for tokens"}, + {"name": "bond", "description": "Bond token management"}, + {"name": "share", "description": "Share token management"}, + {"name": "utility", "description": "Utility functions"}, + {"name": "messaging", "description": "Messaging functions with external systems"}, + {"name": "blockchain_explorer", "description": "Blockchain explorer"}, ] app = FastAPI( @@ -95,8 +61,11 @@ description="Security token management system for ibet network", version="23.3.0", contact={"email": "dev@boostry.co.jp"}, - license_info={"name": "Apache 2.0", "url": "http://www.apache.org/licenses/LICENSE-2.0.html"}, - openapi_tags=tags_metadata + license_info={ + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html", + }, + openapi_tags=tags_metadata, ) @@ -115,6 +84,7 @@ async def api_call_handler(request: Request, call_next): # ROUTER ############################################################### + @app.get("/", tags=["root"]) async def root(): return {"server": SERVER_NAME} @@ -137,13 +107,11 @@ async def root(): # EXCEPTION ############################################################### + # 500:InternalServerError @app.exception_handler(500) async def internal_server_error_handler(request: Request, exc: Exception): - meta = { - "code": 1, - "title": "InternalServerError" - } + meta = {"code": 1, "title": "InternalServerError"} return JSONResponse( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content=jsonable_encoder({"meta": meta}), @@ -153,10 +121,7 @@ async def internal_server_error_handler(request: Request, exc: Exception): # 422:RequestValidationError @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): - meta = { - "code": 1, - "title": "RequestValidationError" - } + meta = {"code": 1, "title": "RequestValidationError"} return JSONResponse( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, content=jsonable_encoder({"meta": meta, "detail": exc.errors()}), @@ -167,10 +132,7 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE # NOTE: for exceptions raised directly from Pydantic validation @app.exception_handler(ValidationError) async def query_validation_exception_handler(request: Request, exc: ValidationError): - meta = { - "code": 1, - "title": "RequestValidationError" - } + meta = {"code": 1, "title": "RequestValidationError"} return JSONResponse( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, content=jsonable_encoder({"meta": meta, "detail": exc.errors()}), @@ -180,10 +142,7 @@ async def query_validation_exception_handler(request: Request, exc: ValidationEr # 400:InvalidParameterError @app.exception_handler(InvalidParameterError) async def invalid_parameter_error_handler(request: Request, exc: InvalidParameterError): - meta = { - "code": 1, - "title": "InvalidParameterError" - } + meta = {"code": 1, "title": "InvalidParameterError"} return JSONResponse( status_code=status.HTTP_400_BAD_REQUEST, content=jsonable_encoder({"meta": meta, "detail": exc.args[0]}), @@ -193,10 +152,7 @@ async def invalid_parameter_error_handler(request: Request, exc: InvalidParamete # 400:SendTransactionError @app.exception_handler(SendTransactionError) async def send_transaction_error_handler(request: Request, exc: SendTransactionError): - meta = { - "code": 2, - "title": "SendTransactionError" - } + meta = {"code": 2, "title": "SendTransactionError"} return JSONResponse( status_code=status.HTTP_400_BAD_REQUEST, content=jsonable_encoder({"meta": meta, "detail": exc.args[0]}), @@ -205,11 +161,10 @@ async def send_transaction_error_handler(request: Request, exc: SendTransactionE # 400:AuthTokenAlreadyExistsError @app.exception_handler(AuthTokenAlreadyExistsError) -async def auth_token_already_exists_error_handler(request: Request, exc: AuthTokenAlreadyExistsError): - meta = { - "code": 3, - "title": "AuthTokenAlreadyExistsError" - } +async def auth_token_already_exists_error_handler( + request: Request, exc: AuthTokenAlreadyExistsError +): + meta = {"code": 3, "title": "AuthTokenAlreadyExistsError"} return JSONResponse( status_code=status.HTTP_400_BAD_REQUEST, content=jsonable_encoder({"meta": meta}), @@ -218,11 +173,10 @@ async def auth_token_already_exists_error_handler(request: Request, exc: AuthTok # 400:ResponseLimitExceededError @app.exception_handler(ResponseLimitExceededError) -async def response_limit_exceeded_error_handler(request: Request, exc: ResponseLimitExceededError): - meta = { - "code": 4, - "title": "ResponseLimitExceededError" - } +async def response_limit_exceeded_error_handler( + request: Request, exc: ResponseLimitExceededError +): + meta = {"code": 4, "title": "ResponseLimitExceededError"} return JSONResponse( status_code=status.HTTP_400_BAD_REQUEST, content=jsonable_encoder({"meta": meta, "detail": exc.args[0]}), @@ -232,10 +186,7 @@ async def response_limit_exceeded_error_handler(request: Request, exc: ResponseL # 400:ContractRevertError @app.exception_handler(ContractRevertError) async def contract_revert_error_handler(request: Request, exc: ContractRevertError): - meta = { - "code": exc.code, - "title": "ContractRevertError" - } + meta = {"code": exc.code, "title": "ContractRevertError"} return JSONResponse( status_code=status.HTTP_400_BAD_REQUEST, content=jsonable_encoder({"meta": meta, "detail": exc.message}), @@ -245,10 +196,7 @@ async def contract_revert_error_handler(request: Request, exc: ContractRevertErr # 401:AuthorizationError @app.exception_handler(AuthorizationError) async def authorization_error_handler(request: Request, exc: AuthorizationError): - meta = { - "code": 1, - "title": "AuthorizationError" - } + meta = {"code": 1, "title": "AuthorizationError"} return JSONResponse( status_code=status.HTTP_401_UNAUTHORIZED, content=jsonable_encoder({"meta": meta, "detail": exc.args[0]}), @@ -258,10 +206,7 @@ async def authorization_error_handler(request: Request, exc: AuthorizationError) # 404:NotFound @app.exception_handler(404) async def not_found_error_handler(request: Request, exc: StarletteHTTPException): - meta = { - "code": 1, - "title": "NotFound" - } + meta = {"code": 1, "title": "NotFound"} return JSONResponse( status_code=status.HTTP_404_NOT_FOUND, content=jsonable_encoder({"meta": meta, "detail": exc.detail}), @@ -270,11 +215,10 @@ async def not_found_error_handler(request: Request, exc: StarletteHTTPException) # 405:MethodNotAllowed @app.exception_handler(405) -async def method_not_allowed_error_handler(request: Request, exc: StarletteHTTPException): - meta = { - "code": 1, - "title": "MethodNotAllowed" - } +async def method_not_allowed_error_handler( + request: Request, exc: StarletteHTTPException +): + meta = {"code": 1, "title": "MethodNotAllowed"} return JSONResponse( status_code=status.HTTP_405_METHOD_NOT_ALLOWED, content=jsonable_encoder({"meta": meta}), @@ -283,11 +227,10 @@ async def method_not_allowed_error_handler(request: Request, exc: StarletteHTTPE # 503:ServiceUnavailable @app.exception_handler(ServiceUnavailableError) -async def service_unavailable_error_handler(request: Request, exc: ServiceUnavailableError): - meta = { - "code": 1, - "title": "ServiceUnavailableError" - } +async def service_unavailable_error_handler( + request: Request, exc: ServiceUnavailableError +): + meta = {"code": 1, "title": "ServiceUnavailableError"} return JSONResponse( status_code=status.HTTP_503_SERVICE_UNAVAILABLE, content=jsonable_encoder({"meta": meta, "detail": exc.args[0]}), diff --git a/app/model/blockchain/__init__.py b/app/model/blockchain/__init__.py index e49cc5ca..cc9b018c 100644 --- a/app/model/blockchain/__init__.py +++ b/app/model/blockchain/__init__.py @@ -17,15 +17,12 @@ SPDX-License-Identifier: Apache-2.0 """ from .e2e_messaging import E2EMessaging -from .exchange import ( - IbetExchangeInterface, - IbetSecurityTokenEscrow -) +from .exchange import IbetExchangeInterface, IbetSecurityTokenEscrow +from .personal_info import PersonalInfoContract from .token import ( - IbetStandardTokenInterface, IbetSecurityTokenInterface, + IbetShareContract, + IbetStandardTokenInterface, IbetStraightBondContract, - IbetShareContract ) from .token_list import TokenListContract -from .personal_info import PersonalInfoContract diff --git a/app/model/blockchain/e2e_messaging.py b/app/model/blockchain/e2e_messaging.py index ee4ddf8e..61e74f86 100644 --- a/app/model/blockchain/e2e_messaging.py +++ b/app/model/blockchain/e2e_messaging.py @@ -21,22 +21,19 @@ import secrets import boto3 -from Crypto.Cipher import ( - AES, - PKCS1_OAEP -) +from Crypto.Cipher import AES, PKCS1_OAEP from Crypto.PublicKey import RSA from Crypto.Util.Padding import pad from web3.exceptions import TimeExhausted +from app.exceptions import ContractRevertError, SendTransactionError +from app.utils.contract_utils import ContractUtils from config import ( + AWS_KMS_GENERATE_RANDOM_ENABLED, + AWS_REGION_NAME, CHAIN_ID, TX_GAS_LIMIT, - AWS_KMS_GENERATE_RANDOM_ENABLED, - AWS_REGION_NAME ) -from app.utils.contract_utils import ContractUtils -from app.exceptions import SendTransactionError, ContractRevertError class E2EMessaging: @@ -45,24 +42,22 @@ class E2EMessaging: def __init__(self, contract_address: str): self.contract_address = contract_address - def send_message(self, - to_address: str, message: str, - tx_from: str, private_key: str): + def send_message( + self, to_address: str, message: str, tx_from: str, private_key: str + ): """Send Message""" contract = ContractUtils.get_contract( - contract_name="E2EMessaging", - contract_address=self.contract_address + contract_name="E2EMessaging", contract_address=self.contract_address ) try: - tx = contract.functions.sendMessage( - to_address, - message - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = contract.functions.sendMessage(to_address, message).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) tx_hash, tx_receipt = ContractUtils.send_transaction(tx, private_key) return tx_hash, tx_receipt except ContractRevertError: @@ -72,9 +67,15 @@ def send_message(self, except Exception as err: raise SendTransactionError(err) - def send_message_external(self, - to_address: str, _type: str, message_org: str, to_rsa_public_key: str, - tx_from: str, private_key: str): + def send_message_external( + self, + to_address: str, + _type: str, + message_org: str, + to_rsa_public_key: str, + tx_from: str, + private_key: str, + ): """Send Message(Format message for external system)""" # Encrypt message with AES-256-CBC @@ -89,7 +90,9 @@ def send_message_external(self, aes_iv = secrets.token_bytes(AES.block_size) aes_cipher = AES.new(aes_key, AES.MODE_CBC, aes_iv) pad_message = pad(message_org.encode("utf-8"), AES.block_size) - encrypted_message = base64.b64encode(aes_iv + aes_cipher.encrypt(pad_message)).decode() + encrypted_message = base64.b64encode( + aes_iv + aes_cipher.encrypt(pad_message) + ).decode() # Encrypt AES key with RSA rsa_key = RSA.import_key(to_rsa_public_key) @@ -111,28 +114,28 @@ def send_message_external(self, to_address=to_address, message=message, tx_from=tx_from, - private_key=private_key + private_key=private_key, ) return tx_hash, tx_receipt - def set_public_key(self, - public_key: str, key_type: str, - tx_from: str, private_key: str): + def set_public_key( + self, public_key: str, key_type: str, tx_from: str, private_key: str + ): """Set Public Key""" contract = ContractUtils.get_contract( - contract_name="E2EMessaging", - contract_address=self.contract_address + contract_name="E2EMessaging", contract_address=self.contract_address ) try: tx = contract.functions.setPublicKey( - public_key, - key_type - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + public_key, key_type + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) tx_hash, tx_receipt = ContractUtils.send_transaction(tx, private_key) return tx_hash, tx_receipt except ContractRevertError: diff --git a/app/model/blockchain/exchange.py b/app/model/blockchain/exchange.py index f4141030..7daa0d7b 100644 --- a/app/model/blockchain/exchange.py +++ b/app/model/blockchain/exchange.py @@ -18,22 +18,22 @@ """ from web3.exceptions import TimeExhausted -from config import ( - CHAIN_ID, - TX_GAS_LIMIT +from app.exceptions import ContractRevertError, SendTransactionError +from app.model.blockchain.tx_params.ibet_security_token_escrow import ( + ApproveTransferParams, ) from app.utils.contract_utils import ContractUtils -from app.model.blockchain.tx_params.ibet_security_token_escrow import ApproveTransferParams -from app.exceptions import SendTransactionError, ContractRevertError +from config import CHAIN_ID, TX_GAS_LIMIT class IbetExchangeInterface: """IbetExchangeInterface model""" - def __init__(self, contract_address: str, contract_name: str = "IbetExchangeInterface"): + def __init__( + self, contract_address: str, contract_name: str = "IbetExchangeInterface" + ): self.exchange_contract = ContractUtils.get_contract( - contract_name=contract_name, - contract_address=contract_address + contract_name=contract_name, contract_address=contract_address ) def get_account_balance(self, account_address: str, token_address: str): @@ -46,43 +46,51 @@ def get_account_balance(self, account_address: str, token_address: str): balance = ContractUtils.call_function( contract=self.exchange_contract, function_name="balanceOf", - args=(account_address, token_address,), - default_returns=0 + args=( + account_address, + token_address, + ), + default_returns=0, ) commitment = ContractUtils.call_function( contract=self.exchange_contract, function_name="commitmentOf", - args=(account_address, token_address,), - default_returns=0 + args=( + account_address, + token_address, + ), + default_returns=0, ) - return { - "balance": balance, - "commitment": commitment - } + return {"balance": balance, "commitment": commitment} class IbetSecurityTokenEscrow(IbetExchangeInterface): """IbetSecurityTokenEscrow model""" def __init__(self, contract_address: str): - super().__init__(contract_address=contract_address, contract_name="IbetSecurityTokenEscrow") + super().__init__( + contract_address=contract_address, contract_name="IbetSecurityTokenEscrow" + ) - def approve_transfer(self, - data: ApproveTransferParams, - tx_from: str, - private_key: str): + def approve_transfer( + self, data: ApproveTransferParams, tx_from: str, private_key: str + ): """Approve Transfer""" try: tx = self.exchange_contract.functions.approveTransfer( data.escrow_id, data.data - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) - tx_hash, tx_receipt = ContractUtils.send_transaction(transaction=tx, private_key=private_key) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) + tx_hash, tx_receipt = ContractUtils.send_transaction( + transaction=tx, private_key=private_key + ) return tx_hash, tx_receipt except ContractRevertError: raise diff --git a/app/model/blockchain/personal_info.py b/app/model/blockchain/personal_info.py index e7d24a2d..ed0599c5 100644 --- a/app/model/blockchain/personal_info.py +++ b/app/model/blockchain/personal_info.py @@ -19,27 +19,24 @@ import base64 import json +import logging import os import sys -import logging + from Crypto.Cipher import PKCS1_OAEP from Crypto.PublicKey import RSA -from web3.exceptions import TimeExhausted from eth_keyfile import decode_keyfile_json +from web3.exceptions import TimeExhausted -path = os.path.join(os.path.dirname(__file__), '../') +path = os.path.join(os.path.dirname(__file__), "../") sys.path.append(path) -from config import ( - CHAIN_ID, - TX_GAS_LIMIT, - ZERO_ADDRESS -) -from app.utils.contract_utils import ContractUtils -from app.utils.web3_utils import Web3Wrapper +from app.exceptions import ContractRevertError, SendTransactionError from app.model.db import Account +from app.utils.contract_utils import ContractUtils from app.utils.e2ee_utils import E2EEUtils -from app.exceptions import SendTransactionError, ContractRevertError +from app.utils.web3_utils import Web3Wrapper +from config import CHAIN_ID, TX_GAS_LIMIT, ZERO_ADDRESS web3 = Web3Wrapper() @@ -49,12 +46,11 @@ class PersonalInfoContract: def __init__(self, db, issuer_address: str, contract_address=None): self.personal_info_contract = ContractUtils.get_contract( - contract_name="PersonalInfo", - contract_address=contract_address + contract_name="PersonalInfo", contract_address=contract_address + ) + self.issuer = ( + db.query(Account).filter(Account.issuer_address == issuer_address).first() ) - self.issuer = db.query(Account). \ - filter(Account.issuer_address == issuer_address). \ - first() def get_info(self, account_address: str, default_value=None): """Get personal information @@ -73,15 +69,18 @@ def get_info(self, account_address: str, default_value=None): "email": default_value, "birth": default_value, "is_corporate": default_value, - "tax_category": default_value + "tax_category": default_value, } # Get encrypted personal information personal_info_state = ContractUtils.call_function( contract=self.personal_info_contract, function_name="personal_info", - args=(account_address, self.issuer.issuer_address,), - default_returns=[ZERO_ADDRESS, ZERO_ADDRESS, ""] + args=( + account_address, + self.issuer.issuer_address, + ), + default_returns=[ZERO_ADDRESS, ZERO_ADDRESS, ""], ) encrypted_info = personal_info_state[2] @@ -110,20 +109,32 @@ def get_info(self, account_address: str, default_value=None): ciphertext = base64.b16decode(hex_fixed.upper()) decrypted_info = json.loads(cipher.decrypt(ciphertext)) - personal_info["key_manager"] = decrypted_info.get("key_manager", default_value) + personal_info["key_manager"] = decrypted_info.get( + "key_manager", default_value + ) personal_info["name"] = decrypted_info.get("name", default_value) - personal_info["address"] = decrypted_info.get("address", default_value) - personal_info["postal_code"] = decrypted_info.get("postal_code", default_value) + personal_info["address"] = decrypted_info.get( + "address", default_value + ) + personal_info["postal_code"] = decrypted_info.get( + "postal_code", default_value + ) personal_info["email"] = decrypted_info.get("email", default_value) personal_info["birth"] = decrypted_info.get("birth", default_value) - personal_info["is_corporate"] = decrypted_info.get("is_corporate", default_value) - personal_info["tax_category"] = decrypted_info.get("tax_category", default_value) + personal_info["is_corporate"] = decrypted_info.get( + "is_corporate", default_value + ) + personal_info["tax_category"] = decrypted_info.get( + "tax_category", default_value + ) return personal_info except Exception as err: logging.error(f"Failed to decrypt: {err}") return personal_info # default - def register_info(self, account_address: str, data: dict, default_value=None) -> str: + def register_info( + self, account_address: str, data: dict, default_value=None + ) -> str: """Register personal information :param account_address: Token holder account address @@ -141,29 +152,35 @@ def register_info(self, account_address: str, data: dict, default_value=None) -> "email": data.get("email", default_value), "birth": data.get("birth", default_value), "is_corporate": data.get("is_corporate", default_value), - "tax_category": data.get("tax_category", default_value) + "tax_category": data.get("tax_category", default_value), } # Encrypt personal info passphrase = E2EEUtils.decrypt(self.issuer.rsa_passphrase) rsa_key = RSA.importKey(self.issuer.rsa_public_key, passphrase=passphrase) cipher = PKCS1_OAEP.new(rsa_key) - ciphertext = base64.encodebytes(cipher.encrypt(json.dumps(personal_info).encode('utf-8'))) + ciphertext = base64.encodebytes( + cipher.encrypt(json.dumps(personal_info).encode("utf-8")) + ) try: password = E2EEUtils.decrypt(self.issuer.eoa_password) private_key = decode_keyfile_json( - raw_keyfile_json=self.issuer.keyfile, - password=password.encode("utf-8") + raw_keyfile_json=self.issuer.keyfile, password=password.encode("utf-8") ) - tx = self.personal_info_contract.functions.forceRegister(account_address, ciphertext). \ - build_transaction({ + tx = self.personal_info_contract.functions.forceRegister( + account_address, ciphertext + ).build_transaction( + { "chainId": CHAIN_ID, "from": self.issuer.issuer_address, "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) - tx_hash, _ = ContractUtils.send_transaction(transaction=tx, private_key=private_key) + "gasPrice": 0, + } + ) + tx_hash, _ = ContractUtils.send_transaction( + transaction=tx, private_key=private_key + ) except ContractRevertError: raise except TimeExhausted as timeout_error: @@ -191,28 +208,32 @@ def modify_info(self, account_address: str, data: dict, default_value=None): "email": data.get("email", default_value), "birth": data.get("birth", default_value), "is_corporate": data.get("is_corporate", default_value), - "tax_category": data.get("tax_category", default_value) + "tax_category": data.get("tax_category", default_value), } # Encrypt personal info passphrase = E2EEUtils.decrypt(self.issuer.rsa_passphrase) rsa_key = RSA.importKey(self.issuer.rsa_public_key, passphrase=passphrase) cipher = PKCS1_OAEP.new(rsa_key) - ciphertext = base64.encodebytes(cipher.encrypt(json.dumps(personal_info).encode('utf-8'))) + ciphertext = base64.encodebytes( + cipher.encrypt(json.dumps(personal_info).encode("utf-8")) + ) try: password = E2EEUtils.decrypt(self.issuer.eoa_password) private_key = decode_keyfile_json( - raw_keyfile_json=self.issuer.keyfile, - password=password.encode("utf-8") + raw_keyfile_json=self.issuer.keyfile, password=password.encode("utf-8") ) - tx = self.personal_info_contract.functions.modify(account_address, ciphertext). \ - build_transaction({ + tx = self.personal_info_contract.functions.modify( + account_address, ciphertext + ).build_transaction( + { "chainId": CHAIN_ID, "from": self.issuer.issuer_address, "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + "gasPrice": 0, + } + ) ContractUtils.send_transaction(transaction=tx, private_key=private_key) except ContractRevertError: raise @@ -233,7 +254,7 @@ def get_register_event(self, block_from, block_to): contract=self.personal_info_contract, event="Register", block_from=block_from, - block_to=block_to + block_to=block_to, ) return events @@ -248,6 +269,6 @@ def get_modify_event(self, block_from, block_to): contract=self.personal_info_contract, event="Modify", block_from=block_from, - block_to=block_to + block_to=block_to, ) return events diff --git a/app/model/blockchain/token.py b/app/model/blockchain/token.py index b0c92837..590252fa 100644 --- a/app/model/blockchain/token.py +++ b/app/model/blockchain/token.py @@ -16,13 +16,10 @@ SPDX-License-Identifier: Apache-2.0 """ -from typing import List import json +from datetime import datetime, timedelta from decimal import Decimal -from datetime import ( - datetime, - timedelta -) +from typing import List from sqlalchemy import desc from sqlalchemy.exc import IntegrityError as SAIntegrityError @@ -30,41 +27,41 @@ from web3.datastructures import AttributeDict from web3.exceptions import TimeExhausted -from config import ( - TOKEN_CACHE, - TOKEN_CACHE_TTL, - CHAIN_ID, - TX_GAS_LIMIT, - ZERO_ADDRESS -) +from app import log from app.database import engine +from app.exceptions import ContractRevertError, SendTransactionError from app.model.blockchain import IbetExchangeInterface from app.model.blockchain.tx_params.ibet_security_token import ( - TransferParams as IbetSecurityTokenTransferParams, AdditionalIssueParams as IbetSecurityTokenAdditionalIssueParams, - RedeemParams as IbetSecurityTokenRedeemParams, +) +from app.model.blockchain.tx_params.ibet_security_token import ( ApproveTransferParams as IbetSecurityTokenApproveTransfer, +) +from app.model.blockchain.tx_params.ibet_security_token import ( CancelTransferParams as IbetSecurityTokenCancelTransfer, +) +from app.model.blockchain.tx_params.ibet_security_token import ( + ForceUnlockParams as IbetSecurityTokenForceUnlockParams, +) +from app.model.blockchain.tx_params.ibet_security_token import ( LockParams as IbetSecurityTokenLockParams, - ForceUnlockParams as IbetSecurityTokenForceUnlockParams ) -from app.model.blockchain.tx_params.ibet_share import ( - UpdateParams as IbetShareUpdateParams +from app.model.blockchain.tx_params.ibet_security_token import ( + RedeemParams as IbetSecurityTokenRedeemParams, ) -from app.model.blockchain.tx_params.ibet_straight_bond import ( - UpdateParams as IbetStraightBondUpdateParams +from app.model.blockchain.tx_params.ibet_security_token import ( + TransferParams as IbetSecurityTokenTransferParams, ) -from app.model.db import ( - TokenAttrUpdate, - TokenCache +from app.model.blockchain.tx_params.ibet_share import ( + UpdateParams as IbetShareUpdateParams, ) -from app.exceptions import ( - SendTransactionError, - ContractRevertError +from app.model.blockchain.tx_params.ibet_straight_bond import ( + UpdateParams as IbetStraightBondUpdateParams, ) -from app import log +from app.model.db import TokenAttrUpdate, TokenCache from app.utils.contract_utils import ContractUtils from app.utils.web3_utils import Web3Wrapper +from config import CHAIN_ID, TOKEN_CACHE, TOKEN_CACHE_TTL, TX_GAS_LIMIT, ZERO_ADDRESS LOG = log.get_logger() @@ -82,19 +79,26 @@ class IbetStandardTokenInterface: tradable_exchange_contract_address: str status: bool - def __init__(self, - contract_address: str = ZERO_ADDRESS, - contract_name: str = "IbetStandardTokenInterface"): + def __init__( + self, + contract_address: str = ZERO_ADDRESS, + contract_name: str = "IbetStandardTokenInterface", + ): self.contract_name = contract_name self.token_address = contract_address def check_attr_update(self, db_session: Session, base_datetime: datetime): is_updated = False - _token_attr_update = db_session.query(TokenAttrUpdate). \ - filter(TokenAttrUpdate.token_address == self.token_address). \ - order_by(desc(TokenAttrUpdate.id)). \ - first() - if _token_attr_update is not None and _token_attr_update.updated_datetime > base_datetime: + _token_attr_update = ( + db_session.query(TokenAttrUpdate) + .filter(TokenAttrUpdate.token_address == self.token_address) + .order_by(desc(TokenAttrUpdate.id)) + .first() + ) + if ( + _token_attr_update is not None + and _token_attr_update.updated_datetime > base_datetime + ): is_updated = True return is_updated @@ -109,39 +113,41 @@ def create_cache(self, db_session: Session): token_cache.token_address = self.token_address token_cache.attributes = self.__dict__ token_cache.cached_datetime = datetime.utcnow() - token_cache.expiration_datetime = datetime.utcnow() + timedelta(seconds=TOKEN_CACHE_TTL) + token_cache.expiration_datetime = datetime.utcnow() + timedelta( + seconds=TOKEN_CACHE_TTL + ) db_session.merge(token_cache) def delete_cache(self, db_session: Session): - db_session.query(TokenCache). \ - filter(TokenCache.token_address == self.token_address). \ - delete() + db_session.query(TokenCache).filter( + TokenCache.token_address == self.token_address + ).delete() def get_account_balance(self, account_address: str): """Get account balance""" contract = ContractUtils.get_contract( - contract_name=self.contract_name, - contract_address=self.token_address + contract_name=self.contract_name, contract_address=self.token_address ) balance = ContractUtils.call_function( contract=contract, function_name="balanceOf", args=(account_address,), - default_returns=0 + default_returns=0, ) tradable_exchange_address = ContractUtils.call_function( contract=contract, function_name="tradableExchange", args=(), - default_returns=ZERO_ADDRESS + default_returns=ZERO_ADDRESS, ) if tradable_exchange_address != ZERO_ADDRESS: exchange_contract = IbetExchangeInterface(tradable_exchange_address) exchange_balance = exchange_contract.get_account_balance( - account_address=account_address, - token_address=self.token_address + account_address=account_address, token_address=self.token_address + ) + balance = ( + balance + exchange_balance["balance"] + exchange_balance["commitment"] ) - balance = balance + exchange_balance["balance"] + exchange_balance["commitment"] return balance @@ -152,36 +158,34 @@ class IbetSecurityTokenInterface(IbetStandardTokenInterface): is_offering: bool transfer_approval_required: bool - def __init__(self, - contract_address: str = ZERO_ADDRESS, - contract_name: str = "IbetSecurityTokenInterface"): + def __init__( + self, + contract_address: str = ZERO_ADDRESS, + contract_name: str = "IbetSecurityTokenInterface", + ): super().__init__(contract_address, contract_name) - def transfer(self, - data: IbetSecurityTokenTransferParams, - tx_from: str, private_key: str): + def transfer( + self, data: IbetSecurityTokenTransferParams, tx_from: str, private_key: str + ): """Transfer ownership""" try: contract = ContractUtils.get_contract( - contract_name=self.contract_name, - contract_address=self.token_address + contract_name=self.contract_name, contract_address=self.token_address ) _from = data.from_address _to = data.to_address _amount = data.amount - tx = contract.functions.transferFrom( - _from, - _to, - _amount - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = contract.functions.transferFrom(_from, _to, _amount).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) tx_hash, _ = ContractUtils.send_transaction( - transaction=tx, - private_key=private_key + transaction=tx, private_key=private_key ) except ContractRevertError: raise @@ -192,30 +196,31 @@ def transfer(self, return tx_hash - def additional_issue(self, - data: IbetSecurityTokenAdditionalIssueParams, - tx_from: str, private_key: str): + def additional_issue( + self, + data: IbetSecurityTokenAdditionalIssueParams, + tx_from: str, + private_key: str, + ): """Additional issue""" try: contract = ContractUtils.get_contract( - contract_name=self.contract_name, - contract_address=self.token_address + contract_name=self.contract_name, contract_address=self.token_address ) _target_address = data.account_address _amount = data.amount tx = contract.functions.issueFrom( - _target_address, - ZERO_ADDRESS, - _amount - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + _target_address, ZERO_ADDRESS, _amount + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) tx_hash, _ = ContractUtils.send_transaction( - transaction=tx, - private_key=private_key + transaction=tx, private_key=private_key ) except ContractRevertError: raise @@ -237,30 +242,28 @@ def additional_issue(self, return tx_hash - def redeem(self, - data: IbetSecurityTokenRedeemParams, - tx_from: str, private_key: str): + def redeem( + self, data: IbetSecurityTokenRedeemParams, tx_from: str, private_key: str + ): """Redeem a token""" try: contract = ContractUtils.get_contract( - contract_name=self.contract_name, - contract_address=self.token_address + contract_name=self.contract_name, contract_address=self.token_address ) _target_address = data.account_address _amount = data.amount tx = contract.functions.redeemFrom( - _target_address, - ZERO_ADDRESS, - _amount - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + _target_address, ZERO_ADDRESS, _amount + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) tx_hash, _ = ContractUtils.send_transaction( - transaction=tx, - private_key=private_key + transaction=tx, private_key=private_key ) except ContractRevertError: raise @@ -282,27 +285,26 @@ def redeem(self, return tx_hash - def approve_transfer(self, - data: IbetSecurityTokenApproveTransfer, - tx_from: str, private_key: str): + def approve_transfer( + self, data: IbetSecurityTokenApproveTransfer, tx_from: str, private_key: str + ): """Approve Transfer""" try: contract = ContractUtils.get_contract( - contract_name=self.contract_name, - contract_address=self.token_address + contract_name=self.contract_name, contract_address=self.token_address ) tx = contract.functions.approveTransfer( - data.application_id, - data.data - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + data.application_id, data.data + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) tx_hash, tx_receipt = ContractUtils.send_transaction( - transaction=tx, - private_key=private_key + transaction=tx, private_key=private_key ) return tx_hash, tx_receipt except ContractRevertError: @@ -312,27 +314,26 @@ def approve_transfer(self, except Exception as err: raise SendTransactionError(err) - def cancel_transfer(self, - data: IbetSecurityTokenCancelTransfer, - tx_from: str, private_key: str): + def cancel_transfer( + self, data: IbetSecurityTokenCancelTransfer, tx_from: str, private_key: str + ): """Cancel Transfer""" try: contract = ContractUtils.get_contract( - contract_name=self.contract_name, - contract_address=self.token_address + contract_name=self.contract_name, contract_address=self.token_address ) tx = contract.functions.cancelTransfer( - data.application_id, - data.data - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + data.application_id, data.data + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) tx_hash, tx_receipt = ContractUtils.send_transaction( - transaction=tx, - private_key=private_key + transaction=tx, private_key=private_key ) return tx_hash, tx_receipt except ContractRevertError: @@ -342,28 +343,24 @@ def cancel_transfer(self, except Exception as err: raise SendTransactionError(err) - def lock(self, - data: IbetSecurityTokenLockParams, - tx_from: str, private_key: str): + def lock(self, data: IbetSecurityTokenLockParams, tx_from: str, private_key: str): """Lock""" try: contract = ContractUtils.get_contract( - contract_name=self.contract_name, - contract_address=self.token_address + contract_name=self.contract_name, contract_address=self.token_address ) tx = contract.functions.lock( - data.lock_address, - data.value, - data.data - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + data.lock_address, data.value, data.data + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) tx_hash, tx_receipt = ContractUtils.send_transaction( - transaction=tx, - private_key=private_key + transaction=tx, private_key=private_key ) return tx_hash, tx_receipt except ContractRevertError: @@ -373,30 +370,30 @@ def lock(self, except Exception as err: raise SendTransactionError(err) - def force_unlock(self, - data: IbetSecurityTokenForceUnlockParams, - tx_from: str, private_key: str): + def force_unlock( + self, data: IbetSecurityTokenForceUnlockParams, tx_from: str, private_key: str + ): """Force Unlock""" try: contract = ContractUtils.get_contract( - contract_name=self.contract_name, - contract_address=self.token_address + contract_name=self.contract_name, contract_address=self.token_address ) tx = contract.functions.forceUnlock( data.lock_address, data.account_address, data.recipient_address, data.value, - data.data - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + data.data, + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) tx_hash, tx_receipt = ContractUtils.send_transaction( - transaction=tx, - private_key=private_key + transaction=tx, private_key=private_key ) return tx_hash, tx_receipt except ContractRevertError: @@ -422,8 +419,7 @@ class IbetStraightBondContract(IbetSecurityTokenInterface): def __init__(self, contract_address: str = ZERO_ADDRESS): super().__init__(contract_address, "IbetStraightBond") - def create(self, args: list, - tx_from: str, private_key: str): + def create(self, args: list, tx_from: str, private_key: str): """Deploy token :param args: deploy arguments @@ -436,7 +432,7 @@ def create(self, args: list, contract_name="IbetStraightBond", args=args, deployer=tx_from, - private_key=private_key + private_key=private_key, ) self.contract_name = "IbetStraightBond" self.token_address = contract_address @@ -450,15 +446,19 @@ def get(self): # When using the cache if TOKEN_CACHE: - token_cache: TokenCache = db_session.query(TokenCache). \ - filter(TokenCache.token_address == self.token_address). \ - first() + token_cache: TokenCache = ( + db_session.query(TokenCache) + .filter(TokenCache.token_address == self.token_address) + .first() + ) if token_cache is not None: is_updated = self.check_attr_update( - db_session=db_session, - base_datetime=token_cache.cached_datetime + db_session=db_session, base_datetime=token_cache.cached_datetime ) - if is_updated is False and token_cache.expiration_datetime > datetime.utcnow(): + if ( + is_updated is False + and token_cache.expiration_datetime > datetime.utcnow() + ): # Get data from cache for k, v in token_cache.attributes.items(): setattr(self, k, v) @@ -470,43 +470,67 @@ def get(self): # Or, if the cache has expired contract = ContractUtils.get_contract( - contract_name=self.contract_name, - contract_address=self.token_address + contract_name=self.contract_name, contract_address=self.token_address ) # Set IbetStandardTokenInterface attribute - self.issuer_address = ContractUtils.call_function(contract, "owner", (), ZERO_ADDRESS) + self.issuer_address = ContractUtils.call_function( + contract, "owner", (), ZERO_ADDRESS + ) self.name = ContractUtils.call_function(contract, "name", (), "") self.symbol = ContractUtils.call_function(contract, "symbol", (), "") self.total_supply = ContractUtils.call_function(contract, "totalSupply", (), 0) - self.tradable_exchange_contract_address = ContractUtils.call_function(contract, "tradableExchange", (), ZERO_ADDRESS) - self.contact_information = ContractUtils.call_function(contract, "contactInformation", (), "") - self.privacy_policy = ContractUtils.call_function(contract, "privacyPolicy", (), "") + self.tradable_exchange_contract_address = ContractUtils.call_function( + contract, "tradableExchange", (), ZERO_ADDRESS + ) + self.contact_information = ContractUtils.call_function( + contract, "contactInformation", (), "" + ) + self.privacy_policy = ContractUtils.call_function( + contract, "privacyPolicy", (), "" + ) self.status = ContractUtils.call_function(contract, "status", (), True) # Set IbetSecurityTokenInterface attribute - self.personal_info_contract_address = ContractUtils.call_function(contract, "personalInfoAddress", (), ZERO_ADDRESS) - self.transferable = ContractUtils.call_function(contract, "transferable", (), False) - self.is_offering = ContractUtils.call_function(contract, "isOffering", (), False) - self.transfer_approval_required = ContractUtils.call_function(contract, "transferApprovalRequired", (), False) + self.personal_info_contract_address = ContractUtils.call_function( + contract, "personalInfoAddress", (), ZERO_ADDRESS + ) + self.transferable = ContractUtils.call_function( + contract, "transferable", (), False + ) + self.is_offering = ContractUtils.call_function( + contract, "isOffering", (), False + ) + self.transfer_approval_required = ContractUtils.call_function( + contract, "transferApprovalRequired", (), False + ) # Set IbetStraightBondToken attribute self.face_value = ContractUtils.call_function(contract, "faceValue", (), 0) self.interest_rate = float( - Decimal(str( - ContractUtils.call_function(contract, "interestRate", (), 0) - )) * Decimal("0.0001") + Decimal(str(ContractUtils.call_function(contract, "interestRate", (), 0))) + * Decimal("0.0001") + ) + self.redemption_date = ContractUtils.call_function( + contract, "redemptionDate", (), "" + ) + self.redemption_value = ContractUtils.call_function( + contract, "redemptionValue", (), 0 ) - self.redemption_date = ContractUtils.call_function(contract, "redemptionDate", (), "") - self.redemption_value = ContractUtils.call_function(contract, "redemptionValue", (), 0) self.return_date = ContractUtils.call_function(contract, "returnDate", (), "") - self.return_amount = ContractUtils.call_function(contract, "returnAmount", (), "") + self.return_amount = ContractUtils.call_function( + contract, "returnAmount", (), "" + ) self.purpose = ContractUtils.call_function(contract, "purpose", (), "") self.memo = ContractUtils.call_function(contract, "memo", (), "") - self.is_redeemed = ContractUtils.call_function(contract, "isRedeemed", (), False) + self.is_redeemed = ContractUtils.call_function( + contract, "isRedeemed", (), False + ) interest_payment_date_list = [] - interest_payment_date_string = ContractUtils.call_function(contract, "interestPaymentDate", (), "").replace("'", '"') + interest_payment_date_string = ContractUtils.call_function( + contract, "interestPaymentDate", (), "" + ).replace("'", '"') interest_payment_date = {} try: if interest_payment_date_string != "": @@ -531,24 +555,23 @@ def get(self): return AttributeDict(self.__dict__) - def update(self, - data: IbetStraightBondUpdateParams, - tx_from: str, private_key: str): + def update( + self, data: IbetStraightBondUpdateParams, tx_from: str, private_key: str + ): """Update token""" contract = ContractUtils.get_contract( - contract_name=self.contract_name, - contract_address=self.token_address + contract_name=self.contract_name, contract_address=self.token_address ) if data.face_value is not None: - tx = contract.functions.setFaceValue( - data.face_value - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = contract.functions.setFaceValue(data.face_value).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) try: ContractUtils.send_transaction(transaction=tx, private_key=private_key) except ContractRevertError: @@ -560,14 +583,14 @@ def update(self, if data.interest_rate is not None: _interest_rate = int(Decimal(str(data.interest_rate)) * Decimal("10000")) - tx = contract.functions.setInterestRate( - _interest_rate - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = contract.functions.setInterestRate(_interest_rate).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) try: ContractUtils.send_transaction(transaction=tx, private_key=private_key) except ContractRevertError: @@ -584,12 +607,14 @@ def update(self, _interest_payment_date_string = json.dumps(_interest_payment_date) tx = contract.functions.setInterestPaymentDate( _interest_payment_date_string - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) try: ContractUtils.send_transaction(transaction=tx, private_key=private_key) except ContractRevertError: @@ -602,12 +627,14 @@ def update(self, if data.redemption_value is not None: tx = contract.functions.setRedemptionValue( data.redemption_value - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) try: ContractUtils.send_transaction(transaction=tx, private_key=private_key) except TimeExhausted as timeout_error: @@ -618,12 +645,14 @@ def update(self, if data.transferable is not None: tx = contract.functions.setTransferable( data.transferable - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) try: ContractUtils.send_transaction(transaction=tx, private_key=private_key) except ContractRevertError: @@ -634,14 +663,14 @@ def update(self, raise SendTransactionError(err) if data.status is not None: - tx = contract.functions.setStatus( - data.status - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = contract.functions.setStatus(data.status).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) try: ContractUtils.send_transaction(transaction=tx, private_key=private_key) except ContractRevertError: @@ -654,12 +683,14 @@ def update(self, if data.is_offering is not None: tx = contract.functions.changeOfferingStatus( data.is_offering - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) try: ContractUtils.send_transaction(transaction=tx, private_key=private_key) except ContractRevertError: @@ -670,12 +701,14 @@ def update(self, raise SendTransactionError(err) if data.is_redeemed is not None and data.is_redeemed: - tx = contract.functions.changeToRedeemed().build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = contract.functions.changeToRedeemed().build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) try: ContractUtils.send_transaction(transaction=tx, private_key=private_key) except ContractRevertError: @@ -688,12 +721,14 @@ def update(self, if data.tradable_exchange_contract_address is not None: tx = contract.functions.setTradableExchange( data.tradable_exchange_contract_address - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) try: ContractUtils.send_transaction(transaction=tx, private_key=private_key) except ContractRevertError: @@ -706,12 +741,14 @@ def update(self, if data.personal_info_contract_address is not None: tx = contract.functions.setPersonalInfoAddress( data.personal_info_contract_address - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) try: ContractUtils.send_transaction(transaction=tx, private_key=private_key) except ContractRevertError: @@ -724,12 +761,14 @@ def update(self, if data.contact_information is not None: tx = contract.functions.setContactInformation( data.contact_information - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) try: ContractUtils.send_transaction(transaction=tx, private_key=private_key) except ContractRevertError: @@ -742,12 +781,14 @@ def update(self, if data.privacy_policy is not None: tx = contract.functions.setPrivacyPolicy( data.privacy_policy - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) try: ContractUtils.send_transaction(transaction=tx, private_key=private_key) except ContractRevertError: @@ -760,12 +801,14 @@ def update(self, if data.transfer_approval_required is not None: tx = contract.functions.setTransferApprovalRequired( data.transfer_approval_required - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) try: ContractUtils.send_transaction(transaction=tx, private_key=private_key) except ContractRevertError: @@ -776,14 +819,14 @@ def update(self, raise SendTransactionError(err) if data.memo is not None: - tx = contract.functions.setMemo( - data.memo - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = contract.functions.setMemo(data.memo).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) try: ContractUtils.send_transaction(transaction=tx, private_key=private_key) except ContractRevertError: @@ -818,8 +861,7 @@ class IbetShareContract(IbetSecurityTokenInterface): def __init__(self, contract_address: str = ZERO_ADDRESS): super().__init__(contract_address, "IbetShare") - def create(self, args: list, - tx_from: str, private_key: str): + def create(self, args: list, tx_from: str, private_key: str): """Deploy token :param args: deploy arguments @@ -832,7 +874,7 @@ def create(self, args: list, contract_name="IbetShare", args=args, deployer=tx_from, - private_key=private_key + private_key=private_key, ) self.contract_name = "IbetShare" self.token_address = contract_address @@ -846,15 +888,19 @@ def get(self): # When using the cache if TOKEN_CACHE: - token_cache: TokenCache = db_session.query(TokenCache). \ - filter(TokenCache.token_address == self.token_address). \ - first() + token_cache: TokenCache = ( + db_session.query(TokenCache) + .filter(TokenCache.token_address == self.token_address) + .first() + ) if token_cache is not None: is_updated = self.check_attr_update( - db_session=db_session, - base_datetime=token_cache.cached_datetime + db_session=db_session, base_datetime=token_cache.cached_datetime ) - if is_updated is False and token_cache.expiration_datetime > datetime.utcnow(): + if ( + is_updated is False + and token_cache.expiration_datetime > datetime.utcnow() + ): # Get data from cache for k, v in token_cache.attributes.items(): setattr(self, k, v) @@ -866,34 +912,59 @@ def get(self): # Or, if the cache has expired contract = ContractUtils.get_contract( - contract_name=self.contract_name, - contract_address=self.token_address + contract_name=self.contract_name, contract_address=self.token_address ) # Set IbetStandardTokenInterface attribute - self.issuer_address = ContractUtils.call_function(contract, "owner", (), ZERO_ADDRESS) + self.issuer_address = ContractUtils.call_function( + contract, "owner", (), ZERO_ADDRESS + ) self.name = ContractUtils.call_function(contract, "name", (), "") self.symbol = ContractUtils.call_function(contract, "symbol", (), "") self.total_supply = ContractUtils.call_function(contract, "totalSupply", (), 0) - self.tradable_exchange_contract_address = ContractUtils.call_function(contract, "tradableExchange", (), ZERO_ADDRESS) - self.contact_information = ContractUtils.call_function(contract, "contactInformation", (), "") - self.privacy_policy = ContractUtils.call_function(contract, "privacyPolicy", (), "") + self.tradable_exchange_contract_address = ContractUtils.call_function( + contract, "tradableExchange", (), ZERO_ADDRESS + ) + self.contact_information = ContractUtils.call_function( + contract, "contactInformation", (), "" + ) + self.privacy_policy = ContractUtils.call_function( + contract, "privacyPolicy", (), "" + ) self.status = ContractUtils.call_function(contract, "status", (), True) # Set IbetSecurityTokenInterface attribute - self.personal_info_contract_address = ContractUtils.call_function(contract, "personalInfoAddress", (), ZERO_ADDRESS) - self.transferable = ContractUtils.call_function(contract, "transferable", (), False) - self.is_offering = ContractUtils.call_function(contract, "isOffering", (), False) - self.transfer_approval_required = ContractUtils.call_function(contract, "transferApprovalRequired", (), False) + self.personal_info_contract_address = ContractUtils.call_function( + contract, "personalInfoAddress", (), ZERO_ADDRESS + ) + self.transferable = ContractUtils.call_function( + contract, "transferable", (), False + ) + self.is_offering = ContractUtils.call_function( + contract, "isOffering", (), False + ) + self.transfer_approval_required = ContractUtils.call_function( + contract, "transferApprovalRequired", (), False + ) # Set IbetShareToken attribute self.issue_price = ContractUtils.call_function(contract, "issuePrice", (), 0) - self.cancellation_date = ContractUtils.call_function(contract, "cancellationDate", (), "") + self.cancellation_date = ContractUtils.call_function( + contract, "cancellationDate", (), "" + ) self.memo = ContractUtils.call_function(contract, "memo", (), "") - self.principal_value = ContractUtils.call_function(contract, "principalValue", (), 0) - self.is_canceled = ContractUtils.call_function(contract, "isCanceled", (), False) - _dividend_info = ContractUtils.call_function(contract, "dividendInformation", (), (0, "", "")) - self.dividends = float(Decimal(str(_dividend_info[0])) * Decimal("0.0000000000001")) + self.principal_value = ContractUtils.call_function( + contract, "principalValue", (), 0 + ) + self.is_canceled = ContractUtils.call_function( + contract, "isCanceled", (), False + ) + _dividend_info = ContractUtils.call_function( + contract, "dividendInformation", (), (0, "", "") + ) + self.dividends = float( + Decimal(str(_dividend_info[0])) * Decimal("0.0000000000001") + ) self.dividend_record_date = _dividend_info[1] self.dividend_payment_date = _dividend_info[2] @@ -909,24 +980,23 @@ def get(self): return AttributeDict(self.__dict__) - def update(self, - data: IbetShareUpdateParams, - tx_from: str, private_key: str): + def update(self, data: IbetShareUpdateParams, tx_from: str, private_key: str): """Update token""" contract = ContractUtils.get_contract( - contract_name=self.contract_name, - contract_address=self.token_address + contract_name=self.contract_name, contract_address=self.token_address ) if data.tradable_exchange_contract_address is not None: tx = contract.functions.setTradableExchange( data.tradable_exchange_contract_address - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) try: ContractUtils.send_transaction(transaction=tx, private_key=private_key) except ContractRevertError: @@ -939,12 +1009,14 @@ def update(self, if data.personal_info_contract_address is not None: tx = contract.functions.setPersonalInfoAddress( data.personal_info_contract_address - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) try: ContractUtils.send_transaction(transaction=tx, private_key=private_key) except ContractRevertError: @@ -957,15 +1029,15 @@ def update(self, if data.dividends is not None: _dividends = int(Decimal(str(data.dividends)) * Decimal("10000000000000")) tx = contract.functions.setDividendInformation( - _dividends, - data.dividend_record_date, - data.dividend_payment_date - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + _dividends, data.dividend_record_date, data.dividend_payment_date + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) try: ContractUtils.send_transaction(transaction=tx, private_key=private_key) except ContractRevertError: @@ -978,12 +1050,14 @@ def update(self, if data.cancellation_date is not None: tx = contract.functions.setCancellationDate( data.cancellation_date - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) try: ContractUtils.send_transaction(transaction=tx, private_key=private_key) except ContractRevertError: @@ -996,12 +1070,14 @@ def update(self, if data.contact_information is not None: tx = contract.functions.setContactInformation( data.contact_information - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) try: ContractUtils.send_transaction(transaction=tx, private_key=private_key) except ContractRevertError: @@ -1014,12 +1090,14 @@ def update(self, if data.privacy_policy is not None: tx = contract.functions.setPrivacyPolicy( data.privacy_policy - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) try: ContractUtils.send_transaction(transaction=tx, private_key=private_key) except ContractRevertError: @@ -1030,14 +1108,14 @@ def update(self, raise SendTransactionError(err) if data.status is not None: - tx = contract.functions.setStatus( - data.status - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = contract.functions.setStatus(data.status).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) try: ContractUtils.send_transaction(transaction=tx, private_key=private_key) except ContractRevertError: @@ -1050,12 +1128,14 @@ def update(self, if data.transferable is not None: tx = contract.functions.setTransferable( data.transferable - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) try: ContractUtils.send_transaction(transaction=tx, private_key=private_key) except ContractRevertError: @@ -1068,12 +1148,14 @@ def update(self, if data.is_offering is not None: tx = contract.functions.changeOfferingStatus( data.is_offering - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) try: ContractUtils.send_transaction(transaction=tx, private_key=private_key) except ContractRevertError: @@ -1086,12 +1168,14 @@ def update(self, if data.transfer_approval_required is not None: tx = contract.functions.setTransferApprovalRequired( data.transfer_approval_required - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) try: ContractUtils.send_transaction(transaction=tx, private_key=private_key) except ContractRevertError: @@ -1104,12 +1188,14 @@ def update(self, if data.principal_value is not None: tx = contract.functions.setPrincipalValue( data.principal_value - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) try: ContractUtils.send_transaction(transaction=tx, private_key=private_key) except ContractRevertError: @@ -1120,12 +1206,14 @@ def update(self, raise SendTransactionError(err) if data.is_canceled is not None and data.is_canceled: - tx = contract.functions.changeToCanceled().build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = contract.functions.changeToCanceled().build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) try: ContractUtils.send_transaction(transaction=tx, private_key=private_key) except ContractRevertError: @@ -1136,14 +1224,14 @@ def update(self, raise SendTransactionError(err) if data.memo is not None: - tx = contract.functions.setMemo( - data.memo - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = contract.functions.setMemo(data.memo).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) try: ContractUtils.send_transaction(transaction=tx, private_key=private_key) except ContractRevertError: diff --git a/app/model/blockchain/token_list.py b/app/model/blockchain/token_list.py index 9f4d0eab..8943a822 100644 --- a/app/model/blockchain/token_list.py +++ b/app/model/blockchain/token_list.py @@ -18,25 +18,21 @@ """ from web3.exceptions import TimeExhausted -from config import ( - CHAIN_ID, - TX_GAS_LIMIT -) -from app.exceptions import SendTransactionError, ContractRevertError +from app.exceptions import ContractRevertError, SendTransactionError from app.utils.contract_utils import ContractUtils from app.utils.web3_utils import Web3Wrapper +from config import CHAIN_ID, TX_GAS_LIMIT web3 = Web3Wrapper() class TokenListContract: - def __init__(self, contract_address: str): self.contract_address = contract_address - def register(self, - token_address: str, token_template: str, - tx_from: str, private_key: str) -> None: + def register( + self, token_address: str, token_template: str, tx_from: str, private_key: str + ) -> None: """Register TokenList :param token_address: token address @@ -51,18 +47,16 @@ def register(self, contract_address=self.contract_address, ) tx = contract.functions.register( - token_address, - token_template - ).build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) - ContractUtils.send_transaction( - transaction=tx, - private_key=private_key + token_address, token_template + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": tx_from, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } ) + ContractUtils.send_transaction(transaction=tx, private_key=private_key) except ContractRevertError: raise except TimeExhausted as timeout_error: diff --git a/app/model/blockchain/tx_params/ibet_security_token.py b/app/model/blockchain/tx_params/ibet_security_token.py index 07824804..50d511e7 100644 --- a/app/model/blockchain/tx_params/ibet_security_token.py +++ b/app/model/blockchain/tx_params/ibet_security_token.py @@ -16,11 +16,7 @@ SPDX-License-Identifier: Apache-2.0 """ -from pydantic import ( - validator, - BaseModel, - PositiveInt -) +from pydantic import BaseModel, PositiveInt, validator from web3 import Web3 diff --git a/app/model/blockchain/tx_params/ibet_share.py b/app/model/blockchain/tx_params/ibet_share.py index 7b634b83..a6474737 100644 --- a/app/model/blockchain/tx_params/ibet_share.py +++ b/app/model/blockchain/tx_params/ibet_share.py @@ -16,26 +16,25 @@ SPDX-License-Identifier: Apache-2.0 """ -from typing import ( - Optional -) import math +from typing import Optional -from pydantic import ( - validator, - BaseModel -) +from pydantic import BaseModel, validator from web3 import Web3 from .ibet_security_token import ( - TransferParams as IbetSecurityTokenTransferParams, AdditionalIssueParams as IbetSecurityTokenAdditionalIssueParams, - RedeemParams as IbetSecurityTokenRedeemParams, +) +from .ibet_security_token import ( ApproveTransferParams as IbetSecurityTokenApproveTransferParams, +) +from .ibet_security_token import ( CancelTransferParams as IbetSecurityTokenCancelTransferParams, - LockParams as IbetSecurityTokenLockParams, - ForceUnlockParams as IbetSecurityTokenForceUnlockParams ) +from .ibet_security_token import ForceUnlockParams as IbetSecurityTokenForceUnlockParams +from .ibet_security_token import LockParams as IbetSecurityTokenLockParams +from .ibet_security_token import RedeemParams as IbetSecurityTokenRedeemParams +from .ibet_security_token import TransferParams as IbetSecurityTokenTransferParams class UpdateParams(BaseModel): @@ -58,8 +57,8 @@ class UpdateParams(BaseModel): @validator("dividends") def dividends_13_decimal_places(cls, v): if v is not None: - float_data = float(v * 10 ** 13) - int_data = int(v * 10 ** 13) + float_data = float(v * 10**13) + int_data = int(v * 10**13) if not math.isclose(int_data, float_data): raise ValueError("dividends must be rounded to 13 decimal places") return v @@ -67,7 +66,9 @@ def dividends_13_decimal_places(cls, v): @validator("tradable_exchange_contract_address") def tradable_exchange_contract_address_is_valid_address(cls, v): if v is not None and not Web3.isAddress(v): - raise ValueError("tradable_exchange_contract_address is not a valid address") + raise ValueError( + "tradable_exchange_contract_address is not a valid address" + ) return v @validator("personal_info_contract_address") diff --git a/app/model/blockchain/tx_params/ibet_straight_bond.py b/app/model/blockchain/tx_params/ibet_straight_bond.py index cfd9d708..09b2b52e 100644 --- a/app/model/blockchain/tx_params/ibet_straight_bond.py +++ b/app/model/blockchain/tx_params/ibet_straight_bond.py @@ -16,26 +16,25 @@ SPDX-License-Identifier: Apache-2.0 """ -from typing import ( - Optional, List -) import math +from typing import List, Optional -from pydantic import ( - validator, - BaseModel -) +from pydantic import BaseModel, validator from web3 import Web3 from .ibet_security_token import ( - TransferParams as IbetSecurityTokenTransferParams, AdditionalIssueParams as IbetSecurityTokenAdditionalIssueParams, - RedeemParams as IbetSecurityTokenRedeemParams, +) +from .ibet_security_token import ( ApproveTransferParams as IbetSecurityTokenApproveTransferParams, +) +from .ibet_security_token import ( CancelTransferParams as IbetSecurityTokenCancelTransferParams, - LockParams as IbetSecurityTokenLockParams, - ForceUnlockParams as IbetSecurityTokenForceUnlockParams ) +from .ibet_security_token import ForceUnlockParams as IbetSecurityTokenForceUnlockParams +from .ibet_security_token import LockParams as IbetSecurityTokenLockParams +from .ibet_security_token import RedeemParams as IbetSecurityTokenRedeemParams +from .ibet_security_token import TransferParams as IbetSecurityTokenTransferParams class UpdateParams(BaseModel): @@ -57,8 +56,8 @@ class UpdateParams(BaseModel): @validator("interest_rate") def interest_rate_4_decimal_places(cls, v): if v is not None: - float_data = float(v * 10 ** 4) - int_data = int(v * 10 ** 4) + float_data = float(v * 10**4) + int_data = int(v * 10**4) if not math.isclose(int_data, float_data): raise ValueError("interest_rate must be rounded to 4 decimal places") return v @@ -66,13 +65,17 @@ def interest_rate_4_decimal_places(cls, v): @validator("interest_payment_date") def interest_payment_date_list_length_less_than_13(cls, v): if v is not None and len(v) >= 13: - raise ValueError("list length of interest_payment_date must be less than 13") + raise ValueError( + "list length of interest_payment_date must be less than 13" + ) return v @validator("tradable_exchange_contract_address") def tradable_exchange_contract_address_is_valid_address(cls, v): if v is not None and not Web3.isAddress(v): - raise ValueError("tradable_exchange_contract_address is not a valid address") + raise ValueError( + "tradable_exchange_contract_address is not a valid address" + ) return v @validator("personal_info_contract_address") diff --git a/app/model/db/__init__.py b/app/model/db/__init__.py index 14f2aaf7..ac065240 100644 --- a/app/model/db/__init__.py +++ b/app/model/db/__init__.py @@ -16,104 +16,64 @@ SPDX-License-Identifier: Apache-2.0 """ -from .base import Base -from .account import ( - Account, - AccountRsaKeyTemporary, - AccountRsaStatus -) +from .account import Account, AccountRsaKeyTemporary, AccountRsaStatus from .auth_token import AuthToken -from .token import ( - Token, - TokenAttrUpdate, - TokenType, - TokenCache -) -from .token_holders import ( - TokenHolder, - TokenHolderBatchStatus, - TokenHoldersList -) +from .base import Base from .batch_issue_redeem import ( - BatchIssueRedeemUpload, BatchIssueRedeem, - BatchIssueRedeemProcessingCategory + BatchIssueRedeemProcessingCategory, + BatchIssueRedeemUpload, ) from .batch_register_personal_info import ( + BatchRegisterPersonalInfo, BatchRegisterPersonalInfoUpload, BatchRegisterPersonalInfoUploadStatus, - BatchRegisterPersonalInfo, -) -from .bulk_transfer import ( - BulkTransferUpload, - BulkTransfer -) -from .e2e_messaging_account import ( - E2EMessagingAccount, - E2EMessagingAccountRsaKey -) -from .idx_block_data import ( - IDXBlockData, - IDXBlockDataBlockNumber -) -from .idx_e2e_messaging import ( - IDXE2EMessaging, - IDXE2EMessagingBlockNumber ) +from .bulk_transfer import BulkTransfer, BulkTransferUpload +from .e2e_messaging_account import E2EMessagingAccount, E2EMessagingAccountRsaKey +from .idx_block_data import IDXBlockData, IDXBlockDataBlockNumber +from .idx_e2e_messaging import IDXE2EMessaging, IDXE2EMessagingBlockNumber from .idx_issue_redeem import ( IDXIssueRedeem, + IDXIssueRedeemBlockNumber, IDXIssueRedeemEventType, IDXIssueRedeemSortItem, - IDXIssueRedeemBlockNumber ) -from .idx_lock_unlock import ( - IDXLock, - IDXUnlock +from .idx_lock_unlock import IDXLock, IDXUnlock +from .idx_personal_info import IDXPersonalInfo, IDXPersonalInfoBlockNumber +from .idx_position import ( + IDXLockedPosition, + IDXPosition, + IDXPositionBondBlockNumber, + IDXPositionShareBlockNumber, ) from .idx_transfer import ( IDXTransfer, IDXTransferBlockNumber, - IDXTransferSourceEventType + IDXTransferSourceEventType, ) from .idx_transfer_approval import ( IDXTransferApproval, + IDXTransferApprovalBlockNumber, IDXTransferApprovalsSortItem, - IDXTransferApprovalBlockNumber ) from .idx_tx_data import IDXTxData -from .idx_position import ( - IDXPosition, - IDXPositionBondBlockNumber, - IDXPositionShareBlockNumber, - IDXLockedPosition -) -from .idx_personal_info import ( - IDXPersonalInfo, - IDXPersonalInfoBlockNumber -) -from .update_token import UpdateToken -from .ledger import ( - Ledger, - LedgerDetailsData -) +from .ledger import Ledger, LedgerDetailsData from .ledger_template import ( - LedgerTemplate, + LedgerDetailsDataType, LedgerDetailsTemplate, - LedgerDetailsDataType + LedgerTemplate, ) from .node import Node -from .notification import ( - Notification, - NotificationType -) +from .notification import Notification, NotificationType +from .scheduled_events import ScheduledEvents, ScheduledEventType +from .token import Token, TokenAttrUpdate, TokenCache, TokenType +from .token_holders import TokenHolder, TokenHolderBatchStatus, TokenHoldersList from .transfer_appoval_history import ( TransferApprovalHistory, - TransferApprovalOperationType + TransferApprovalOperationType, ) from .tx_management import TransactionLock -from .utxo import UTXO, UTXOBlockNumber -from .scheduled_events import ( - ScheduledEvents, - ScheduledEventType -) +from .update_token import UpdateToken from .upload_file import UploadFile +from .utxo import UTXO, UTXOBlockNumber diff --git a/app/model/db/account.py b/app/model/db/account.py index d05d7881..c81c7ba3 100644 --- a/app/model/db/account.py +++ b/app/model/db/account.py @@ -18,19 +18,14 @@ """ from enum import Enum -from sqlalchemy import ( - Column, - JSON, - String, - Integer, - Boolean -) +from sqlalchemy import JSON, Boolean, Column, Integer, String from .base import Base class Account(Base): """Issuer Account""" + __tablename__ = "account" # issuer address @@ -58,6 +53,7 @@ class AccountRsaStatus(int, Enum): 2:CHANGING 3:SET """ + UNSET = 0 CREATING = 1 CHANGING = 2 @@ -66,6 +62,7 @@ class AccountRsaStatus(int, Enum): class AccountRsaKeyTemporary(Base): """Issuer Account (RSA Key Temporary Table)""" + __tablename__ = "account_rsa_key_temporary" # issuer address diff --git a/app/model/db/auth_token.py b/app/model/db/auth_token.py index a804abdc..ae83e26e 100644 --- a/app/model/db/auth_token.py +++ b/app/model/db/auth_token.py @@ -18,18 +18,14 @@ """ from datetime import datetime -from sqlalchemy import ( - Column, - String, - Integer, - DateTime -) +from sqlalchemy import Column, DateTime, Integer, String from .base import Base class AuthToken(Base): """Authentication Token""" + __tablename__ = "auth_token" # issuer address diff --git a/app/model/db/base.py b/app/model/db/base.py index d7977be7..1a409aee 100644 --- a/app/model/db/base.py +++ b/app/model/db/base.py @@ -17,12 +17,11 @@ SPDX-License-Identifier: Apache-2.0 """ -from datetime import datetime -from datetime import date as datetime_date import time +from datetime import date as datetime_date +from datetime import datetime -from sqlalchemy import Column -from sqlalchemy import DateTime +from sqlalchemy import Column, DateTime from sqlalchemy.orm import declarative_base from app.database import get_db_schema diff --git a/app/model/db/batch_issue_redeem.py b/app/model/db/batch_issue_redeem.py index ebbf13cb..9e193f8a 100644 --- a/app/model/db/batch_issue_redeem.py +++ b/app/model/db/batch_issue_redeem.py @@ -18,20 +18,15 @@ """ from enum import Enum -from sqlalchemy import ( - Column, - Integer, - String, - Boolean, - BigInteger -) +from sqlalchemy import BigInteger, Boolean, Column, Integer, String from .base import Base class BatchIssueRedeemUpload(Base): """Batch Issue/Redeem Upload""" - __tablename__ = 'batch_issue_redeem_upload' + + __tablename__ = "batch_issue_redeem_upload" # upload id (UUID) upload_id = Column(String(36), primary_key=True) @@ -49,12 +44,14 @@ class BatchIssueRedeemUpload(Base): class BatchIssueRedeemProcessingCategory(str, Enum): """Batch Issue/Redeem Category""" + ISSUE = "Issue" REDEEM = "Redeem" class BatchIssueRedeem(Base): """Batch Issue/Redeem Data""" + __tablename__ = "batch_issue_redeem" # sequence id diff --git a/app/model/db/batch_register_personal_info.py b/app/model/db/batch_register_personal_info.py index bd6c46d2..ef1b2192 100644 --- a/app/model/db/batch_register_personal_info.py +++ b/app/model/db/batch_register_personal_info.py @@ -17,12 +17,8 @@ SPDX-License-Identifier: Apache-2.0 """ from enum import Enum -from sqlalchemy import ( - Column, - Integer, - String, - JSON -) + +from sqlalchemy import JSON, Column, Integer, String from sqlalchemy.ext.hybrid import hybrid_property from .base import Base @@ -30,6 +26,7 @@ class BatchRegisterPersonalInfoUpload(Base): """Batch Register PersonalInfo Upload""" + __tablename__ = "batch_register_personal_info_upload" # upload id (UUID) @@ -42,6 +39,7 @@ class BatchRegisterPersonalInfoUpload(Base): class BatchRegisterPersonalInfoUploadStatus(str, Enum): """Batch Register PersonalInfo Upload Status""" + PENDING = "pending" DONE = "done" FAILED = "failed" @@ -49,6 +47,7 @@ class BatchRegisterPersonalInfoUploadStatus(str, Enum): class BatchRegisterPersonalInfo(Base): """Batch Register PersonalInfo""" + __tablename__ = "batch_register_personal_info" # sequence id @@ -86,7 +85,7 @@ def personal_info(self): "email": self._personal_info.get("email", None), "birth": self._personal_info.get("birth", None), "is_corporate": self._personal_info.get("is_corporate", None), - "tax_category": self._personal_info.get("tax_category", None) + "tax_category": self._personal_info.get("tax_category", None), } return self._personal_info @@ -100,5 +99,5 @@ def personal_info(self, personal_info_dict): "email": personal_info_dict.get("email", None), "birth": personal_info_dict.get("birth", None), "is_corporate": personal_info_dict.get("is_corporate", None), - "tax_category": personal_info_dict.get("tax_category", None) + "tax_category": personal_info_dict.get("tax_category", None), } diff --git a/app/model/db/bulk_transfer.py b/app/model/db/bulk_transfer.py index edfb387b..05507412 100644 --- a/app/model/db/bulk_transfer.py +++ b/app/model/db/bulk_transfer.py @@ -16,19 +16,15 @@ SPDX-License-Identifier: Apache-2.0 """ -from sqlalchemy import ( - Column, - Integer, - String, - BigInteger -) +from sqlalchemy import BigInteger, Column, Integer, String from .base import Base class BulkTransferUpload(Base): """Bulk Transfer Upload""" - __tablename__ = 'bulk_transfer_upload' + + __tablename__ = "bulk_transfer_upload" # upload id (UUID) upload_id = Column(String(36), primary_key=True) @@ -42,6 +38,7 @@ class BulkTransferUpload(Base): class BulkTransfer(Base): """Bulk Transfer""" + __tablename__ = "bulk_transfer" # sequence id diff --git a/app/model/db/e2e_messaging_account.py b/app/model/db/e2e_messaging_account.py index 0db6c0be..0b559829 100644 --- a/app/model/db/e2e_messaging_account.py +++ b/app/model/db/e2e_messaging_account.py @@ -16,22 +16,15 @@ SPDX-License-Identifier: Apache-2.0 """ -from sqlalchemy import Column -from sqlalchemy import ( - String, - JSON, - Integer, - Boolean, - BigInteger, - DateTime -) +from sqlalchemy import JSON, BigInteger, Boolean, Column, DateTime, Integer, String from .base import Base class E2EMessagingAccount(Base): """E2E Messaging Account""" - __tablename__ = 'e2e_messaging_account' + + __tablename__ = "e2e_messaging_account" # account address account_address = Column(String(42), primary_key=True) @@ -49,7 +42,8 @@ class E2EMessagingAccount(Base): class E2EMessagingAccountRsaKey(Base): """E2E Messaging Account Rsa Key""" - __tablename__ = 'e2e_messaging_account_rsa_key' + + __tablename__ = "e2e_messaging_account_rsa_key" id = Column(BigInteger, primary_key=True, autoincrement=True) # transaction hash diff --git a/app/model/db/idx_block_data.py b/app/model/db/idx_block_data.py index 12b72f1b..cb6dfd1f 100644 --- a/app/model/db/idx_block_data.py +++ b/app/model/db/idx_block_data.py @@ -16,20 +16,14 @@ SPDX-License-Identifier: Apache-2.0 """ -from sqlalchemy import ( - Column, - String, - BigInteger, - Integer, - Text, - JSON -) +from sqlalchemy import JSON, BigInteger, Column, Integer, String, Text from .base import Base class IDXBlockData(Base): """Block data (INDEX)""" + __tablename__ = "block_data" # Header data @@ -57,6 +51,7 @@ class IDXBlockData(Base): class IDXBlockDataBlockNumber(Base): """Synchronized blockNumber of IDXBlockData""" + __tablename__ = "idx_block_data_block_number" # Chain id diff --git a/app/model/db/idx_e2e_messaging.py b/app/model/db/idx_e2e_messaging.py index 77df6d6e..09d886cb 100644 --- a/app/model/db/idx_e2e_messaging.py +++ b/app/model/db/idx_e2e_messaging.py @@ -16,19 +16,15 @@ SPDX-License-Identifier: Apache-2.0 """ -from sqlalchemy import Column -from sqlalchemy import ( - BigInteger, - String, - DateTime -) +from sqlalchemy import BigInteger, Column, DateTime, String from .base import Base class IDXE2EMessaging(Base): """INDEX E2E Message""" - __tablename__ = 'idx_e2e_messaging' + + __tablename__ = "idx_e2e_messaging" id = Column(BigInteger, primary_key=True, autoincrement=True) # transaction hash @@ -49,10 +45,9 @@ class IDXE2EMessaging(Base): class IDXE2EMessagingBlockNumber(Base): """Synchronized blockNumber of IDXE2EMessaging""" + __tablename__ = "idx_e2e_messaging_block_number" id = Column(BigInteger, primary_key=True, autoincrement=True) # latest blockNumber latest_block_number = Column(BigInteger) - - diff --git a/app/model/db/idx_issue_redeem.py b/app/model/db/idx_issue_redeem.py index 7ab4d5d7..cc462c86 100644 --- a/app/model/db/idx_issue_redeem.py +++ b/app/model/db/idx_issue_redeem.py @@ -18,18 +18,14 @@ """ from enum import Enum -from sqlalchemy import ( - Column, - BigInteger, - String, - DateTime -) +from sqlalchemy import BigInteger, Column, DateTime, String from .base import Base class IDXIssueRedeem(Base): """INDEX Issue/Redeem""" + __tablename__ = "idx_issue_redeem" id = Column(BigInteger, primary_key=True, autoincrement=True) @@ -51,12 +47,14 @@ class IDXIssueRedeem(Base): class IDXIssueRedeemEventType(str, Enum): """Issue/Redeem event type""" + ISSUE = "Issue" REDEEM = "Redeem" class IDXIssueRedeemSortItem(str, Enum): """Issue/Redeem sort item""" + BLOCK_TIMESTAMP = "block_timestamp" LOCKED_ADDRESS = "locked_address" TARGET_ADDRESS = "target_address" @@ -65,6 +63,7 @@ class IDXIssueRedeemSortItem(str, Enum): class IDXIssueRedeemBlockNumber(Base): """Synchronized blockNumber of IDXIssueRedeem""" + __tablename__ = "idx_issue_redeem_block_number" # sequence id diff --git a/app/model/db/idx_lock_unlock.py b/app/model/db/idx_lock_unlock.py index ca4e09df..7c1fa82f 100644 --- a/app/model/db/idx_lock_unlock.py +++ b/app/model/db/idx_lock_unlock.py @@ -16,19 +16,14 @@ SPDX-License-Identifier: Apache-2.0 """ -from sqlalchemy import ( - Column, - String, - BigInteger, - JSON, - DateTime -) +from sqlalchemy import JSON, BigInteger, Column, DateTime, String from .base import Base class IDXLock(Base): """Token Lock Event (INDEX)""" + __tablename__ = "idx_lock" # Sequence Id @@ -53,6 +48,7 @@ class IDXLock(Base): class IDXUnlock(Base): """Token Unlock Event (INDEX)""" + __tablename__ = "idx_unlock" # Sequence Id diff --git a/app/model/db/idx_personal_info.py b/app/model/db/idx_personal_info.py index aff6c44c..b1a37ddb 100644 --- a/app/model/db/idx_personal_info.py +++ b/app/model/db/idx_personal_info.py @@ -16,12 +16,7 @@ SPDX-License-Identifier: Apache-2.0 """ -from sqlalchemy import ( - Column, - BigInteger, - String, - JSON -) +from sqlalchemy import JSON, BigInteger, Column, String from sqlalchemy.ext.hybrid import hybrid_property from .base import Base @@ -29,7 +24,8 @@ class IDXPersonalInfo(Base): """INDEX Personal information of the token holder (decrypted)""" - __tablename__ = 'idx_personal_info' + + __tablename__ = "idx_personal_info" id = Column(BigInteger, primary_key=True, autoincrement=True) # account address @@ -47,7 +43,7 @@ class IDXPersonalInfo(Base): # "is_corporate": "boolean", # "tax_category": "integer" # } - _personal_info = Column('personal_info', JSON, nullable=False) + _personal_info = Column("personal_info", JSON, nullable=False) @hybrid_property def personal_info(self): @@ -60,7 +56,7 @@ def personal_info(self): "email": self._personal_info.get("email", None), "birth": self._personal_info.get("birth", None), "is_corporate": self._personal_info.get("is_corporate", None), - "tax_category": self._personal_info.get("tax_category", None) + "tax_category": self._personal_info.get("tax_category", None), } return self._personal_info @@ -74,12 +70,13 @@ def personal_info(self, personal_info_dict): "email": personal_info_dict.get("email", None), "birth": personal_info_dict.get("birth", None), "is_corporate": personal_info_dict.get("is_corporate", None), - "tax_category": personal_info_dict.get("tax_category", None) + "tax_category": personal_info_dict.get("tax_category", None), } class IDXPersonalInfoBlockNumber(Base): """Synchronized blockNumber of IDXPersonalInfo""" + __tablename__ = "idx_personal_info_block_number" id = Column(BigInteger, primary_key=True, autoincrement=True) diff --git a/app/model/db/idx_position.py b/app/model/db/idx_position.py index 28241bfa..5b7a4fca 100644 --- a/app/model/db/idx_position.py +++ b/app/model/db/idx_position.py @@ -16,18 +16,15 @@ SPDX-License-Identifier: Apache-2.0 """ -from sqlalchemy import ( - Column, - String, - BigInteger -) +from sqlalchemy import BigInteger, Column, String from .base import Base class IDXPosition(Base): """INDEX Position""" - __tablename__ = 'idx_position' + + __tablename__ = "idx_position" id = Column(BigInteger, primary_key=True, autoincrement=True) # token address @@ -49,12 +46,13 @@ def json(self): "balance": self.balance, "exchange_balance": self.exchange_balance, "exchange_commitment": self.exchange_commitment, - "pending_transfer": self.pending_transfer + "pending_transfer": self.pending_transfer, } class IDXPositionBondBlockNumber(Base): """Synchronized blockNumber of IDXPosition(Bond token)""" + __tablename__ = "idx_position_bond_block_number" # sequence id @@ -65,6 +63,7 @@ class IDXPositionBondBlockNumber(Base): class IDXPositionShareBlockNumber(Base): """Synchronized blockNumber of IDXPosition(Share token)""" + __tablename__ = "idx_position_share_block_number" # sequence id @@ -75,6 +74,7 @@ class IDXPositionShareBlockNumber(Base): class IDXLockedPosition(Base): """INDEX Locked Position""" + __tablename__ = "idx_locked_position" # token address @@ -91,5 +91,5 @@ def json(self): "token_address": self.token_address, "lock_address": self.lock_address, "account_address": self.account_address, - "value": self.value + "value": self.value, } diff --git a/app/model/db/idx_transfer.py b/app/model/db/idx_transfer.py index 28690514..5fff5337 100644 --- a/app/model/db/idx_transfer.py +++ b/app/model/db/idx_transfer.py @@ -18,25 +18,21 @@ """ from enum import Enum -from sqlalchemy import ( - Column, - BigInteger, - String, - DateTime, - JSON -) +from sqlalchemy import JSON, BigInteger, Column, DateTime, String from .base import Base class IDXTransferSourceEventType(str, Enum): """Transfer source event type""" + TRANSFER = "Transfer" UNLOCK = "Unlock" class IDXTransfer(Base): """INDEX Transfer""" + __tablename__ = "idx_transfer" id = Column(BigInteger, primary_key=True, autoincrement=True) @@ -60,6 +56,7 @@ class IDXTransfer(Base): class IDXTransferBlockNumber(Base): """Synchronized blockNumber of IDXTransfer""" + __tablename__ = "idx_transfer_block_number" # sequence id diff --git a/app/model/db/idx_transfer_approval.py b/app/model/db/idx_transfer_approval.py index 692a445a..9509ad50 100644 --- a/app/model/db/idx_transfer_approval.py +++ b/app/model/db/idx_transfer_approval.py @@ -18,28 +18,26 @@ """ from enum import Enum -from sqlalchemy import ( - Boolean, - Column, - DateTime, - String, - BigInteger -) +from sqlalchemy import BigInteger, Boolean, Column, DateTime, String import config + from .base import Base class IDXTransferApproval(Base): """INDEX Transfer Approval""" - __tablename__ = 'idx_transfer_approval' + + __tablename__ = "idx_transfer_approval" # Sequence Id id = Column(BigInteger, primary_key=True, autoincrement=True) # Token Address token_address = Column(String(42), index=True, nullable=False) # Exchange Address (value is set if the event is from exchange) - exchange_address = Column(String(42), index=True, nullable=False, default=config.ZERO_ADDRESS) + exchange_address = Column( + String(42), index=True, nullable=False, default=config.ZERO_ADDRESS + ) # Application ID (escrow id is set if the event is from exchange) application_id = Column(BigInteger, index=True, nullable=False) # Transfer From @@ -77,7 +75,7 @@ def json(self): "approval_blocktimestamp": self.approval_blocktimestamp, "cancelled": self.cancelled, "escrow_finished": self.escrow_finished, - "transfer_approved": self.transfer_approved + "transfer_approved": self.transfer_approved, } @@ -95,6 +93,7 @@ class IDXTransferApprovalsSortItem(str, Enum): class IDXTransferApprovalBlockNumber(Base): """Synchronized blockNumber of IDXTransferApproval""" + __tablename__ = "idx_transfer_approval_block_number" # sequence id diff --git a/app/model/db/idx_tx_data.py b/app/model/db/idx_tx_data.py index 64082cf8..10858888 100644 --- a/app/model/db/idx_tx_data.py +++ b/app/model/db/idx_tx_data.py @@ -16,19 +16,14 @@ SPDX-License-Identifier: Apache-2.0 """ -from sqlalchemy import ( - Column, - String, - BigInteger, - Integer, - Text -) +from sqlalchemy import BigInteger, Column, Integer, String, Text from .base import Base class IDXTxData(Base): """Transaction data (INDEX)""" + __tablename__ = "tx_data" hash = Column(String(66), primary_key=True) diff --git a/app/model/db/ledger.py b/app/model/db/ledger.py index 1e6ec05e..9246bfca 100644 --- a/app/model/db/ledger.py +++ b/app/model/db/ledger.py @@ -18,20 +18,14 @@ """ from datetime import datetime -from sqlalchemy import ( - Column, - Integer, - BigInteger, - String, - JSON, - DateTime -) +from sqlalchemy import JSON, BigInteger, Column, DateTime, Integer, String from .base import Base class Ledger(Base): """Ledger""" + __tablename__ = "ledger" # sequence id @@ -79,6 +73,7 @@ class Ledger(Base): class LedgerDetailsData(Base): """Ledger Details Data""" + __tablename__ = "ledger_details_data" # sequence id diff --git a/app/model/db/ledger_template.py b/app/model/db/ledger_template.py index 1270f117..e29d6a33 100644 --- a/app/model/db/ledger_template.py +++ b/app/model/db/ledger_template.py @@ -18,18 +18,14 @@ """ from enum import Enum -from sqlalchemy import ( - Column, - Integer, - String, - JSON -) +from sqlalchemy import JSON, Column, Integer, String from .base import Base class LedgerTemplate(Base): """Ledger Template""" + __tablename__ = "ledger_template" # token address @@ -46,6 +42,7 @@ class LedgerTemplate(Base): class LedgerDetailsTemplate(Base): """Ledger Details Template""" + __tablename__ = "ledger_details_template" # sequence id diff --git a/app/model/db/node.py b/app/model/db/node.py index 72516472..5be8c8a9 100644 --- a/app/model/db/node.py +++ b/app/model/db/node.py @@ -16,18 +16,14 @@ SPDX-License-Identifier: Apache-2.0 """ -from sqlalchemy import ( - Column, - Integer, - String, - Boolean -) +from sqlalchemy import Boolean, Column, Integer, String from .base import Base class Node(Base): """Ethereum Node Information""" + __tablename__ = "node" id = Column(Integer, primary_key=True, autoincrement=True) @@ -36,4 +32,4 @@ class Node(Base): # connect priority(top priority is lower number) priority = Column(Integer) # node synchronized status - is_synced = Column(Boolean, nullable=False) \ No newline at end of file + is_synced = Column(Boolean, nullable=False) diff --git a/app/model/db/notification.py b/app/model/db/notification.py index ccf8e775..ce6ff2db 100644 --- a/app/model/db/notification.py +++ b/app/model/db/notification.py @@ -17,12 +17,8 @@ SPDX-License-Identifier: Apache-2.0 """ from enum import Enum -from sqlalchemy import ( - Column, - Integer, - String, - JSON -) + +from sqlalchemy import JSON, Column, Integer, String from .base import Base @@ -71,6 +67,7 @@ class Notification(Base): """Notification""" + __tablename__ = "notification" # sequence id diff --git a/app/model/db/scheduled_events.py b/app/model/db/scheduled_events.py index e5ae98ac..3bb31e66 100644 --- a/app/model/db/scheduled_events.py +++ b/app/model/db/scheduled_events.py @@ -16,19 +16,14 @@ # SPDX-License-Identifier: Apache-2.0 from enum import Enum -from sqlalchemy import ( - Column, - Integer, - String, - DateTime, - JSON -) +from sqlalchemy import JSON, Column, DateTime, Integer, String from .base import Base class ScheduledEvents(Base): """Scheduled Event""" + __tablename__ = "scheduled_events" # sequence id diff --git a/app/model/db/token.py b/app/model/db/token.py index 155f5745..438f274c 100644 --- a/app/model/db/token.py +++ b/app/model/db/token.py @@ -19,19 +19,14 @@ from datetime import datetime from enum import Enum -from sqlalchemy import ( - Column, - Integer, - String, - JSON, - DateTime -) +from sqlalchemy import JSON, Column, DateTime, Integer, String from .base import Base class Token(Base): """Issued Token""" + __tablename__ = "token" id = Column(Integer, primary_key=True, autoincrement=True) @@ -51,6 +46,7 @@ class Token(Base): class TokenAttrUpdate(Base): """Managed Token Attribute Update""" + __tablename__ = "token_attr_update" # sequence id @@ -68,6 +64,7 @@ class TokenType(str, Enum): class TokenCache(Base): """Token Cache""" + __tablename__ = "token_cache" # token address diff --git a/app/model/db/token_holders.py b/app/model/db/token_holders.py index 2edbe693..b338ca5c 100644 --- a/app/model/db/token_holders.py +++ b/app/model/db/token_holders.py @@ -18,7 +18,7 @@ """ from enum import Enum -from sqlalchemy import Column, String, BigInteger +from sqlalchemy import BigInteger, Column, String from .base import Base @@ -63,5 +63,5 @@ def json(self): return { "account_address": self.account_address, "hold_balance": self.hold_balance, - "locked_balance": self.locked_balance + "locked_balance": self.locked_balance, } diff --git a/app/model/db/transfer_appoval_history.py b/app/model/db/transfer_appoval_history.py index 0723e056..f9eb79f4 100644 --- a/app/model/db/transfer_appoval_history.py +++ b/app/model/db/transfer_appoval_history.py @@ -18,18 +18,15 @@ """ from enum import Enum -from sqlalchemy import ( - BigInteger, - Column, - String -) +from sqlalchemy import BigInteger, Column, String from .base import Base class TransferApprovalHistory(Base): """Token Transfer Approval Operation History""" - __tablename__ = 'transfer_approval_history' + + __tablename__ = "transfer_approval_history" # Sequence Id id = Column(BigInteger, primary_key=True, autoincrement=True) diff --git a/app/model/db/tx_management.py b/app/model/db/tx_management.py index 4493971b..5ebe5d82 100644 --- a/app/model/db/tx_management.py +++ b/app/model/db/tx_management.py @@ -16,16 +16,14 @@ SPDX-License-Identifier: Apache-2.0 """ -from sqlalchemy import ( - Column, - String -) +from sqlalchemy import Column, String from .base import Base class TransactionLock(Base): """Transaction Lock""" + __tablename__ = "tx_management" # transaction from diff --git a/app/model/db/update_token.py b/app/model/db/update_token.py index 3b78f7e0..a9172383 100644 --- a/app/model/db/update_token.py +++ b/app/model/db/update_token.py @@ -16,18 +16,14 @@ SPDX-License-Identifier: Apache-2.0 """ -from sqlalchemy import ( - Column, - Integer, - String, - JSON -) +from sqlalchemy import JSON, Column, Integer, String from .base import Base class UpdateToken(Base): """Update Token""" + __tablename__ = "update_token" id = Column(Integer, primary_key=True, autoincrement=True) diff --git a/app/model/db/upload_file.py b/app/model/db/upload_file.py index 5037273d..304a1c48 100644 --- a/app/model/db/upload_file.py +++ b/app/model/db/upload_file.py @@ -16,18 +16,14 @@ SPDX-License-Identifier: Apache-2.0 """ -from sqlalchemy import ( - Column, - String, - Integer, - LargeBinary -) +from sqlalchemy import Column, Integer, LargeBinary, String from .base import Base class UploadFile(Base): """Upload File""" + __tablename__ = "upload_file" # file id (UUID) diff --git a/app/model/db/utxo.py b/app/model/db/utxo.py index 378cefb3..b7c395c1 100644 --- a/app/model/db/utxo.py +++ b/app/model/db/utxo.py @@ -16,18 +16,14 @@ SPDX-License-Identifier: Apache-2.0 """ -from sqlalchemy import ( - Column, - String, - BigInteger, - DateTime -) +from sqlalchemy import BigInteger, Column, DateTime, String from .base import Base class UTXO(Base): """UTXO""" + # NOTE: When consuming amount, consume(subtract) in order from old records. __tablename__ = "utxo" @@ -48,6 +44,7 @@ class UTXO(Base): class UTXOBlockNumber(Base): """Synchronized blockNumber of UTXO""" + __tablename__ = "utxo_block_number" # sequence id diff --git a/app/model/schema/__init__.py b/app/model/schema/__init__.py index c8530f01..cfd15bf7 100644 --- a/app/model/schema/__init__.py +++ b/app/model/schema/__init__.py @@ -17,156 +17,120 @@ SPDX-License-Identifier: Apache-2.0 """ from .account import ( - # Request - AccountCreateKeyRequest, - AccountGenerateRsaKeyRequest, + AccountAuthTokenRequest, + AccountAuthTokenResponse, AccountChangeEOAPasswordRequest, AccountChangeRSAPassphraseRequest, - AccountAuthTokenRequest, - # Response + AccountCreateKeyRequest, + AccountGenerateRsaKeyRequest, AccountResponse, - AccountAuthTokenResponse ) from .batch_issue_redeem import ( - # Response BatchIssueRedeemUploadIdResponse, GetBatchIssueRedeemResponse, GetBatchIssueRedeemResult, - ListBatchIssueRedeemUploadResponse + ListBatchIssueRedeemUploadResponse, ) from .bc_explorer import ( - # Request + BlockDataDetail, + BlockDataListResponse, + BlockDataResponse, ListBlockDataQuery, ListTxDataQuery, - # Response - BlockDataResponse, - BlockDataListResponse, - BlockDataDetail, - TxDataResponse, + TxDataDetail, TxDataListResponse, - TxDataDetail + TxDataResponse, ) from .bulk_transfer import ( - # Response + BulkTransferResponse, BulkTransferUploadIdResponse, BulkTransferUploadResponse, - BulkTransferResponse ) from .e2e_messaging import ( - # Request - E2EMessagingAccountCreateRequest, - E2EMessagingAccountUpdateRsaKeyRequest, E2EMessagingAccountChangeEOAPasswordRequest, E2EMessagingAccountChangeRSAPassphraseRequest, - # Response + E2EMessagingAccountCreateRequest, E2EMessagingAccountResponse, + E2EMessagingAccountUpdateRsaKeyRequest, E2EMessagingResponse, - ListAllE2EMessagingResponse + ListAllE2EMessagingResponse, ) from .file import ( - # Request - UploadFileRequest, - # Response + DownloadFileResponse, FileResponse, ListAllFilesResponse, - DownloadFileResponse -) -from .holder import ( - # Response - HolderResponse, - HolderCountResponse -) -from .index import ( - # Response - E2EEResponse, - BlockNumberResponse -) -from .issue_redeem import ( - # Response - IssueRedeemEvent, - IssueRedeemHistoryResponse + UploadFileRequest, ) +from .holder import HolderCountResponse, HolderResponse +from .index import BlockNumberResponse, E2EEResponse +from .issue_redeem import IssueRedeemEvent, IssueRedeemHistoryResponse from .ledger import ( - # Request - CreateUpdateLedgerTemplateRequest, CreateUpdateLedgerDetailsDataRequest, - # Response - ListAllLedgerHistoryResponse, - RetrieveLedgerHistoryResponse, + CreateUpdateLedgerTemplateRequest, + LedgerDetailsDataResponse, LedgerTemplateResponse, ListAllLedgerDetailsDataResponse, - LedgerDetailsDataResponse, - RetrieveLedgerDetailsDataResponse + ListAllLedgerHistoryResponse, + RetrieveLedgerDetailsDataResponse, + RetrieveLedgerHistoryResponse, ) from .notification import ListAllNotificationsResponse from .personal_info import ( - # Request - RegisterPersonalInfoRequest, - # Response + BatchRegisterPersonalInfoResult, BatchRegisterPersonalInfoUploadResponse, - ListBatchRegisterPersonalInfoUploadResponse, GetBatchRegisterPersonalInfoResponse, - BatchRegisterPersonalInfoResult + ListBatchRegisterPersonalInfoUploadResponse, + RegisterPersonalInfoRequest, ) from .position import ( - # Request - LockEventCategory, - ListAllLockEventsSortItem, - ListAllLockEventsQuery, ForceUnlockRequest, - # Response - PositionResponse, - ListAllPositionResponse, ListAllLockedPositionResponse, - ListAllLockEventsResponse + ListAllLockEventsQuery, + ListAllLockEventsResponse, + ListAllLockEventsSortItem, + ListAllPositionResponse, + LockEventCategory, + PositionResponse, ) from .scheduled_events import ( - # Request - IbetStraightBondScheduledUpdate, IbetShareScheduledUpdate, - # Response + IbetStraightBondScheduledUpdate, ScheduledEventIdResponse, - ScheduledEventResponse + ScheduledEventResponse, ) from .token import ( - # Request - IbetStraightBondCreate, - IbetStraightBondUpdate, - IbetStraightBondTransfer, - IbetStraightBondAdditionalIssue, - IbetStraightBondRedeem, - IbetShareCreate, - IbetShareUpdate, - IbetShareTransfer, IbetShareAdditionalIssue, + IbetShareCreate, IbetShareRedeem, + IbetShareResponse, + IbetShareTransfer, + IbetShareUpdate, + IbetStraightBondAdditionalIssue, + IbetStraightBondCreate, + IbetStraightBondRedeem, + IbetStraightBondResponse, + IbetStraightBondTransfer, + IbetStraightBondUpdate, ListAllTokenLockEventsQuery, + ListAllTokenLockEventsResponse, ListAllTokenLockEventsSortItem, - # Response TokenAddressResponse, - IbetStraightBondResponse, - IbetShareResponse, - ListAllTokenLockEventsResponse ) from .token_holders import ( - # Request CreateTokenHoldersListRequest, - # Response CreateTokenHoldersListResponse, + ListAllTokenHolderCollectionsResponse, RetrieveTokenHoldersListResponse, - ListAllTokenHolderCollectionsResponse ) from .transfer import ( - # Request - UpdateTransferApprovalRequest, - UpdateTransferApprovalOperationType, - ListTransferHistorySortItem, ListTransferHistoryQuery, - # Response - TransferResponse, - TransferHistoryResponse, + ListTransferHistorySortItem, + TransferApprovalHistoryResponse, TransferApprovalsResponse, TransferApprovalTokenResponse, - TransferApprovalHistoryResponse + TransferHistoryResponse, + TransferResponse, + UpdateTransferApprovalOperationType, + UpdateTransferApprovalRequest, ) from .types import ResultSet diff --git a/app/model/schema/account.py b/app/model/schema/account.py index 5a075a8e..514b53a3 100644 --- a/app/model/schema/account.py +++ b/app/model/schema/account.py @@ -18,15 +18,12 @@ """ from datetime import datetime from typing import Optional -from pydantic import ( - BaseModel, - validator, - Field -) -from config import E2EE_REQUEST_ENABLED -from app.utils.check_utils import check_value_is_encrypted +from pydantic import BaseModel, Field, validator + from app.model.db import AccountRsaStatus +from app.utils.check_utils import check_value_is_encrypted +from config import E2EE_REQUEST_ENABLED ############################ @@ -34,6 +31,7 @@ ############################ class AccountCreateKeyRequest(BaseModel): """Account Create Key schema (REQUEST)""" + eoa_password: str @validator("eoa_password") @@ -45,6 +43,7 @@ def eoa_password_is_encrypted_value(cls, v): class AccountGenerateRsaKeyRequest(BaseModel): """Account Change Rsa Key schema (REQUEST)""" + rsa_passphrase: Optional[str] @validator("rsa_passphrase") @@ -56,6 +55,7 @@ def rsa_passphrase_is_encrypted_value(cls, v): class AccountChangeEOAPasswordRequest(BaseModel): """Account Change EOA Password schema (REQUEST)""" + old_eoa_password: str eoa_password: str @@ -74,6 +74,7 @@ def eoa_password_is_encrypted_value(cls, v): class AccountChangeRSAPassphraseRequest(BaseModel): """Account Change RSA Passphrase schema (REQUEST)""" + old_rsa_passphrase: str rsa_passphrase: str @@ -92,15 +93,20 @@ def rsa_passphrase_is_encrypted_value(cls, v): class AccountAuthTokenRequest(BaseModel): """Account Create Auth Token schema (REQUEST)""" - valid_duration: int = Field(None, ge=0, le=259200) # The maximum valid duration shall be 3 days. + + valid_duration: int = Field( + None, ge=0, le=259200 + ) # The maximum valid duration shall be 3 days. ############################ # RESPONSE ############################ + class AccountResponse(BaseModel): """Account schema (Response)""" + issuer_address: str rsa_public_key: Optional[str] rsa_status: AccountRsaStatus @@ -109,6 +115,7 @@ class AccountResponse(BaseModel): class AccountAuthTokenResponse(BaseModel): """Account Auth Token schema (RESPONSE)""" + auth_token: str usage_start: datetime valid_duration: int diff --git a/app/model/schema/batch_issue_redeem.py b/app/model/schema/batch_issue_redeem.py index f5f227b2..e3a6bdad 100644 --- a/app/model/schema/batch_issue_redeem.py +++ b/app/model/schema/batch_issue_redeem.py @@ -17,21 +17,21 @@ SPDX-License-Identifier: Apache-2.0 """ from typing import List -from pydantic import ( - BaseModel, - Field -) -from .types import ResultSet +from pydantic import BaseModel, Field + from app.model.db import TokenType +from .types import ResultSet ############################ # RESPONSE ############################ + class BatchIssueRedeemUpload(BaseModel): """Batch issue/redeem Upload""" + batch_id: str = Field(description="UUID v4 required") issuer_address: str token_type: TokenType @@ -47,24 +47,27 @@ class Config: "token_type": "Bond", "token_address": "0x0000000000000000000000000000000000000000", "processed": True, - "created": "2022-09-02T19:49:33.370874+09:00" + "created": "2022-09-02T19:49:33.370874+09:00", } } class ListBatchIssueRedeemUploadResponse(BaseModel): """List All Batch issue/redeem Upload(RESPONSE)""" + result_set: ResultSet uploads: List[BatchIssueRedeemUpload] class BatchIssueRedeemUploadIdResponse(BaseModel): """Batch issue/redeem upload id (RESPONSE)""" + batch_id: str class GetBatchIssueRedeemResult(BaseModel): """Result of Creating Batch issue/redeem schema (RESPONSE)""" + account_address: str amount: int status: int @@ -72,5 +75,6 @@ class GetBatchIssueRedeemResult(BaseModel): class GetBatchIssueRedeemResponse(BaseModel): """Get Batch issue/redeem upload schema (RESPONSE)""" + processed: bool results: List[GetBatchIssueRedeemResult] diff --git a/app/model/schema/bc_explorer.py b/app/model/schema/bc_explorer.py index 3233ebfa..142b0621 100644 --- a/app/model/schema/bc_explorer.py +++ b/app/model/schema/bc_explorer.py @@ -19,25 +19,17 @@ from typing import Optional from fastapi import Query -from pydantic import ( - BaseModel, - Field, - NonNegativeInt, - validator -) +from pydantic import BaseModel, Field, NonNegativeInt, validator from pydantic.dataclasses import dataclass from web3 import Web3 -from .types import ( - ResultSet, - SortOrder -) - +from .types import ResultSet, SortOrder ############################ # COMMON ############################ + class BlockData(BaseModel): number: NonNegativeInt = Field(description="Block number") hash: str = Field(description="Block hash") @@ -98,20 +90,25 @@ class TxDataDetail(BaseModel): # REQUEST ############################ + @dataclass class ListBlockDataQuery: offset: Optional[NonNegativeInt] = Query(default=None, description="start position") limit: Optional[NonNegativeInt] = Query(default=None, description="number of set") from_block_number: Optional[NonNegativeInt] = Query(default=None) to_block_number: Optional[NonNegativeInt] = Query(default=None) - sort_order: Optional[SortOrder] = Query(default=SortOrder.ASC, description="sort order(0: ASC, 1: DESC)") + sort_order: Optional[SortOrder] = Query( + default=SortOrder.ASC, description="sort order(0: ASC, 1: DESC)" + ) @dataclass class ListTxDataQuery: offset: Optional[NonNegativeInt] = Query(default=None, description="start position") limit: Optional[NonNegativeInt] = Query(default=None, description="number of set") - block_number: Optional[NonNegativeInt] = Query(default=None, description="block number") + block_number: Optional[NonNegativeInt] = Query( + default=None, description="block number" + ) from_address: Optional[str] = Query(default=None, description="tx from") to_address: Optional[str] = Query(default=None, description="tx to") @@ -134,6 +131,7 @@ def to_address_is_valid_address(cls, v): # RESPONSE ############################ + class BlockDataResponse(BaseModel): __root__: BlockDataDetail diff --git a/app/model/schema/bulk_transfer.py b/app/model/schema/bulk_transfer.py index ff93d5c2..5f8a2d33 100644 --- a/app/model/schema/bulk_transfer.py +++ b/app/model/schema/bulk_transfer.py @@ -20,18 +20,20 @@ from app.model.db import TokenType - ############################ # RESPONSE ############################ + class BulkTransferUploadIdResponse(BaseModel): """bulk transfer upload id""" + upload_id: str class BulkTransferUploadResponse(BaseModel): """bulk transfer upload""" + upload_id: str issuer_address: str token_type: TokenType @@ -41,6 +43,7 @@ class BulkTransferUploadResponse(BaseModel): class BulkTransferResponse(BaseModel): """bulk transfer data""" + upload_id: str issuer_address: str token_address: str diff --git a/app/model/schema/e2e_messaging.py b/app/model/schema/e2e_messaging.py index 30ad22fd..6fb18221 100644 --- a/app/model/schema/e2e_messaging.py +++ b/app/model/schema/e2e_messaging.py @@ -17,23 +17,14 @@ SPDX-License-Identifier: Apache-2.0 """ from datetime import datetime -from typing import ( - Optional, - List, - Union, - Dict, - Any -) - -from pydantic import ( - BaseModel, - validator, - Field -) +from typing import Any, Dict, List, Optional, Union + +from pydantic import BaseModel, Field, validator -from .types import ResultSet -from config import E2EE_REQUEST_ENABLED from app.utils.check_utils import check_value_is_encrypted +from config import E2EE_REQUEST_ENABLED + +from .types import ResultSet ############################ @@ -41,6 +32,7 @@ ############################ class E2EMessagingAccountCreateRequest(BaseModel): """E2E Messaging Account Create schema (REQUEST)""" + eoa_password: str rsa_passphrase: Optional[str] rsa_key_generate_interval: Optional[int] = Field(24, ge=0, le=10_000) @@ -61,28 +53,38 @@ def rsa_passphrase_is_encrypted_value(cls, v): class Config: @staticmethod def schema_extra(schema: Dict[str, Any], _) -> None: - rsa_key_generate_interval_schema = schema["properties"]["rsa_key_generate_interval"] - rsa_key_generate_interval_schema["description"] = "0 disables auto-generate(Unit is hour)" + rsa_key_generate_interval_schema = schema["properties"][ + "rsa_key_generate_interval" + ] + rsa_key_generate_interval_schema[ + "description" + ] = "0 disables auto-generate(Unit is hour)" rsa_generation_schema = schema["properties"]["rsa_generation"] rsa_generation_schema["description"] = "0 disables generation" class E2EMessagingAccountUpdateRsaKeyRequest(BaseModel): """E2E Messaging Account Rsa Key Update schema (REQUEST)""" + rsa_key_generate_interval: Optional[int] = Field(24, ge=0, le=10_000) rsa_generation: Optional[int] = Field(7, ge=0, le=100) class Config: @staticmethod def schema_extra(schema: Dict[str, Any], _) -> None: - rsa_key_generate_interval_schema = schema["properties"]["rsa_key_generate_interval"] - rsa_key_generate_interval_schema["description"] = "0 disables auto-generate(Unit is hour)" + rsa_key_generate_interval_schema = schema["properties"][ + "rsa_key_generate_interval" + ] + rsa_key_generate_interval_schema[ + "description" + ] = "0 disables auto-generate(Unit is hour)" rsa_generation_schema = schema["properties"]["rsa_generation"] rsa_generation_schema["description"] = "0 disables generation" class E2EMessagingAccountChangeEOAPasswordRequest(BaseModel): """E2E Messaging Account Change EOA Password schema (REQUEST)""" + old_eoa_password: str eoa_password: str @@ -101,6 +103,7 @@ def eoa_password_is_encrypted_value(cls, v): class E2EMessagingAccountChangeRSAPassphraseRequest(BaseModel): """E2E Messaging Account Change RSA Passphrase schema (REQUEST)""" + old_rsa_passphrase: str rsa_passphrase: str @@ -122,6 +125,7 @@ def rsa_passphrase_is_encrypted_value(cls, v): ############################ class E2EMessagingAccountResponse(BaseModel): """E2E Messaging Account schema (Response)""" + account_address: str rsa_key_generate_interval: Optional[int] rsa_generation: Optional[int] @@ -131,6 +135,7 @@ class E2EMessagingAccountResponse(BaseModel): class E2EMessagingResponse(BaseModel): """E2E Messaging schema (Response)""" + id: int from_address: str to_address: str @@ -141,5 +146,6 @@ class E2EMessagingResponse(BaseModel): class ListAllE2EMessagingResponse(BaseModel): """List All E2E Messaging schema (Response)""" + result_set: ResultSet e2e_messages: List[E2EMessagingResponse] diff --git a/app/model/schema/file.py b/app/model/schema/file.py index 090da7b4..35f49503 100644 --- a/app/model/schema/file.py +++ b/app/model/schema/file.py @@ -18,29 +18,22 @@ """ import base64 from datetime import datetime -from typing import ( - Optional, - List, - Dict, - Any -) - -from pydantic import ( - BaseModel, - validator, - Field -) +from typing import Any, Dict, List, Optional + +from pydantic import BaseModel, Field, validator from config import MAX_UPLOAD_FILE_SIZE -from .types import ResultSet +from .types import ResultSet ############################ # REQUEST ############################ + class UploadFileRequest(BaseModel): """Upload File schema (Request)""" + relation: Optional[str] = Field(None, max_length=50) file_name: str = Field(..., max_length=256) content: str @@ -55,23 +48,28 @@ def content_is_less_than_max_upload_file_size(cls, v): raise ValueError("content is not a Base64-encoded string") if len(data) >= MAX_UPLOAD_FILE_SIZE: raise ValueError( - f"file size(Base64-decoded size) must be less than or equal to {MAX_UPLOAD_FILE_SIZE}") + f"file size(Base64-decoded size) must be less than or equal to {MAX_UPLOAD_FILE_SIZE}" + ) return v class Config: @staticmethod def schema_extra(schema: Dict[str, Any], _) -> None: notice_code_schema = schema["properties"]["content"] - notice_code_schema["description"] = "Base64-encoded content.\n" \ - f"Max length of binary data before encoding is {MAX_UPLOAD_FILE_SIZE}." + notice_code_schema["description"] = ( + "Base64-encoded content.\n" + f"Max length of binary data before encoding is {MAX_UPLOAD_FILE_SIZE}." + ) ############################ # RESPONSE ############################ + class FileResponse(BaseModel): """File schema (Response)""" + file_id: str issuer_address: str relation: Optional[str] @@ -84,12 +82,14 @@ class FileResponse(BaseModel): class ListAllFilesResponse(BaseModel): """List All Files schema (Response)""" + result_set: ResultSet files: List[FileResponse] class DownloadFileResponse(BaseModel): """Download File schema (Response)""" + file_id: str issuer_address: str relation: Optional[str] diff --git a/app/model/schema/holder.py b/app/model/schema/holder.py index 23d169dc..0c695874 100644 --- a/app/model/schema/holder.py +++ b/app/model/schema/holder.py @@ -16,10 +16,7 @@ SPDX-License-Identifier: Apache-2.0 """ -from typing import ( - Dict, - Any -) +from typing import Any, Dict from pydantic import BaseModel @@ -29,6 +26,7 @@ ############################ class HolderResponse(BaseModel): """Holder schema (Response)""" + account_address: str personal_information: Dict[str, Any] balance: int @@ -40,4 +38,5 @@ class HolderResponse(BaseModel): class HolderCountResponse(BaseModel): """Holder count schema (Response)""" + count: int diff --git a/app/model/schema/index.py b/app/model/schema/index.py index c860d323..5f4e81f1 100644 --- a/app/model/schema/index.py +++ b/app/model/schema/index.py @@ -17,6 +17,7 @@ SPDX-License-Identifier: Apache-2.0 """ from typing import Optional + from pydantic import BaseModel @@ -25,9 +26,11 @@ ############################ class E2EEResponse(BaseModel): """E2EE schema (Response)""" + public_key: Optional[str] class BlockNumberResponse(BaseModel): """Block Number schema (Response)""" + block_number: int diff --git a/app/model/schema/issue_redeem.py b/app/model/schema/issue_redeem.py index 859378cd..84731fcb 100644 --- a/app/model/schema/issue_redeem.py +++ b/app/model/schema/issue_redeem.py @@ -17,11 +17,11 @@ SPDX-License-Identifier: Apache-2.0 """ from typing import List + from pydantic import BaseModel from .types import ResultSet - ############################ # REQUEST ############################ @@ -31,8 +31,10 @@ # RESPONSE ############################ + class IssueRedeemEvent(BaseModel): """Issue/Redeem event""" + transaction_hash: str token_address: str locked_address: str @@ -43,5 +45,6 @@ class IssueRedeemEvent(BaseModel): class IssueRedeemHistoryResponse(BaseModel): """Issue/Redeem history""" + result_set: ResultSet history: List[IssueRedeemEvent] diff --git a/app/model/schema/ledger.py b/app/model/schema/ledger.py index ab887cae..0fcbd65f 100644 --- a/app/model/schema/ledger.py +++ b/app/model/schema/ledger.py @@ -16,36 +16,30 @@ SPDX-License-Identifier: Apache-2.0 """ -from typing import ( - List, - Optional -) -from pydantic import ( - BaseModel, - validator, - Field -) from datetime import datetime +from typing import List, Optional -from .types import ResultSet -from app.model.db import ( - LedgerDetailsDataType, - TokenType -) +from pydantic import BaseModel, Field, validator + +from app.model.db import LedgerDetailsDataType, TokenType +from .types import ResultSet ############################ # REQUEST ############################ + class CreateUpdateLedgerDetailsDataTemplateRequest(BaseModel): """Create or Update Ledger Details Data Template schema (Request)""" + type: LedgerDetailsDataType = Field(...) source: Optional[str] = Field(None, max_length=42) class CreateUpdateLedgerDetailsTemplateRequest(BaseModel): """Create or Update Ledger Details Template schema (Request)""" + token_detail_type: str = Field(..., max_length=100) headers: Optional[List[dict]] data: CreateUpdateLedgerDetailsDataTemplateRequest @@ -54,6 +48,7 @@ class CreateUpdateLedgerDetailsTemplateRequest(BaseModel): class CreateUpdateLedgerTemplateRequest(BaseModel): """Create or Update Ledger Template schema (Request)""" + token_name: str = Field(..., max_length=200) headers: Optional[List[dict]] details: List[CreateUpdateLedgerDetailsTemplateRequest] @@ -68,12 +63,15 @@ def details_length_is_greater_than_1(cls, v): class CreateUpdateLedgerDetailsDataRequest(BaseModel): """Create or Update Ledger Details Data Structure schema (Request)""" + name: Optional[str] = Field(None, max_length=200) address: Optional[str] = Field(None, max_length=200) amount: Optional[int] = Field(None, ge=0, le=1_000_000_000_000) price: Optional[int] = Field(None, ge=0, le=5_000_000_000) balance: Optional[int] = Field(None, ge=0, le=1_000_000_000_000 * 5_000_000_000) - acquisition_date: Optional[str] = Field(None, min_length=10, max_length=10, description="YYYY/MM/DD") + acquisition_date: Optional[str] = Field( + None, min_length=10, max_length=10, description="YYYY/MM/DD" + ) @validator("acquisition_date") def acquisition_date_format_is_YYYYMMDD_slash(cls, v): @@ -89,8 +87,10 @@ def acquisition_date_format_is_YYYYMMDD_slash(cls, v): # RESPONSE ############################ + class LedgerResponse(BaseModel): """Ledger schema (Response)""" + id: int token_address: str token_type: TokenType @@ -99,12 +99,14 @@ class LedgerResponse(BaseModel): class ListAllLedgerHistoryResponse(BaseModel): """List All Ledger History schema (Response)""" + result_set: ResultSet ledgers: List[LedgerResponse] class RetrieveLedgerDetailsDataHistoryResponse(BaseModel): """Retrieve Ledger Details Data History schema (Response)""" + account_address: Optional[str] name: Optional[str] address: Optional[str] @@ -116,6 +118,7 @@ class RetrieveLedgerDetailsDataHistoryResponse(BaseModel): class RetrieveLedgerDetailsHistoryResponse(BaseModel): """Retrieve Ledger Details History schema (Response)""" + token_detail_type: str headers: Optional[List[dict]] data: List[RetrieveLedgerDetailsDataHistoryResponse] @@ -124,6 +127,7 @@ class RetrieveLedgerDetailsHistoryResponse(BaseModel): class RetrieveLedgerHistoryResponse(BaseModel): """Retrieve Ledger History schema (Response)""" + created: str token_name: str headers: Optional[List[dict]] @@ -133,12 +137,14 @@ class RetrieveLedgerHistoryResponse(BaseModel): class LedgerDetailsDataTemplateResponse(BaseModel): """Ledger Details Data Template schema (Response)""" + type: LedgerDetailsDataType source: Optional[str] class LedgerDetailsTemplateResponse(BaseModel): """Ledger Details Template schema (Response)""" + token_detail_type: str headers: Optional[List[dict]] data: LedgerDetailsDataTemplateResponse @@ -147,6 +153,7 @@ class LedgerDetailsTemplateResponse(BaseModel): class LedgerTemplateResponse(BaseModel): """Ledger Template schema (Response)""" + token_name: str headers: Optional[List[dict]] details: List[LedgerDetailsTemplateResponse] @@ -155,6 +162,7 @@ class LedgerTemplateResponse(BaseModel): class LedgerDetailsDataListAllResponse(BaseModel): """Ledger Details Data(List All) schema (Response)""" + data_id: str count: int created: datetime @@ -162,17 +170,20 @@ class LedgerDetailsDataListAllResponse(BaseModel): class ListAllLedgerDetailsDataResponse(BaseModel): """List All Ledger Details Data schema (Response)""" + result_set: ResultSet details_data: List[LedgerDetailsDataListAllResponse] class LedgerDetailsDataResponse(BaseModel): """Ledger Details Data schema (Response)""" + data_id: str class RetrieveLedgerDetailsDataResponse(BaseModel): """Retrieve Ledger Details Data schema (Response)""" + name: Optional[str] address: Optional[str] amount: int diff --git a/app/model/schema/notification.py b/app/model/schema/notification.py index f4ac9823..557b8cdd 100644 --- a/app/model/schema/notification.py +++ b/app/model/schema/notification.py @@ -17,23 +17,13 @@ SPDX-License-Identifier: Apache-2.0 """ -from typing import ( - List, - Dict, - Any, - Union, - Optional, - Literal -) +from typing import Any, Dict, List, Literal, Optional, Union from pydantic import BaseModel, conint +from app.model.db import BatchIssueRedeemProcessingCategory, NotificationType, TokenType + from .types import ResultSet -from app.model.db import ( - NotificationType, - BatchIssueRedeemProcessingCategory, - TokenType -) class IssueErrorMetaInfo(BaseModel): @@ -115,9 +105,11 @@ class Config: @staticmethod def schema_extra(schema: Dict[str, Any], _) -> None: notice_code_schema = schema["properties"]["notice_code"] - notice_code_schema["description"] = " - 0: Issuer does not exist\n" \ - " - 1: Could not get the private key of the issuer\n" \ - " - 2: Failed to send transaction\n" + notice_code_schema["description"] = ( + " - 0: Issuer does not exist\n" + " - 1: Could not get the private key of the issuer\n" + " - 2: Failed to send transaction\n" + ) class BulkTransferErrorNotification(Notification): @@ -129,10 +121,11 @@ class Config: @staticmethod def schema_extra(schema: Dict[str, Any], _) -> None: notice_code_schema = schema["properties"]["notice_code"] - notice_code_schema["description"] = " - 0: Issuer does not exist\n" \ - " - 1: Could not get the private key of the issuer\n" \ - " - 2: Failed to send transaction\n" \ - + notice_code_schema["description"] = ( + " - 0: Issuer does not exist\n" + " - 1: Could not get the private key of the issuer\n" + " - 2: Failed to send transaction\n" + ) class ScheduleEventErrorNotification(Notification): @@ -144,10 +137,11 @@ class Config: @staticmethod def schema_extra(schema: Dict[str, Any], _) -> None: notice_code_schema = schema["properties"]["notice_code"] - notice_code_schema["description"] = " - 0: Issuer does not exist\n" \ - " - 1: Could not get the private key of the issuer\n" \ - " - 2: Failed to send transaction\n" \ - + notice_code_schema["description"] = ( + " - 0: Issuer does not exist\n" + " - 1: Could not get the private key of the issuer\n" + " - 2: Failed to send transaction\n" + ) class TransferApprovalInfoNotification(Notification): @@ -159,10 +153,12 @@ class Config: @staticmethod def schema_extra(schema: Dict[str, Any], _) -> None: notice_code_schema = schema["properties"]["notice_code"] - notice_code_schema["description"] = " - 0: Apply for transfer\n" \ - " - 1: Cancel transfer\n" \ - " - 2: Approve transfer\n" \ - " - 3: Escrow finished (Only occurs in security token escrow)\n" + notice_code_schema["description"] = ( + " - 0: Apply for transfer\n" + " - 1: Cancel transfer\n" + " - 2: Approve transfer\n" + " - 3: Escrow finished (Only occurs in security token escrow)\n" + ) class CreateLedgerInfoNotification(Notification): @@ -174,7 +170,9 @@ class Config: @staticmethod def schema_extra(schema: Dict[str, Any], _) -> None: notice_code_schema = schema["properties"]["notice_code"] - notice_code_schema["description"] = " - 0: Created ledger info successfully\n" + notice_code_schema[ + "description" + ] = " - 0: Created ledger info successfully\n" class BatchRegisterPersonalInfoErrorNotification(Notification): @@ -186,8 +184,9 @@ class Config: @staticmethod def schema_extra(schema: Dict[str, Any], _) -> None: notice_code_schema = schema["properties"]["notice_code"] - notice_code_schema["description"] = " - 0: Issuer does not exist\n" \ - " - 1: Failed to send transaction\n" + notice_code_schema["description"] = ( + " - 0: Issuer does not exist\n" " - 1: Failed to send transaction\n" + ) class BatchIssueRedeemProcessedNotification(Notification): @@ -199,10 +198,12 @@ class Config: @staticmethod def schema_extra(schema: Dict[str, Any], _) -> None: notice_code_schema = schema["properties"]["notice_code"] - notice_code_schema["description"] = " - 0: All records successfully processed\n" \ - " - 1: Issuer does not exist\n" \ - " - 2: Failed to decode keyfile\n" \ - " - 3: Some records are failed to send transaction" + notice_code_schema["description"] = ( + " - 0: All records successfully processed\n" + " - 1: Issuer does not exist\n" + " - 2: Failed to decode keyfile\n" + " - 3: Some records are failed to send transaction" + ) class LockInfoNotification(Notification): @@ -228,6 +229,7 @@ def schema_extra(schema: Dict[str, Any], _) -> None: notice_code_schema = schema["properties"]["notice_code"] notice_code_schema["description"] = " - 0: Balance is unlocked\n" + ############################ # REQUEST ############################ @@ -237,8 +239,10 @@ def schema_extra(schema: Dict[str, Any], _) -> None: # RESPONSE ############################ + class NotificationsListResponse(BaseModel): """Notifications List schema (Response)""" + __root__: Union[ IssueErrorNotification, BulkTransferErrorNotification, @@ -248,11 +252,12 @@ class NotificationsListResponse(BaseModel): BatchRegisterPersonalInfoErrorNotification, BatchIssueRedeemProcessedNotification, LockInfoNotification, - UnlockInfoNotification + UnlockInfoNotification, ] class ListAllNotificationsResponse(BaseModel): """List All Notifications schema (Response)""" + result_set: ResultSet notifications: List[NotificationsListResponse] diff --git a/app/model/schema/personal_info.py b/app/model/schema/personal_info.py index c80c23b0..ae652a2d 100644 --- a/app/model/schema/personal_info.py +++ b/app/model/schema/personal_info.py @@ -16,12 +16,9 @@ SPDX-License-Identifier: Apache-2.0 """ -from typing import Optional, List -from pydantic import ( - BaseModel, - validator, - Field -) +from typing import List, Optional + +from pydantic import BaseModel, Field, validator from web3 import Web3 from app.model.db import BatchRegisterPersonalInfoUploadStatus @@ -30,6 +27,7 @@ class PersonalInfo(BaseModel): """Personal Information schema""" + name: Optional[str] postal_code: Optional[str] address: Optional[str] @@ -43,8 +41,10 @@ class PersonalInfo(BaseModel): # REQUEST ############################ + class RegisterPersonalInfoRequest(PersonalInfo): """Register Personal Information schema (REQUEST)""" + account_address: str key_manager: str @@ -54,10 +54,12 @@ def account_address_is_valid_address(cls, v): raise ValueError("account_address is not a valid address") return v + ############################ # RESPONSE ############################ + class BatchRegisterPersonalInfoUploadResponse(BaseModel): """Batch Register PersonalInfo schema (RESPONSE)""" @@ -70,19 +72,21 @@ class Config: "example": { "batch_id": "cfd83622-34dc-4efe-a68b-2cc275d3d824", "status": "pending", - "created": "2022-09-02T19:49:33.370874+09:00" + "created": "2022-09-02T19:49:33.370874+09:00", } } class ListBatchRegisterPersonalInfoUploadResponse(BaseModel): """List All Batch Register PersonalInfo Upload (Response)""" + result_set: ResultSet uploads: List[BatchRegisterPersonalInfoUploadResponse] class BatchRegisterPersonalInfoResult(BaseModel): """Result of Creating Batch Register PersonalInfo schema (RESPONSE)""" + status: int # (pending:0, succeeded:1, failed:2) account_address: str diff --git a/app/model/schema/position.py b/app/model/schema/position.py index 5dc449e3..a67789a9 100644 --- a/app/model/schema/position.py +++ b/app/model/schema/position.py @@ -17,34 +17,25 @@ SPDX-License-Identifier: Apache-2.0 """ from enum import Enum -from typing import ( - List, - Optional -) +from typing import List, Optional from fastapi import Query -from pydantic import ( - BaseModel, - Field, - PositiveInt, - validator -) +from pydantic import BaseModel, Field, PositiveInt, validator from pydantic.dataclasses import dataclass from web3 import Web3 -from .types import ( - ResultSet, - SortOrder -) from app.model.db import TokenType +from .types import ResultSet, SortOrder ############################ # COMMON ############################ + class Position(BaseModel): """Position""" + issuer_address: str = Field(description="Issuer address") token_address: str = Field(description="Token address") token_type: TokenType = Field(description="Token type") @@ -58,6 +49,7 @@ class Position(BaseModel): class LockedPosition(BaseModel): """Locked Position""" + issuer_address: str = Field(description="Issuer address") token_address: str = Field(description="Token address") token_type: TokenType = Field(description="Token type") @@ -80,16 +72,21 @@ class LockEvent(BaseModel): token_name: str = Field(description="Token name") lock_address: str = Field(description="Lock address") account_address: str = Field(description="Account address") - recipient_address: Optional[str] = Field(default=None, description="Recipient address") + recipient_address: Optional[str] = Field( + default=None, description="Recipient address" + ) value: int = Field(description="Lock/Unlock amount") data: dict = Field(description="Message at lock/unlock") - block_timestamp: str = Field(description="block_timestamp when Lock log was emitted") + block_timestamp: str = Field( + description="block_timestamp when Lock log was emitted" + ) ############################ # REQUEST ############################ + class ListAllLockEventsSortItem(str, Enum): token_address = "token_address" lock_address = "lock_address" @@ -106,11 +103,19 @@ class ListAllLockEventsQuery: token_address: Optional[str] = Query(default=None, description="Token address") token_type: Optional[TokenType] = Query(default=None, description="Token type") lock_address: Optional[str] = Query(default=None, description="Lock address") - recipient_address: Optional[str] = Query(default=None, description="Recipient address") - category: Optional[LockEventCategory] = Query(default=None, description="Event category") + recipient_address: Optional[str] = Query( + default=None, description="Recipient address" + ) + category: Optional[LockEventCategory] = Query( + default=None, description="Event category" + ) - sort_item: ListAllLockEventsSortItem = Query(default=ListAllLockEventsSortItem.block_timestamp, description="Sort item") - sort_order: SortOrder = Query(default=SortOrder.DESC, description="Sort order(0: ASC, 1: DESC)") + sort_item: ListAllLockEventsSortItem = Query( + default=ListAllLockEventsSortItem.block_timestamp, description="Sort item" + ) + sort_order: SortOrder = Query( + default=SortOrder.DESC, description="Sort order(0: ASC, 1: DESC)" + ) class ForceUnlockRequest(BaseModel): @@ -149,24 +154,29 @@ def recipient_address_is_valid_address(cls, v): # RESPONSE ############################ + class PositionResponse(BaseModel): """Position schema (Response)""" + __root__: Position class ListAllPositionResponse(BaseModel): """List All Position schema (Response)""" + result_set: ResultSet positions: List[Position] = Field(description="Position list") class ListAllLockedPositionResponse(BaseModel): """List All Locked Position schema (Response)""" + result_set: ResultSet locked_positions: List[LockedPosition] = Field(description="Locked position list") class ListAllLockEventsResponse(BaseModel): """List All Lock/Unlock events (Response)""" + result_set: ResultSet events: List[LockEvent] = Field(description="Lock/Unlock event list") diff --git a/app/model/schema/scheduled_events.py b/app/model/schema/scheduled_events.py index 5d347b99..7c9afcf0 100644 --- a/app/model/schema/scheduled_events.py +++ b/app/model/schema/scheduled_events.py @@ -16,30 +16,23 @@ SPDX-License-Identifier: Apache-2.0 """ -from typing import ( - Dict, - Any -) +from datetime import datetime +from typing import Any, Dict -from pydantic import ( - BaseModel, - Field -) +from pydantic import BaseModel, Field -from datetime import datetime from app.model.db import TokenType -from .token import ( - IbetStraightBondUpdate, - IbetShareUpdate -) from app.model.db.scheduled_events import ScheduledEventType +from .token import IbetShareUpdate, IbetStraightBondUpdate + ############################ # REQUEST ############################ class IbetStraightBondScheduledUpdate(BaseModel): """scheduled event (Request)""" + scheduled_datetime: datetime event_type: ScheduledEventType = Field(...) data: IbetStraightBondUpdate @@ -47,6 +40,7 @@ class IbetStraightBondScheduledUpdate(BaseModel): class IbetShareScheduledUpdate(BaseModel): """scheduled event (Request)""" + scheduled_datetime: datetime event_type: ScheduledEventType = Field(...) data: IbetShareUpdate @@ -57,11 +51,13 @@ class IbetShareScheduledUpdate(BaseModel): ############################ class ScheduledEventIdResponse(BaseModel): """scheduled event (Response)""" + scheduled_event_id: str class ScheduledEventResponse(BaseModel): """scheduled event (Response)""" + scheduled_event_id: str token_address: str token_type: TokenType diff --git a/app/model/schema/token.py b/app/model/schema/token.py index 71e672b9..7d75a569 100644 --- a/app/model/schema/token.py +++ b/app/model/schema/token.py @@ -16,41 +16,27 @@ SPDX-License-Identifier: Apache-2.0 """ -from enum import Enum -from typing import ( - List, - Optional -) import math -from fastapi import Query +from enum import Enum +from typing import List, Optional -from pydantic import ( - BaseModel, - Field, - validator -) +from fastapi import Query +from pydantic import BaseModel, Field, validator from pydantic.dataclasses import dataclass from web3 import Web3 -from . import ( - LockEventCategory -) -from .position import LockEvent - -from .types import ( - MMDD_constr, - YYYYMMDD_constr, - EMPTY_str, - SortOrder, - ResultSet -) +from . import LockEventCategory +from .position import LockEvent +from .types import EMPTY_str, MMDD_constr, ResultSet, SortOrder, YYYYMMDD_constr ############################ # REQUEST ############################ + class IbetStraightBondCreate(BaseModel): """ibet Straight Bond schema (Create)""" + name: str = Field(max_length=100) total_supply: int = Field(..., ge=0, le=1_000_000_000_000) face_value: int = Field(..., ge=0, le=5_000_000_000) @@ -76,22 +62,28 @@ class IbetStraightBondCreate(BaseModel): @validator("interest_rate") def interest_rate_4_decimal_places(cls, v): if v is not None: - float_data = float(v * 10 ** 4) - int_data = int(v * 10 ** 4) + float_data = float(v * 10**4) + int_data = int(v * 10**4) if not math.isclose(int_data, float_data): - raise ValueError("interest_rate must be less than or equal to four decimal places") + raise ValueError( + "interest_rate must be less than or equal to four decimal places" + ) return v @validator("interest_payment_date") def interest_payment_date_list_length_less_than_13(cls, v): if v is not None and len(v) >= 13: - raise ValueError("list length of interest_payment_date must be less than 13") + raise ValueError( + "list length of interest_payment_date must be less than 13" + ) return v @validator("tradable_exchange_contract_address") def tradable_exchange_contract_address_is_valid_address(cls, v): if v is not None and not Web3.isAddress(v): - raise ValueError("tradable_exchange_contract_address is not a valid address") + raise ValueError( + "tradable_exchange_contract_address is not a valid address" + ) return v @validator("personal_info_contract_address") @@ -103,6 +95,7 @@ def personal_info_contract_address_is_valid_address(cls, v): class IbetStraightBondUpdate(BaseModel): """ibet Straight Bond schema (Update)""" + face_value: Optional[int] = Field(None, ge=0, le=5_000_000_000) interest_rate: Optional[float] = Field(None, ge=0.0000, le=100.0000) interest_payment_date: Optional[List[MMDD_constr]] @@ -121,8 +114,8 @@ class IbetStraightBondUpdate(BaseModel): @validator("interest_rate") def interest_rate_4_decimal_places(cls, v): if v is not None: - float_data = float(v * 10 ** 4) - int_data = int(v * 10 ** 4) + float_data = float(v * 10**4) + int_data = int(v * 10**4) if not math.isclose(int_data, float_data): raise ValueError("interest_rate must be rounded to 4 decimal places") return v @@ -130,13 +123,17 @@ def interest_rate_4_decimal_places(cls, v): @validator("interest_payment_date") def interest_payment_date_list_length_less_than_13(cls, v): if v is not None and len(v) >= 13: - raise ValueError("list length of interest_payment_date must be less than 13") + raise ValueError( + "list length of interest_payment_date must be less than 13" + ) return v @validator("tradable_exchange_contract_address") def tradable_exchange_contract_address_is_valid_address(cls, v): if v is not None and not Web3.isAddress(v): - raise ValueError("tradable_exchange_contract_address is not a valid address") + raise ValueError( + "tradable_exchange_contract_address is not a valid address" + ) return v @validator("personal_info_contract_address") @@ -148,6 +145,7 @@ def personal_info_contract_address_is_valid_address(cls, v): class IbetStraightBondAdditionalIssue(BaseModel): """ibet Straight Bond schema (Additional Issue)""" + account_address: str amount: int = Field(..., ge=1, le=1_000_000_000_000) @@ -160,6 +158,7 @@ def account_address_is_valid_address(cls, v): class IbetStraightBondRedeem(BaseModel): """ibet Straight Bond schema (Redeem)""" + account_address: str amount: int = Field(..., ge=1, le=1_000_000_000_000) @@ -172,6 +171,7 @@ def account_address_is_valid_address(cls, v): class IbetStraightBondTransfer(BaseModel): """ibet Straight Bond schema (Transfer)""" + token_address: str from_address: str to_address: str @@ -198,6 +198,7 @@ def to_address_is_valid_address(cls, v): class IbetShareCreate(BaseModel): """ibet Share schema (Create)""" + name: str = Field(max_length=100) issue_price: int = Field(..., ge=0, le=5_000_000_000) principal_value: int = Field(..., ge=0, le=5_000_000_000) @@ -220,8 +221,8 @@ class IbetShareCreate(BaseModel): @validator("dividends") def dividends_13_decimal_places(cls, v): if v is not None: - float_data = float(v * 10 ** 13) - int_data = int(v * 10 ** 13) + float_data = float(v * 10**13) + int_data = int(v * 10**13) if not math.isclose(int_data, float_data): raise ValueError("dividends must be rounded to 13 decimal places") return v @@ -229,7 +230,9 @@ def dividends_13_decimal_places(cls, v): @validator("tradable_exchange_contract_address") def tradable_exchange_contract_address_is_valid_address(cls, v): if v is not None and not Web3.isAddress(v): - raise ValueError("tradable_exchange_contract_address is not a valid address") + raise ValueError( + "tradable_exchange_contract_address is not a valid address" + ) return v @validator("personal_info_contract_address") @@ -241,6 +244,7 @@ def personal_info_contract_address_is_valid_address(cls, v): class IbetShareUpdate(BaseModel): """ibet Share schema (Update)""" + cancellation_date: Optional[YYYYMMDD_constr | EMPTY_str] dividend_record_date: Optional[YYYYMMDD_constr | EMPTY_str] dividend_payment_date: Optional[YYYYMMDD_constr | EMPTY_str] @@ -260,8 +264,8 @@ class IbetShareUpdate(BaseModel): @validator("dividends") def dividends_13_decimal_places(cls, v): if v is not None: - float_data = float(v * 10 ** 13) - int_data = int(v * 10 ** 13) + float_data = float(v * 10**13) + int_data = int(v * 10**13) if not math.isclose(int_data, float_data): raise ValueError("dividends must be rounded to 13 decimal places") return v @@ -269,14 +273,21 @@ def dividends_13_decimal_places(cls, v): @validator("dividends") def dividend_information_all_required(cls, v, values, **kwargs): if v is not None: - if values.get("dividend_record_date") is None or values.get("dividend_payment_date") is None: - raise ValueError("all items are required to update the dividend information") + if ( + values.get("dividend_record_date") is None + or values.get("dividend_payment_date") is None + ): + raise ValueError( + "all items are required to update the dividend information" + ) return v @validator("tradable_exchange_contract_address") def tradable_exchange_contract_address_is_valid_address(cls, v): if v is not None and not Web3.isAddress(v): - raise ValueError("tradable_exchange_contract_address is not a valid address") + raise ValueError( + "tradable_exchange_contract_address is not a valid address" + ) return v @validator("personal_info_contract_address") @@ -288,6 +299,7 @@ def personal_info_contract_address_is_valid_address(cls, v): class IbetShareTransfer(BaseModel): """ibet Share schema (Transfer)""" + token_address: str from_address: str to_address: str @@ -314,6 +326,7 @@ def to_address_is_valid_address(cls, v): class IbetShareAdditionalIssue(BaseModel): """ibet Share schema (Additional Issue)""" + account_address: str amount: int = Field(..., ge=1, le=1_000_000_000_000) @@ -326,6 +339,7 @@ def account_address_is_valid_address(cls, v): class IbetShareRedeem(BaseModel): """ibet Share schema (Redeem)""" + account_address: str amount: int = Field(..., ge=1, le=1_000_000_000_000) @@ -351,25 +365,36 @@ class ListAllTokenLockEventsQuery: account_address: Optional[str] = Query(default=None, description="Account address") lock_address: Optional[str] = Query(default=None, description="Lock address") - recipient_address: Optional[str] = Query(default=None, description="Recipient address") - category: Optional[LockEventCategory] = Query(default=None, description="Event category") + recipient_address: Optional[str] = Query( + default=None, description="Recipient address" + ) + category: Optional[LockEventCategory] = Query( + default=None, description="Event category" + ) - sort_item: ListAllTokenLockEventsSortItem = Query(default=ListAllTokenLockEventsSortItem.block_timestamp, description="Sort item") - sort_order: SortOrder = Query(default=SortOrder.DESC, description="Sort order(0: ASC, 1: DESC)") + sort_item: ListAllTokenLockEventsSortItem = Query( + default=ListAllTokenLockEventsSortItem.block_timestamp, description="Sort item" + ) + sort_order: SortOrder = Query( + default=SortOrder.DESC, description="Sort order(0: ASC, 1: DESC)" + ) ############################ # RESPONSE ############################ + class TokenAddressResponse(BaseModel): """token address""" + token_address: str token_status: int class IbetStraightBondResponse(BaseModel): """ibet Straight Bond schema (Response)""" + issuer_address: str token_address: str name: str @@ -399,6 +424,7 @@ class IbetStraightBondResponse(BaseModel): class IbetShareResponse(BaseModel): """ibet Share schema (Response)""" + issuer_address: str token_address: str name: str @@ -426,5 +452,6 @@ class IbetShareResponse(BaseModel): class ListAllTokenLockEventsResponse(BaseModel): """List All Lock/Unlock events (Response)""" + result_set: ResultSet events: List[LockEvent] = Field(description="Lock/Unlock event list") diff --git a/app/model/schema/token_holders.py b/app/model/schema/token_holders.py index a3854323..35d5b639 100644 --- a/app/model/schema/token_holders.py +++ b/app/model/schema/token_holders.py @@ -17,12 +17,13 @@ SPDX-License-Identifier: Apache-2.0 """ import uuid -from typing import List, Dict, Union +from typing import Dict, List, Union + from pydantic import BaseModel, Field, validator + from app.model.db import TokenHolderBatchStatus from app.model.schema.types import ResultSet - ############################ # REQUEST ############################ @@ -82,14 +83,17 @@ class RetrieveTokenHolderCollectionResponse(BaseModel): class ListAllTokenHolderCollectionsResponse(BaseModel): """List All Token Holders Collections schema (RESPONSE)""" + result_set: ResultSet collections: List[RetrieveTokenHolderCollectionResponse] class TokenHoldersCollectionHolder(BaseModel): account_address: str = Field(description="Account address of token holder.") - hold_balance: int = Field(description="Amount of balance." - "This includes balance/pending_transfer/exchange_balance/exchange_commitment.") + hold_balance: int = Field( + description="Amount of balance." + "This includes balance/pending_transfer/exchange_balance/exchange_commitment." + ) locked_balance: int = Field(description="Amount of locked balance.") @@ -107,7 +111,7 @@ class Config: { "account_address": "0x85a8b8887a4bD76859751b10C8aC8EC5f3aA1bDB", "hold_balance": 30000, - "locked_balance": 0 + "locked_balance": 0, } ], } diff --git a/app/model/schema/transfer.py b/app/model/schema/transfer.py index 1afeb3fc..62fa7b21 100644 --- a/app/model/schema/transfer.py +++ b/app/model/schema/transfer.py @@ -17,25 +17,19 @@ SPDX-License-Identifier: Apache-2.0 """ from enum import Enum -from typing import ( - List, - Optional -) +from typing import List, Optional + from fastapi import Query -from pydantic import ( - BaseModel, - Field, - NonNegativeInt -) +from pydantic import BaseModel, Field, NonNegativeInt from pydantic.dataclasses import dataclass from .types import ResultSet - ############################ # COMMON ############################ + class TransferSourceEventType(str, Enum): Transfer = "Transfer" Unlock = "Unlock" @@ -45,6 +39,7 @@ class TransferSourceEventType(str, Enum): # REQUEST ############################ + class ListTransferHistorySortItem(str, Enum): BLOCK_TIMESTAMP = "block_timestamp" FROM_ADDRESS = "from_address" @@ -54,7 +49,9 @@ class ListTransferHistorySortItem(str, Enum): @dataclass class ListTransferHistoryQuery: - source_event: Optional[TransferSourceEventType] = Query(default=None, description="source event of transfer") + source_event: Optional[TransferSourceEventType] = Query( + default=None, description="source event of transfer" + ) data: Optional[str] = Query(default=None, description="source event data") sort_item: ListTransferHistorySortItem = Query( @@ -72,6 +69,7 @@ class UpdateTransferApprovalOperationType(str, Enum): class UpdateTransferApprovalRequest(BaseModel): """Update Transfer Approval schema (Request)""" + operation_type: UpdateTransferApprovalOperationType = Field(...) @@ -79,8 +77,10 @@ class UpdateTransferApprovalRequest(BaseModel): # RESPONSE ############################ + class TransferResponse(BaseModel): """transfer data""" + transaction_hash: str token_address: str from_address: str @@ -93,12 +93,14 @@ class TransferResponse(BaseModel): class TransferHistoryResponse(BaseModel): """transfer history""" + result_set: ResultSet transfer_history: List[TransferResponse] class TransferApprovalResponse(BaseModel): """transfer approval data""" + issuer_address: str token_address: str application_count: int @@ -110,12 +112,14 @@ class TransferApprovalResponse(BaseModel): class TransferApprovalsResponse(BaseModel): """transfer approvals""" + result_set: ResultSet transfer_approvals: List[TransferApprovalResponse] class TransferApprovalTokenResponse(BaseModel): """transfer approval token data""" + id: int token_address: str exchange_address: str @@ -136,5 +140,6 @@ class TransferApprovalTokenResponse(BaseModel): class TransferApprovalHistoryResponse(BaseModel): """transfer approval token history""" + result_set: ResultSet transfer_approval_history: List[TransferApprovalTokenResponse] diff --git a/app/model/schema/types.py b/app/model/schema/types.py index 272d24ff..e2179457 100644 --- a/app/model/schema/types.py +++ b/app/model/schema/types.py @@ -17,20 +17,20 @@ SPDX-License-Identifier: Apache-2.0 """ from enum import IntEnum -from typing import Optional, Literal +from typing import Literal, Optional -from pydantic import ( - BaseModel, - constr -) +from pydantic import BaseModel, constr MMDD_constr = constr(regex="^(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$") -YYYYMMDD_constr = constr(regex="^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$") +YYYYMMDD_constr = constr( + regex="^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$" +) EMPTY_str = Literal[""] class ResultSet(BaseModel): """result set for pagination""" + count: Optional[int] offset: Optional[int] limit: Optional[int] diff --git a/app/routers/account.py b/app/routers/account.py index bb117513..4be72f3c 100644 --- a/app/routers/account.py +++ b/app/routers/account.py @@ -17,69 +17,64 @@ SPDX-License-Identifier: Apache-2.0 """ import hashlib -from datetime import timedelta, datetime -from typing import List, Optional -import secrets import re +import secrets +from datetime import datetime, timedelta +from typing import List, Optional -from fastapi import ( - APIRouter, - Depends, - Header, - Request -) +import boto3 +import eth_keyfile +from coincurve import PublicKey +from Crypto.PublicKey import RSA +from eth_utils import keccak, to_checksum_address +from fastapi import APIRouter, Depends, Header, Request from fastapi.exceptions import HTTPException from pytz import timezone -from sqlalchemy.orm import Session from sqlalchemy.exc import IntegrityError as SAIntegrityError -from coincurve import PublicKey -from Crypto.PublicKey import RSA -from eth_utils import to_checksum_address, keccak -import eth_keyfile -import boto3 +from sqlalchemy.orm import Session -from config import ( - PERSONAL_INFO_RSA_DEFAULT_PASSPHRASE, - EOA_PASSWORD_PATTERN, - EOA_PASSWORD_PATTERN_MSG, - PERSONAL_INFO_RSA_PASSPHRASE_PATTERN, - PERSONAL_INFO_RSA_PASSPHRASE_PATTERN_MSG, - E2EE_REQUEST_ENABLED, - AWS_REGION_NAME, - AWS_KMS_GENERATE_RANDOM_ENABLED, - TZ -) from app.database import db_session +from app.exceptions import ( + AuthorizationError, + AuthTokenAlreadyExistsError, + InvalidParameterError, +) +from app.model.db import ( + Account, + AccountRsaKeyTemporary, + AccountRsaStatus, + AuthToken, + TransactionLock, +) from app.model.schema import ( - AccountCreateKeyRequest, - AccountResponse, - AccountGenerateRsaKeyRequest, + AccountAuthTokenRequest, + AccountAuthTokenResponse, AccountChangeEOAPasswordRequest, AccountChangeRSAPassphraseRequest, - AccountAuthTokenRequest, - AccountAuthTokenResponse + AccountCreateKeyRequest, + AccountGenerateRsaKeyRequest, + AccountResponse, ) -from app.utils.fastapi import json_response -from app.utils.e2ee_utils import E2EEUtils from app.utils.check_utils import ( - validate_headers, address_is_valid_address, - eoa_password_is_required, + check_auth, eoa_password_is_encrypted_value, - check_auth + eoa_password_is_required, + validate_headers, ) from app.utils.docs_utils import get_routers_responses -from app.model.db import ( - Account, - AccountRsaKeyTemporary, - AccountRsaStatus, - AuthToken, - TransactionLock -) -from app.exceptions import ( - InvalidParameterError, - AuthTokenAlreadyExistsError, - AuthorizationError +from app.utils.e2ee_utils import E2EEUtils +from app.utils.fastapi import json_response +from config import ( + AWS_KMS_GENERATE_RANDOM_ENABLED, + AWS_REGION_NAME, + E2EE_REQUEST_ENABLED, + EOA_PASSWORD_PATTERN, + EOA_PASSWORD_PATTERN_MSG, + PERSONAL_INFO_RSA_DEFAULT_PASSPHRASE, + PERSONAL_INFO_RSA_PASSPHRASE_PATTERN, + PERSONAL_INFO_RSA_PASSPHRASE_PATTERN_MSG, + TZ, ) router = APIRouter(tags=["account"]) @@ -91,14 +86,16 @@ @router.post( "/accounts", response_model=AccountResponse, - responses=get_routers_responses(422, InvalidParameterError) + responses=get_routers_responses(422, InvalidParameterError), ) -def create_key( - data: AccountCreateKeyRequest, - db: Session = Depends(db_session)): +def create_key(data: AccountCreateKeyRequest, db: Session = Depends(db_session)): """Create Keys""" # Check Password Policy - eoa_password = E2EEUtils.decrypt(data.eoa_password) if E2EE_REQUEST_ENABLED else data.eoa_password + eoa_password = ( + E2EEUtils.decrypt(data.eoa_password) + if E2EE_REQUEST_ENABLED + else data.eoa_password + ) if not re.match(EOA_PASSWORD_PATTERN, eoa_password): raise InvalidParameterError(EOA_PASSWORD_PATTERN_MSG) @@ -112,9 +109,7 @@ def create_key( public_key = PublicKey.from_valid_secret(private_key).format(compressed=False)[1:] addr = to_checksum_address(keccak(public_key)[-20:]) keyfile_json = eth_keyfile.create_keyfile_json( - private_key=private_key, - password=eoa_password.encode("utf-8"), - kdf="pbkdf2" + private_key=private_key, password=eoa_password.encode("utf-8"), kdf="pbkdf2" ) # Register key data to the DB @@ -133,19 +128,18 @@ def create_key( db.commit() - return json_response({ - "issuer_address": _account.issuer_address, - "rsa_public_key": "", - "rsa_status": _account.rsa_status, - "is_deleted": _account.is_deleted - }) + return json_response( + { + "issuer_address": _account.issuer_address, + "rsa_public_key": "", + "rsa_status": _account.rsa_status, + "is_deleted": _account.is_deleted, + } + ) # GET: /accounts -@router.get( - "/accounts", - response_model=List[AccountResponse] -) +@router.get("/accounts", response_model=List[AccountResponse]) def list_all_accounts(db: Session = Depends(db_session)): """List all accounts""" @@ -154,12 +148,14 @@ def list_all_accounts(db: Session = Depends(db_session)): account_list = [] for _account in _accounts: - account_list.append({ - "issuer_address": _account.issuer_address, - "rsa_public_key": _account.rsa_public_key, - "rsa_status": _account.rsa_status, - "is_deleted": _account.is_deleted - }) + account_list.append( + { + "issuer_address": _account.issuer_address, + "rsa_public_key": _account.rsa_public_key, + "rsa_status": _account.rsa_status, + "is_deleted": _account.is_deleted, + } + ) return json_response(account_list) @@ -168,37 +164,39 @@ def list_all_accounts(db: Session = Depends(db_session)): @router.get( "/accounts/{issuer_address}", response_model=AccountResponse, - responses=get_routers_responses(404) + responses=get_routers_responses(404), ) def retrieve_account(issuer_address: str, db: Session = Depends(db_session)): """Retrieve an account""" - _account = db.query(Account). \ - filter(Account.issuer_address == issuer_address). \ - first() + _account = ( + db.query(Account).filter(Account.issuer_address == issuer_address).first() + ) if _account is None: raise HTTPException(status_code=404, detail="issuer does not exist") - return json_response({ - "issuer_address": _account.issuer_address, - "rsa_public_key": _account.rsa_public_key, - "rsa_status": _account.rsa_status, - "is_deleted": _account.is_deleted - }) + return json_response( + { + "issuer_address": _account.issuer_address, + "rsa_public_key": _account.rsa_public_key, + "rsa_status": _account.rsa_status, + "is_deleted": _account.is_deleted, + } + ) # DELETE: /accounts/{issuer_address} @router.delete( "/accounts/{issuer_address}", response_model=AccountResponse, - responses=get_routers_responses(404) + responses=get_routers_responses(404), ) def delete_account(issuer_address: str, db: Session = Depends(db_session)): """Logically delete an account""" - _account = db.query(Account). \ - filter(Account.issuer_address == issuer_address). \ - first() + _account = ( + db.query(Account).filter(Account.issuer_address == issuer_address).first() + ) if _account is None: raise HTTPException(status_code=404, detail="issuer does not exist") @@ -206,41 +204,50 @@ def delete_account(issuer_address: str, db: Session = Depends(db_session)): db.merge(_account) db.commit() - return json_response({ - "issuer_address": _account.issuer_address, - "rsa_public_key": _account.rsa_public_key, - "rsa_status": _account.rsa_status, - "is_deleted": _account.is_deleted - }) + return json_response( + { + "issuer_address": _account.issuer_address, + "rsa_public_key": _account.rsa_public_key, + "rsa_status": _account.rsa_status, + "is_deleted": _account.is_deleted, + } + ) # POST: /accounts/{issuer_address}/rsakey @router.post( "/accounts/{issuer_address}/rsakey", response_model=AccountResponse, - responses=get_routers_responses(422, 404, InvalidParameterError) + responses=get_routers_responses(422, 404, InvalidParameterError), ) def generate_rsa_key( - issuer_address: str, - data: AccountGenerateRsaKeyRequest, - db: Session = Depends(db_session)): + issuer_address: str, + data: AccountGenerateRsaKeyRequest, + db: Session = Depends(db_session), +): """Generate RSA key""" # Get Account - _account = db.query(Account). \ - filter(Account.issuer_address == issuer_address). \ - first() + _account = ( + db.query(Account).filter(Account.issuer_address == issuer_address).first() + ) if _account is None: raise HTTPException(status_code=404, detail="issuer does not exist") # Check now Generating RSA - if _account.rsa_status == AccountRsaStatus.CREATING.value or \ - _account.rsa_status == AccountRsaStatus.CHANGING.value: + if ( + _account.rsa_status == AccountRsaStatus.CREATING.value + or _account.rsa_status == AccountRsaStatus.CHANGING.value + ): raise InvalidParameterError("RSA key is now generating") # Check Password Policy if data.rsa_passphrase: - rsa_passphrase = E2EEUtils.decrypt(data.rsa_passphrase) if E2EE_REQUEST_ENABLED else data.rsa_passphrase + rsa_passphrase = ( + E2EEUtils.decrypt(data.rsa_passphrase) + if E2EE_REQUEST_ENABLED + else data.rsa_passphrase + ) if not re.match(PERSONAL_INFO_RSA_PASSPHRASE_PATTERN, rsa_passphrase): raise InvalidParameterError(PERSONAL_INFO_RSA_PASSPHRASE_PATTERN_MSG) else: @@ -268,39 +275,51 @@ def generate_rsa_key( db.commit() - return json_response({ - "issuer_address": issuer_address, - "rsa_public_key": _account.rsa_public_key, - "rsa_status": rsa_status, - "is_deleted": _account.is_deleted - }) + return json_response( + { + "issuer_address": issuer_address, + "rsa_public_key": _account.rsa_public_key, + "rsa_status": rsa_status, + "is_deleted": _account.is_deleted, + } + ) # POST: /accounts/{issuer_address}/eoa_password @router.post( "/accounts/{issuer_address}/eoa_password", response_model=None, - responses=get_routers_responses(422, 404, InvalidParameterError)) + responses=get_routers_responses(422, 404, InvalidParameterError), +) def change_eoa_password( - issuer_address: str, - data: AccountChangeEOAPasswordRequest, - db: Session = Depends(db_session)): + issuer_address: str, + data: AccountChangeEOAPasswordRequest, + db: Session = Depends(db_session), +): """Change EOA Password""" # Get Account - _account = db.query(Account). \ - filter(Account.issuer_address == issuer_address). \ - first() + _account = ( + db.query(Account).filter(Account.issuer_address == issuer_address).first() + ) if _account is None: raise HTTPException(status_code=404, detail="issuer does not exist") # Check Password Policy - eoa_password = E2EEUtils.decrypt(data.eoa_password) if E2EE_REQUEST_ENABLED else data.eoa_password + eoa_password = ( + E2EEUtils.decrypt(data.eoa_password) + if E2EE_REQUEST_ENABLED + else data.eoa_password + ) if not re.match(EOA_PASSWORD_PATTERN, eoa_password): raise InvalidParameterError(EOA_PASSWORD_PATTERN_MSG) # Check Old Password - old_eoa_password = E2EEUtils.decrypt(data.old_eoa_password) if E2EE_REQUEST_ENABLED else data.old_eoa_password + old_eoa_password = ( + E2EEUtils.decrypt(data.old_eoa_password) + if E2EE_REQUEST_ENABLED + else data.old_eoa_password + ) correct_eoa_password = E2EEUtils.decrypt(_account.eoa_password) if old_eoa_password != correct_eoa_password: raise InvalidParameterError("old password mismatch") @@ -308,15 +327,12 @@ def change_eoa_password( # Get Ethereum Key old_keyfile_json = _account.keyfile private_key = eth_keyfile.decode_keyfile_json( - raw_keyfile_json=old_keyfile_json, - password=old_eoa_password.encode("utf-8") + raw_keyfile_json=old_keyfile_json, password=old_eoa_password.encode("utf-8") ) # Create New Ethereum Key File keyfile_json = eth_keyfile.create_keyfile_json( - private_key=private_key, - password=eoa_password.encode("utf-8"), - kdf="pbkdf2" + private_key=private_key, password=eoa_password.encode("utf-8"), kdf="pbkdf2" ) # Update data to the DB @@ -333,35 +349,47 @@ def change_eoa_password( @router.post( "/accounts/{issuer_address}/rsa_passphrase", response_model=None, - responses=get_routers_responses(422, 404, InvalidParameterError)) + responses=get_routers_responses(422, 404, InvalidParameterError), +) def change_rsa_passphrase( - issuer_address: str, - data: AccountChangeRSAPassphraseRequest, - db: Session = Depends(db_session)): + issuer_address: str, + data: AccountChangeRSAPassphraseRequest, + db: Session = Depends(db_session), +): """Change RSA Passphrase""" # Get Account - _account = db.query(Account). \ - filter(Account.issuer_address == issuer_address). \ - first() + _account = ( + db.query(Account).filter(Account.issuer_address == issuer_address).first() + ) if _account is None: raise HTTPException(status_code=404, detail="issuer does not exist") # Check Old Passphrase - old_rsa_passphrase = E2EEUtils.decrypt(data.old_rsa_passphrase) if E2EE_REQUEST_ENABLED else data.old_rsa_passphrase + old_rsa_passphrase = ( + E2EEUtils.decrypt(data.old_rsa_passphrase) + if E2EE_REQUEST_ENABLED + else data.old_rsa_passphrase + ) correct_rsa_passphrase = E2EEUtils.decrypt(_account.rsa_passphrase) if old_rsa_passphrase != correct_rsa_passphrase: raise InvalidParameterError("old passphrase mismatch") # Check Password Policy - rsa_passphrase = E2EEUtils.decrypt(data.rsa_passphrase) if E2EE_REQUEST_ENABLED else data.rsa_passphrase + rsa_passphrase = ( + E2EEUtils.decrypt(data.rsa_passphrase) + if E2EE_REQUEST_ENABLED + else data.rsa_passphrase + ) if not re.match(PERSONAL_INFO_RSA_PASSPHRASE_PATTERN, rsa_passphrase): raise InvalidParameterError(PERSONAL_INFO_RSA_PASSPHRASE_PATTERN_MSG) # Create New RSA Private Key old_rsa_private_key = _account.rsa_private_key rsa_key = RSA.importKey(old_rsa_private_key, old_rsa_passphrase) - rsa_private_key = rsa_key.exportKey(format="PEM", passphrase=rsa_passphrase).decode() + rsa_private_key = rsa_key.exportKey( + format="PEM", passphrase=rsa_passphrase + ).decode() # Update data to the DB _account.rsa_private_key = rsa_private_key @@ -377,19 +405,26 @@ def change_rsa_passphrase( @router.post( "/accounts/{issuer_address}/auth_token", response_model=AccountAuthTokenResponse, - responses=get_routers_responses(422, 404, InvalidParameterError, AuthTokenAlreadyExistsError)) + responses=get_routers_responses( + 422, 404, InvalidParameterError, AuthTokenAlreadyExistsError + ), +) def create_auth_token( - request: Request, - data: AccountAuthTokenRequest, - issuer_address: str, - eoa_password: Optional[str] = Header(None), - db: Session = Depends(db_session)): + request: Request, + data: AccountAuthTokenRequest, + issuer_address: str, + eoa_password: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Create Auth Token""" # Validate Headers validate_headers( issuer_address=(issuer_address, address_is_valid_address), - eoa_password=(eoa_password, [eoa_password_is_required, eoa_password_is_encrypted_value]) + eoa_password=( + eoa_password, + [eoa_password_is_required, eoa_password_is_encrypted_value], + ), ) # Authentication @@ -409,15 +444,17 @@ def create_auth_token( current_datetime_local = current_datetime_utc.astimezone(local_tz).isoformat() # Register auth token - auth_token: Optional[AuthToken] = db.query(AuthToken). \ - filter(AuthToken.issuer_address == issuer_address). \ - first() + auth_token: Optional[AuthToken] = ( + db.query(AuthToken).filter(AuthToken.issuer_address == issuer_address).first() + ) if auth_token is not None: # If a valid auth token already exists, return an error. if auth_token.valid_duration == 0: raise AuthTokenAlreadyExistsError() else: - expiration_datetime = auth_token.usage_start + timedelta(seconds=auth_token.valid_duration) + expiration_datetime = auth_token.usage_start + timedelta( + seconds=auth_token.valid_duration + ) if datetime.utcnow() <= expiration_datetime: raise AuthTokenAlreadyExistsError() # Update auth token @@ -439,31 +476,34 @@ def create_auth_token( # NOTE: Registration can be conflicting. raise AuthTokenAlreadyExistsError() - return json_response({ - "auth_token": new_token, - "usage_start": current_datetime_local, - "valid_duration": data.valid_duration - }) + return json_response( + { + "auth_token": new_token, + "usage_start": current_datetime_local, + "valid_duration": data.valid_duration, + } + ) # DELETE: /accounts/{issuer_address}/auth_token @router.delete( "/accounts/{issuer_address}/auth_token", response_model=None, - responses=get_routers_responses(422, 404, AuthorizationError) + responses=get_routers_responses(422, 404, AuthorizationError), ) def delete_auth_token( - request: Request, - issuer_address: str, - eoa_password: Optional[str] = Header(None), - auth_token: Optional[str] = Header(None), - db: Session = Depends(db_session)): + request: Request, + issuer_address: str, + eoa_password: Optional[str] = Header(None), + auth_token: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Delete auth token""" # Validate Headers validate_headers( issuer_address=(issuer_address, address_is_valid_address), - eoa_password=(eoa_password, eoa_password_is_encrypted_value) + eoa_password=(eoa_password, eoa_password_is_encrypted_value), ) # Authentication @@ -472,13 +512,13 @@ def delete_auth_token( db=db, issuer_address=issuer_address, eoa_password=eoa_password, - auth_token=auth_token + auth_token=auth_token, ) # Delete auto token - _auth_token = db.query(AuthToken). \ - filter(AuthToken.issuer_address == issuer_address). \ - first() + _auth_token = ( + db.query(AuthToken).filter(AuthToken.issuer_address == issuer_address).first() + ) if _auth_token is None: raise HTTPException(status_code=404, detail="auth token does not exist") diff --git a/app/routers/bc_explorer.py b/app/routers/bc_explorer.py index 83d21e7e..d98cf9aa 100644 --- a/app/routers/bc_explorer.py +++ b/app/routers/bc_explorer.py @@ -16,57 +16,40 @@ SPDX-License-Identifier: Apache-2.0 """ -from typing import Tuple, Dict, Any, Type +from typing import Any, Dict, Tuple, Type from eth_utils import to_checksum_address -from fastapi import ( - APIRouter, - Depends, - HTTPException, - Path -) +from fastapi import APIRouter, Depends, HTTPException, Path from pydantic import NonNegativeInt from sqlalchemy import desc from sqlalchemy.orm import Session from web3.contract import ContractFunction -import config +import config from app import log from app.database import db_session -from app.exceptions import ( - ResponseLimitExceededError -) -from app.model.db import ( - IDXBlockData, - IDXTxData, - Token, - IDXBlockDataBlockNumber -) +from app.exceptions import ResponseLimitExceededError +from app.model.db import IDXBlockData, IDXBlockDataBlockNumber, IDXTxData, Token from app.model.schema import ( + BlockDataListResponse, + BlockDataResponse, ListBlockDataQuery, ListTxDataQuery, - BlockDataResponse, - BlockDataListResponse, + TxDataListResponse, TxDataResponse, - TxDataListResponse ) -from app.utils.fastapi import json_response from app.utils.contract_utils import ContractUtils from app.utils.docs_utils import get_routers_responses +from app.utils.fastapi import json_response from app.utils.web3_utils import Web3Wrapper -from config import ( - BC_EXPLORER_ENABLED -) +from config import BC_EXPLORER_ENABLED LOG = log.get_logger() web3 = Web3Wrapper() BLOCK_RESPONSE_LIMIT = 1000 TX_RESPONSE_LIMIT = 10000 -router = APIRouter( - prefix="/blockchain_explorer", - tags=["blockchain_explorer"] -) +router = APIRouter(prefix="/blockchain_explorer", tags=["blockchain_explorer"]) # ------------------------------ @@ -77,18 +60,20 @@ summary="[ibet Blockchain Explorer] List block data", operation_id="ListBlockData", response_model=BlockDataListResponse, - responses=get_routers_responses(404, ResponseLimitExceededError) + responses=get_routers_responses(404, ResponseLimitExceededError), ) def list_block_data( request_query: ListBlockDataQuery = Depends(), - session: Session = Depends(db_session) + session: Session = Depends(db_session), ): """ Returns a list of block data within the specified block number range. The maximum number of search results is 1000. """ if BC_EXPLORER_ENABLED is False: - raise HTTPException(status_code=404, detail="This URL is not available in the current settings") + raise HTTPException( + status_code=404, detail="This URL is not available in the current settings" + ) offset = request_query.offset limit = request_query.limit @@ -99,18 +84,22 @@ def list_block_data( # NOTE: The more data, the slower the SELECT COUNT(1) query becomes. # To get total number of block data, latest block number where block data synced is used here. idx_block_data_block_number = ( - session.query(IDXBlockDataBlockNumber).filter(IDXBlockDataBlockNumber.chain_id == str(config.CHAIN_ID)).first() + session.query(IDXBlockDataBlockNumber) + .filter(IDXBlockDataBlockNumber.chain_id == str(config.CHAIN_ID)) + .first() ) if idx_block_data_block_number is None: - return json_response({ - "result_set": { - "count": 0, - "offset": offset, - "limit": limit, - "total": 0 - }, - "block_data": [] - }) + return json_response( + { + "result_set": { + "count": 0, + "offset": offset, + "limit": limit, + "total": 0, + }, + "block_data": [], + } + ) total = idx_block_data_block_number.latest_block_number + 1 @@ -118,7 +107,10 @@ def list_block_data( # Search Filter if from_block_number is not None and to_block_number is not None: - query = query.filter(IDXBlockData.number >= from_block_number, IDXBlockData.number <= to_block_number) + query = query.filter( + IDXBlockData.number >= from_block_number, + IDXBlockData.number <= to_block_number, + ) elif from_block_number is not None: query = query.filter(IDXBlockData.number >= from_block_number) elif to_block_number is not None: @@ -144,25 +136,30 @@ def list_block_data( block_data_tmp: list[Type[IDXBlockData]] = query.all() block_data = [] for bd in block_data_tmp: - block_data.append({ - "number": bd.number, - "hash": bd.hash, - "transactions": bd.transactions, - "timestamp": bd.timestamp, - "gas_limit": bd.gas_limit, - "gas_used": bd.gas_used, - "size": bd.size - }) - - return json_response({ - "result_set": { - "count": count, - "offset": offset, - "limit": limit, - "total": total - }, - "block_data": block_data - }) + block_data.append( + { + "number": bd.number, + "hash": bd.hash, + "transactions": bd.transactions, + "timestamp": bd.timestamp, + "gas_limit": bd.gas_limit, + "gas_used": bd.gas_used, + "size": bd.size, + } + ) + + return json_response( + { + "result_set": { + "count": count, + "offset": offset, + "limit": limit, + "total": total, + }, + "block_data": block_data, + } + ) + # ------------------------------ # [BC-Explorer] Retrieve Block data @@ -172,46 +169,49 @@ def list_block_data( summary="[ibet Blockchain Explorer] Retrieve block data", operation_id="GetBlockData", response_model=BlockDataResponse, - responses=get_routers_responses(404) + responses=get_routers_responses(404), ) def get_block_data( block_number: NonNegativeInt = Path(description="Block number"), - session: Session = Depends(db_session) + session: Session = Depends(db_session), ): """ Returns block data in the specified block number. """ if BC_EXPLORER_ENABLED is False: - raise HTTPException(status_code=404, detail="This URL is not available in the current settings") + raise HTTPException( + status_code=404, detail="This URL is not available in the current settings" + ) block_data = ( - session.query(IDXBlockData). - filter(IDXBlockData.number == block_number). - first() + session.query(IDXBlockData).filter(IDXBlockData.number == block_number).first() ) if block_data is None: raise HTTPException(status_code=404, detail="block data not found") - return json_response({ - "number": block_data.number, - "parent_hash": block_data.parent_hash, - "sha3_uncles": block_data.sha3_uncles, - "miner": block_data.miner, - "state_root": block_data.state_root, - "transactions_root": block_data.transactions_root, - "receipts_root": block_data.receipts_root, - "logs_bloom": block_data.logs_bloom, - "difficulty": block_data.difficulty, - "gas_limit": block_data.gas_limit, - "gas_used": block_data.gas_used, - "timestamp": block_data.timestamp, - "proof_of_authority_data": block_data.proof_of_authority_data, - "mix_hash": block_data.mix_hash, - "nonce": block_data.nonce, - "hash": block_data.hash, - "size": block_data.size, - "transactions": block_data.transactions - }) + return json_response( + { + "number": block_data.number, + "parent_hash": block_data.parent_hash, + "sha3_uncles": block_data.sha3_uncles, + "miner": block_data.miner, + "state_root": block_data.state_root, + "transactions_root": block_data.transactions_root, + "receipts_root": block_data.receipts_root, + "logs_bloom": block_data.logs_bloom, + "difficulty": block_data.difficulty, + "gas_limit": block_data.gas_limit, + "gas_used": block_data.gas_used, + "timestamp": block_data.timestamp, + "proof_of_authority_data": block_data.proof_of_authority_data, + "mix_hash": block_data.mix_hash, + "nonce": block_data.nonce, + "hash": block_data.hash, + "size": block_data.size, + "transactions": block_data.transactions, + } + ) + # ------------------------------ # [BC-Explorer] List Tx data @@ -221,18 +221,19 @@ def get_block_data( summary="[ibet Blockchain Explorer] List tx data", operation_id="ListTxData", response_model=TxDataListResponse, - responses=get_routers_responses(404, ResponseLimitExceededError) + responses=get_routers_responses(404, ResponseLimitExceededError), ) def list_tx_data( - request_query: ListTxDataQuery = Depends(), - session: Session = Depends(db_session) + request_query: ListTxDataQuery = Depends(), session: Session = Depends(db_session) ): """ Returns a list of transactions by various search parameters. The maximum number of search results is 10000. """ if BC_EXPLORER_ENABLED is False: - raise HTTPException(status_code=404, detail="This URL is not available in the current settings") + raise HTTPException( + status_code=404, detail="This URL is not available in the current settings" + ) offset = request_query.offset limit = request_query.limit @@ -247,7 +248,9 @@ def list_tx_data( if block_number is not None: query = query.filter(IDXTxData.block_number == block_number) if from_address is not None: - query = query.filter(IDXTxData.from_address == to_checksum_address(from_address)) + query = query.filter( + IDXTxData.from_address == to_checksum_address(from_address) + ) if to_address is not None: query = query.filter(IDXTxData.to_address == to_checksum_address(to_address)) @@ -268,24 +271,28 @@ def list_tx_data( tx_data_tmp: list[Type[IDXTxData]] = query.all() tx_data = [] for txd in tx_data_tmp: - tx_data.append({ - "hash": txd.hash, - "block_hash": txd.block_hash, - "block_number": txd.block_number, - "transaction_index": txd.transaction_index, - "from_address": txd.from_address, - "to_address": txd.to_address - }) - - return json_response({ - "result_set": { - "count": count, - "offset": offset, - "limit": limit, - "total": total - }, - "tx_data": tx_data - }) + tx_data.append( + { + "hash": txd.hash, + "block_hash": txd.block_hash, + "block_number": txd.block_number, + "transaction_index": txd.transaction_index, + "from_address": txd.from_address, + "to_address": txd.to_address, + } + ) + + return json_response( + { + "result_set": { + "count": count, + "offset": offset, + "limit": limit, + "total": total, + }, + "tx_data": tx_data, + } + ) # ------------------------------ @@ -296,24 +303,22 @@ def list_tx_data( summary="[ibet Blockchain Explorer] Retrieve transaction data", operation_id="GetTxData", response_model=TxDataResponse, - responses=get_routers_responses(404) + responses=get_routers_responses(404), ) def get_tx_data( hash: str = Path(description="Transaction hash"), - session: Session = Depends(db_session) + session: Session = Depends(db_session), ): """ Searching for the transaction by transaction hash """ if BC_EXPLORER_ENABLED is False: - raise HTTPException(status_code=404, detail="This URL is not available in the current settings") + raise HTTPException( + status_code=404, detail="This URL is not available in the current settings" + ) # Search tx data - tx_data = ( - session.query(IDXTxData). - filter(IDXTxData.hash == hash). - first() - ) + tx_data = session.query(IDXTxData).filter(IDXTxData.hash == hash).first() if tx_data is None: raise HTTPException(status_code=404, detail="block data not found") @@ -322,32 +327,33 @@ def get_tx_data( contract_function: str | None = None contract_parameters: dict | None = None token_contract = ( - session.query(Token). - filter(Token.token_address == tx_data.to_address). - first() + session.query(Token).filter(Token.token_address == tx_data.to_address).first() ) if token_contract is not None: contract_name = token_contract.type contract = ContractUtils.get_contract( - contract_name=contract_name, - contract_address=tx_data.to_address + contract_name=contract_name, contract_address=tx_data.to_address ) - decoded_input: Tuple['ContractFunction', Dict[str, Any]] = contract.decode_function_input(tx_data.input) + decoded_input: Tuple[ + "ContractFunction", Dict[str, Any] + ] = contract.decode_function_input(tx_data.input) contract_function = decoded_input[0].fn_name contract_parameters = decoded_input[1] - return json_response({ - "hash": tx_data.hash, - "block_hash": tx_data.block_hash, - "block_number": tx_data.block_number, - "transaction_index": tx_data.transaction_index, - "from_address": tx_data.from_address, - "to_address": tx_data.to_address, - "contract_name": contract_name, - "contract_function": contract_function, - "contract_parameters": contract_parameters, - "gas": tx_data.gas, - "gas_price": tx_data.gas_price, - "value": tx_data.value, - "nonce": tx_data.nonce - }) + return json_response( + { + "hash": tx_data.hash, + "block_hash": tx_data.block_hash, + "block_number": tx_data.block_number, + "transaction_index": tx_data.transaction_index, + "from_address": tx_data.from_address, + "to_address": tx_data.to_address, + "contract_name": contract_name, + "contract_function": contract_function, + "contract_parameters": contract_parameters, + "gas": tx_data.gas, + "gas_price": tx_data.gas_price, + "value": tx_data.value, + "nonce": tx_data.nonce, + } + ) diff --git a/app/routers/bond.py b/app/routers/bond.py index 52cfca01..985edae5 100644 --- a/app/routers/bond.py +++ b/app/routers/bond.py @@ -18,143 +18,128 @@ """ import uuid from datetime import datetime -from typing import ( - List, - Optional, - Type -) +from typing import List, Optional, Type -from fastapi import ( - APIRouter, - Depends, - Header, - Query, - Request -) +from eth_keyfile import decode_keyfile_json +from fastapi import APIRouter, Depends, Header, Query, Request from fastapi.exceptions import HTTPException +from pytz import timezone from sqlalchemy import ( - desc, - case, + String, and_, - or_, - func, - literal_column, + case, cast, - String, + column, + desc, + func, literal, + literal_column, null, - column -) -from sqlalchemy.orm import ( - Session, - aliased + or_, ) -from eth_keyfile import decode_keyfile_json -from pytz import timezone +from sqlalchemy.orm import Session, aliased import config from app import log from app.database import db_session -from app.model.schema import ( - # Request - IbetStraightBondCreate, - IbetStraightBondUpdate, - IbetStraightBondTransfer, - IbetStraightBondAdditionalIssue, - IbetStraightBondRedeem, - RegisterPersonalInfoRequest, - IbetStraightBondScheduledUpdate, - UpdateTransferApprovalOperationType, - UpdateTransferApprovalRequest, - ListTransferHistorySortItem, - ListTransferHistoryQuery, - ListAllTokenLockEventsQuery, - ListAllTokenLockEventsSortItem, - LockEventCategory, - # Response - IbetStraightBondResponse, - TokenAddressResponse, - HolderResponse, - HolderCountResponse, - TransferHistoryResponse, - BulkTransferUploadIdResponse, - BulkTransferUploadResponse, - BulkTransferResponse, - ScheduledEventIdResponse, - ScheduledEventResponse, - TransferApprovalsResponse, - TransferApprovalHistoryResponse, - TransferApprovalTokenResponse, - BatchIssueRedeemUploadIdResponse, - GetBatchIssueRedeemResponse, - ListBatchIssueRedeemUploadResponse, - IssueRedeemHistoryResponse, - BatchRegisterPersonalInfoUploadResponse, - ListBatchRegisterPersonalInfoUploadResponse, - GetBatchRegisterPersonalInfoResponse, - ListAllTokenLockEventsResponse +from app.exceptions import ( + AuthorizationError, + ContractRevertError, + InvalidParameterError, + SendTransactionError, +) +from app.model.blockchain import ( + IbetSecurityTokenEscrow, + IbetStraightBondContract, + PersonalInfoContract, + TokenListContract, +) +from app.model.blockchain.tx_params.ibet_security_token_escrow import ( + ApproveTransferParams as EscrowApproveTransferParams, +) +from app.model.blockchain.tx_params.ibet_straight_bond import ( + AdditionalIssueParams, + ApproveTransferParams, + CancelTransferParams, + RedeemParams, + TransferParams, + UpdateParams, ) from app.model.db import ( + UTXO, Account, - Token, - TokenType, - UpdateToken, - IDXPosition, - IDXLockedPosition, - IDXPersonalInfo, + BatchIssueRedeem, + BatchIssueRedeemProcessingCategory, + BatchIssueRedeemUpload, + BatchRegisterPersonalInfo, + BatchRegisterPersonalInfoUpload, + BatchRegisterPersonalInfoUploadStatus, BulkTransfer, BulkTransferUpload, - IDXTransfer, - IDXTransferApproval, - IDXTransferApprovalsSortItem, IDXIssueRedeem, IDXIssueRedeemEventType, IDXIssueRedeemSortItem, + IDXLock, + IDXLockedPosition, + IDXPersonalInfo, + IDXPosition, + IDXTransfer, + IDXTransferApproval, + IDXTransferApprovalsSortItem, + IDXUnlock, ScheduledEvents, - UTXO, - BatchIssueRedeemUpload, - BatchIssueRedeem, - BatchIssueRedeemProcessingCategory, - BatchRegisterPersonalInfoUpload, - BatchRegisterPersonalInfoUploadStatus, - BatchRegisterPersonalInfo, + Token, + TokenType, TransferApprovalHistory, TransferApprovalOperationType, - IDXLock, - IDXUnlock -) -from app.model.blockchain import ( - IbetStraightBondContract, - TokenListContract, - PersonalInfoContract, - IbetSecurityTokenEscrow -) -from app.model.blockchain.tx_params.ibet_straight_bond import ( - UpdateParams, - TransferParams, - AdditionalIssueParams, - RedeemParams, - ApproveTransferParams, - CancelTransferParams + UpdateToken, ) -from app.model.blockchain.tx_params.ibet_security_token_escrow import ( - ApproveTransferParams as EscrowApproveTransferParams +from app.model.schema import ( # Request; Response + BatchIssueRedeemUploadIdResponse, + BatchRegisterPersonalInfoUploadResponse, + BulkTransferResponse, + BulkTransferUploadIdResponse, + BulkTransferUploadResponse, + GetBatchIssueRedeemResponse, + GetBatchRegisterPersonalInfoResponse, + HolderCountResponse, + HolderResponse, + IbetStraightBondAdditionalIssue, + IbetStraightBondCreate, + IbetStraightBondRedeem, + IbetStraightBondResponse, + IbetStraightBondScheduledUpdate, + IbetStraightBondTransfer, + IbetStraightBondUpdate, + IssueRedeemHistoryResponse, + ListAllTokenLockEventsQuery, + ListAllTokenLockEventsResponse, + ListAllTokenLockEventsSortItem, + ListBatchIssueRedeemUploadResponse, + ListBatchRegisterPersonalInfoUploadResponse, + ListTransferHistoryQuery, + ListTransferHistorySortItem, + LockEventCategory, + RegisterPersonalInfoRequest, + ScheduledEventIdResponse, + ScheduledEventResponse, + TokenAddressResponse, + TransferApprovalHistoryResponse, + TransferApprovalsResponse, + TransferApprovalTokenResponse, + TransferHistoryResponse, + UpdateTransferApprovalOperationType, + UpdateTransferApprovalRequest, ) -from app.utils.fastapi import json_response -from app.utils.contract_utils import ContractUtils from app.utils.check_utils import ( - validate_headers, address_is_valid_address, + check_auth, eoa_password_is_encrypted_value, - check_auth + validate_headers, ) +from app.utils.contract_utils import ContractUtils from app.utils.docs_utils import get_routers_responses -from app.exceptions import ( - InvalidParameterError, - SendTransactionError, - ContractRevertError, - AuthorizationError -) +from app.utils.fastapi import json_response router = APIRouter( prefix="/bond", @@ -169,21 +154,24 @@ @router.post( "/tokens", response_model=TokenAddressResponse, - responses=get_routers_responses(422, 401, AuthorizationError, SendTransactionError, ContractRevertError) + responses=get_routers_responses( + 422, 401, AuthorizationError, SendTransactionError, ContractRevertError + ), ) def issue_token( - request: Request, - token: IbetStraightBondCreate, - issuer_address: str = Header(...), - eoa_password: Optional[str] = Header(None), - auth_token: Optional[str] = Header(None), - db: Session = Depends(db_session)): + request: Request, + token: IbetStraightBondCreate, + issuer_address: str = Header(...), + eoa_password: Optional[str] = Header(None), + auth_token: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Issue ibetStraightBond token""" # Validate Headers validate_headers( issuer_address=(issuer_address, address_is_valid_address), - eoa_password=(eoa_password, eoa_password_is_encrypted_value) + eoa_password=(eoa_password, eoa_password_is_encrypted_value), ) # Authentication @@ -192,20 +180,23 @@ def issue_token( db=db, issuer_address=issuer_address, eoa_password=eoa_password, - auth_token=auth_token + auth_token=auth_token, ) # Get private key keyfile_json = _account.keyfile private_key = decode_keyfile_json( - raw_keyfile_json=keyfile_json, - password=decrypt_password.encode("utf-8") + raw_keyfile_json=keyfile_json, password=decrypt_password.encode("utf-8") ) # Deploy _symbol = token.symbol if token.symbol is not None else "" - _redemption_date = token.redemption_date if token.redemption_date is not None else "" - _redemption_value = token.redemption_value if token.redemption_value is not None else 0 + _redemption_date = ( + token.redemption_date if token.redemption_date is not None else "" + ) + _redemption_value = ( + token.redemption_value if token.redemption_value is not None else 0 + ) _return_date = token.return_date if token.return_date is not None else "" _return_amount = token.return_amount if token.return_amount is not None else "" arguments = [ @@ -217,13 +208,11 @@ def issue_token( _redemption_value, _return_date, _return_amount, - token.purpose + token.purpose, ] try: contract_address, abi, tx_hash = IbetStraightBondContract().create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) except SendTransactionError: raise SendTransactionError("failed to send transaction") @@ -240,7 +229,7 @@ def issue_token( "personal_info_contract_address", "contact_information", "privacy_policy", - "transfer_approval_required" + "transfer_approval_required", ] token_dict = token.__dict__ is_update = False @@ -269,7 +258,7 @@ def issue_token( token_address=contract_address, token_template=TokenType.IBET_STRAIGHT_BOND.value, tx_from=issuer_address, - private_key=private_key + private_key=private_key, ) except SendTransactionError: raise SendTransactionError("failed to register token address token list") @@ -309,21 +298,20 @@ def issue_token( db.commit() - return json_response({ - "token_address": _token.token_address, - "token_status": token_status - }) + return json_response( + {"token_address": _token.token_address, "token_status": token_status} + ) # GET: /bond/tokens @router.get( "/tokens", response_model=List[IbetStraightBondResponse], - responses=get_routers_responses(422) + responses=get_routers_responses(422), ) def list_all_tokens( - issuer_address: Optional[str] = Header(None), - db: Session = Depends(db_session)): + issuer_address: Optional[str] = Header(None), db: Session = Depends(db_session) +): """List all issued tokens""" # Validate Headers @@ -331,23 +319,29 @@ def list_all_tokens( # Get issued token list if issuer_address is None: - tokens = db.query(Token). \ - filter(Token.type == TokenType.IBET_STRAIGHT_BOND). \ - order_by(Token.id). \ - all() + tokens = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_STRAIGHT_BOND) + .order_by(Token.id) + .all() + ) else: - tokens = db.query(Token). \ - filter(Token.type == TokenType.IBET_STRAIGHT_BOND). \ - filter(Token.issuer_address == issuer_address). \ - order_by(Token.id). \ - all() + tokens = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_STRAIGHT_BOND) + .filter(Token.issuer_address == issuer_address) + .order_by(Token.id) + .all() + ) bond_tokens = [] for token in tokens: # Get contract data bond_token = IbetStraightBondContract(token.token_address).get().__dict__ issue_datetime_utc = timezone("UTC").localize(token.created) - bond_token["issue_datetime"] = issue_datetime_utc.astimezone(local_tz).isoformat() + bond_token["issue_datetime"] = issue_datetime_utc.astimezone( + local_tz + ).isoformat() bond_token["token_status"] = token.token_status bond_token.pop("contract_name") bond_tokens.append(bond_token) @@ -359,18 +353,18 @@ def list_all_tokens( @router.get( "/tokens/{token_address}", response_model=IbetStraightBondResponse, - responses=get_routers_responses(404, InvalidParameterError) + responses=get_routers_responses(404, InvalidParameterError), ) -def retrieve_token( - token_address: str, - db: Session = Depends(db_session)): +def retrieve_token(token_address: str, db: Session = Depends(db_session)): """Retrieve token""" # Get Token - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_STRAIGHT_BOND). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_STRAIGHT_BOND) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: @@ -390,22 +384,31 @@ def retrieve_token( @router.post( "/tokens/{token_address}", response_model=None, - responses=get_routers_responses(422, 401, 404, AuthorizationError, InvalidParameterError, SendTransactionError, ContractRevertError) + responses=get_routers_responses( + 422, + 401, + 404, + AuthorizationError, + InvalidParameterError, + SendTransactionError, + ContractRevertError, + ), ) def update_token( - request: Request, - token_address: str, - token: IbetStraightBondUpdate, - issuer_address: str = Header(...), - eoa_password: Optional[str] = Header(None), - auth_token: Optional[str] = Header(None), - db: Session = Depends(db_session)): + request: Request, + token_address: str, + token: IbetStraightBondUpdate, + issuer_address: str = Header(...), + eoa_password: Optional[str] = Header(None), + auth_token: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Update a token""" # Validate Headers validate_headers( issuer_address=(issuer_address, address_is_valid_address), - eoa_password=(eoa_password, eoa_password_is_encrypted_value) + eoa_password=(eoa_password, eoa_password_is_encrypted_value), ) # Authentication @@ -414,23 +417,24 @@ def update_token( db=db, issuer_address=issuer_address, eoa_password=eoa_password, - auth_token=auth_token + auth_token=auth_token, ) # Get private key keyfile_json = _account.keyfile private_key = decode_keyfile_json( - raw_keyfile_json=keyfile_json, - password=decrypt_password.encode("utf-8") + raw_keyfile_json=keyfile_json, password=decrypt_password.encode("utf-8") ) # Get Token - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_STRAIGHT_BOND). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_STRAIGHT_BOND) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: @@ -441,7 +445,7 @@ def update_token( IbetStraightBondContract(token_address).update( data=UpdateParams(**token.dict()), tx_from=issuer_address, - private_key=private_key + private_key=private_key, ) except SendTransactionError: raise SendTransactionError("failed to send transaction") @@ -454,32 +458,37 @@ def update_token( @router.get( "/tokens/{token_address}/additional_issue", response_model=IssueRedeemHistoryResponse, - responses=get_routers_responses(422, 404, InvalidParameterError) + responses=get_routers_responses(422, 404, InvalidParameterError), ) def list_additional_issuance_history( - token_address: str, - sort_item: IDXIssueRedeemSortItem = Query(IDXIssueRedeemSortItem.BLOCK_TIMESTAMP), - sort_order: int = Query(1, ge=0, le=1, description="0:asc, 1:desc"), - offset: Optional[int] = Query(None), - limit: Optional[int] = Query(None), - db: Session = Depends(db_session)): + token_address: str, + sort_item: IDXIssueRedeemSortItem = Query(IDXIssueRedeemSortItem.BLOCK_TIMESTAMP), + sort_order: int = Query(1, ge=0, le=1, description="0:asc, 1:desc"), + offset: Optional[int] = Query(None), + limit: Optional[int] = Query(None), + db: Session = Depends(db_session), +): """List additional issuance history""" # Get token - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_STRAIGHT_BOND). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_STRAIGHT_BOND) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: raise InvalidParameterError("this token is temporarily unavailable") # Get history record - query = db.query(IDXIssueRedeem). \ - filter(IDXIssueRedeem.event_type == IDXIssueRedeemEventType.ISSUE). \ - filter(IDXIssueRedeem.token_address == token_address) + query = ( + db.query(IDXIssueRedeem) + .filter(IDXIssueRedeem.event_type == IDXIssueRedeemEventType.ISSUE) + .filter(IDXIssueRedeem.token_address == token_address) + ) total = query.count() count = total @@ -503,46 +512,59 @@ def list_additional_issuance_history( history = [] for _event in _events: block_timestamp_utc = timezone("UTC").localize(_event.block_timestamp) - history.append({ - "transaction_hash": _event.transaction_hash, - "token_address": token_address, - "locked_address": _event.locked_address, - "target_address": _event.target_address, - "amount": _event.amount, - "block_timestamp": block_timestamp_utc.astimezone(local_tz).isoformat() - }) + history.append( + { + "transaction_hash": _event.transaction_hash, + "token_address": token_address, + "locked_address": _event.locked_address, + "target_address": _event.target_address, + "amount": _event.amount, + "block_timestamp": block_timestamp_utc.astimezone(local_tz).isoformat(), + } + ) - return json_response({ - "result_set": { - "count": count, - "offset": offset, - "limit": limit, - "total": total - }, - "history": history - }) + return json_response( + { + "result_set": { + "count": count, + "offset": offset, + "limit": limit, + "total": total, + }, + "history": history, + } + ) # POST: /bond/tokens/{token_address}/additional_issue @router.post( "/tokens/{token_address}/additional_issue", response_model=None, - responses=get_routers_responses(422, 401, 404, AuthorizationError, InvalidParameterError, SendTransactionError, ContractRevertError) + responses=get_routers_responses( + 422, + 401, + 404, + AuthorizationError, + InvalidParameterError, + SendTransactionError, + ContractRevertError, + ), ) def additional_issue( - request: Request, - token_address: str, - data: IbetStraightBondAdditionalIssue, - issuer_address: str = Header(...), - eoa_password: Optional[str] = Header(None), - auth_token: Optional[str] = Header(None), - db: Session = Depends(db_session)): + request: Request, + token_address: str, + data: IbetStraightBondAdditionalIssue, + issuer_address: str = Header(...), + eoa_password: Optional[str] = Header(None), + auth_token: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Additional issue""" # Validate Headers validate_headers( issuer_address=(issuer_address, address_is_valid_address), - eoa_password=(eoa_password, eoa_password_is_encrypted_value) + eoa_password=(eoa_password, eoa_password_is_encrypted_value), ) # Authentication @@ -551,23 +573,24 @@ def additional_issue( db=db, issuer_address=issuer_address, eoa_password=eoa_password, - auth_token=auth_token + auth_token=auth_token, ) # Get private key keyfile_json = _account.keyfile private_key = decode_keyfile_json( - raw_keyfile_json=keyfile_json, - password=decrypt_password.encode("utf-8") + raw_keyfile_json=keyfile_json, password=decrypt_password.encode("utf-8") ) # Get Token - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_STRAIGHT_BOND). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_STRAIGHT_BOND) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: @@ -578,7 +601,7 @@ def additional_issue( IbetStraightBondContract(token_address).additional_issue( data=AdditionalIssueParams(**data.dict()), tx_from=issuer_address, - private_key=private_key + private_key=private_key, ) except SendTransactionError: raise SendTransactionError("failed to send transaction") @@ -590,7 +613,7 @@ def additional_issue( @router.get( "/tokens/{token_address}/additional_issue/batch", response_model=ListBatchIssueRedeemUploadResponse, - responses=get_routers_responses(422) + responses=get_routers_responses(422), ) def list_all_additional_issue_upload( token_address: str, @@ -599,13 +622,17 @@ def list_all_additional_issue_upload( offset: Optional[int] = Query(None), limit: Optional[int] = Query(None), issuer_address: Optional[str] = Header(None), - db: Session = Depends(db_session) + db: Session = Depends(db_session), ): # Get a list of uploads - query = db.query(BatchIssueRedeemUpload). \ - filter(BatchIssueRedeemUpload.token_address == token_address). \ - filter(BatchIssueRedeemUpload.token_type == TokenType.IBET_STRAIGHT_BOND). \ - filter(BatchIssueRedeemUpload.category == BatchIssueRedeemProcessingCategory.ISSUE) + query = ( + db.query(BatchIssueRedeemUpload) + .filter(BatchIssueRedeemUpload.token_address == token_address) + .filter(BatchIssueRedeemUpload.token_type == TokenType.IBET_STRAIGHT_BOND) + .filter( + BatchIssueRedeemUpload.category == BatchIssueRedeemProcessingCategory.ISSUE + ) + ) if issuer_address is not None: query = query.filter(BatchIssueRedeemUpload.issuer_address == issuer_address) @@ -634,23 +661,25 @@ def list_all_additional_issue_upload( uploads = [] for _upload in _upload_list: created_utc = timezone("UTC").localize(_upload.created) - uploads.append({ - "batch_id": _upload.upload_id, - "issuer_address": _upload.issuer_address, - "token_type": _upload.token_type, - "token_address": _upload.token_address, - "processed": _upload.processed, - "created": created_utc.astimezone(local_tz).isoformat() - }) + uploads.append( + { + "batch_id": _upload.upload_id, + "issuer_address": _upload.issuer_address, + "token_type": _upload.token_type, + "token_address": _upload.token_address, + "processed": _upload.processed, + "created": created_utc.astimezone(local_tz).isoformat(), + } + ) resp = { "result_set": { "count": count, "offset": offset, "limit": limit, - "total": total + "total": total, }, - "uploads": uploads + "uploads": uploads, } return json_response(resp) @@ -659,22 +688,25 @@ def list_all_additional_issue_upload( @router.post( "/tokens/{token_address}/additional_issue/batch", response_model=BatchIssueRedeemUploadIdResponse, - responses=get_routers_responses(422, 401, 404, AuthorizationError, InvalidParameterError) + responses=get_routers_responses( + 422, 401, 404, AuthorizationError, InvalidParameterError + ), ) def additional_issue_in_batch( - request: Request, - token_address: str, - data: List[IbetStraightBondAdditionalIssue], - issuer_address: str = Header(...), - auth_token: Optional[str] = Header(None), - eoa_password: Optional[str] = Header(None), - db: Session = Depends(db_session)): + request: Request, + token_address: str, + data: List[IbetStraightBondAdditionalIssue], + issuer_address: str = Header(...), + auth_token: Optional[str] = Header(None), + eoa_password: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Additional issue (Batch)""" # Validate Headers validate_headers( issuer_address=(issuer_address, address_is_valid_address), - eoa_password=(eoa_password, eoa_password_is_encrypted_value) + eoa_password=(eoa_password, eoa_password_is_encrypted_value), ) # Validate params @@ -687,16 +719,18 @@ def additional_issue_in_batch( db=db, issuer_address=issuer_address, eoa_password=eoa_password, - auth_token=auth_token + auth_token=auth_token, ) # Check token status - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_STRAIGHT_BOND). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_STRAIGHT_BOND) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: @@ -725,87 +759,96 @@ def additional_issue_in_batch( db.commit() - return json_response({ - "batch_id": str(upload_id) - }) + return json_response({"batch_id": str(upload_id)}) # GET: /bond/tokens/{token_address}/additional_issue/batch/{batch_id} @router.get( "/tokens/{token_address}/additional_issue/batch/{batch_id}", response_model=GetBatchIssueRedeemResponse, - responses=get_routers_responses(422, 404) + responses=get_routers_responses(422, 404), ) def retrieve_batch_additional_issue( - token_address: str, - batch_id: str, - issuer_address: str = Header(...), - db: Session = Depends(db_session)): + token_address: str, + batch_id: str, + issuer_address: str = Header(...), + db: Session = Depends(db_session), +): """Get Batch status for additional issue""" # Validate Headers - validate_headers( - issuer_address=(issuer_address, address_is_valid_address) - ) + validate_headers(issuer_address=(issuer_address, address_is_valid_address)) # Upload Existence Check - batch: Optional[BatchIssueRedeemUpload] = db.query(BatchIssueRedeemUpload). \ - filter(BatchIssueRedeemUpload.upload_id == batch_id). \ - filter(BatchIssueRedeemUpload.issuer_address == issuer_address). \ - filter(BatchIssueRedeemUpload.token_type == TokenType.IBET_STRAIGHT_BOND). \ - filter(BatchIssueRedeemUpload.token_address == token_address). \ - filter(BatchIssueRedeemUpload.category == BatchIssueRedeemProcessingCategory.ISSUE). \ - first() + batch: Optional[BatchIssueRedeemUpload] = ( + db.query(BatchIssueRedeemUpload) + .filter(BatchIssueRedeemUpload.upload_id == batch_id) + .filter(BatchIssueRedeemUpload.issuer_address == issuer_address) + .filter(BatchIssueRedeemUpload.token_type == TokenType.IBET_STRAIGHT_BOND) + .filter(BatchIssueRedeemUpload.token_address == token_address) + .filter( + BatchIssueRedeemUpload.category == BatchIssueRedeemProcessingCategory.ISSUE + ) + .first() + ) if batch is None: raise HTTPException(status_code=404, detail="batch not found") # Get Batch Records - record_list: List[Type[BatchIssueRedeem]] = db.query(BatchIssueRedeem). \ - filter(BatchIssueRedeem.upload_id == batch_id). \ - all() + record_list: List[Type[BatchIssueRedeem]] = ( + db.query(BatchIssueRedeem).filter(BatchIssueRedeem.upload_id == batch_id).all() + ) - return json_response({ - "processed": batch.processed, - "results": [ - { - "account_address": record.account_address, - "amount": record.amount, - "status": record.status - } for record in record_list - ] - }) + return json_response( + { + "processed": batch.processed, + "results": [ + { + "account_address": record.account_address, + "amount": record.amount, + "status": record.status, + } + for record in record_list + ], + } + ) # GET: /bond/tokens/{token_address}/redeem @router.get( "/tokens/{token_address}/redeem", response_model=IssueRedeemHistoryResponse, - responses=get_routers_responses(422, 404, InvalidParameterError) + responses=get_routers_responses(422, 404, InvalidParameterError), ) def list_redeem_history( - token_address: str, - sort_item: IDXIssueRedeemSortItem = Query(IDXIssueRedeemSortItem.BLOCK_TIMESTAMP), - sort_order: int = Query(1, ge=0, le=1, description="0:asc, 1:desc"), - offset: Optional[int] = Query(None), - limit: Optional[int] = Query(None), - db: Session = Depends(db_session)): + token_address: str, + sort_item: IDXIssueRedeemSortItem = Query(IDXIssueRedeemSortItem.BLOCK_TIMESTAMP), + sort_order: int = Query(1, ge=0, le=1, description="0:asc, 1:desc"), + offset: Optional[int] = Query(None), + limit: Optional[int] = Query(None), + db: Session = Depends(db_session), +): """List redemption history""" # Get token - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_STRAIGHT_BOND). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_STRAIGHT_BOND) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: raise InvalidParameterError("this token is temporarily unavailable") # Get history record - query = db.query(IDXIssueRedeem). \ - filter(IDXIssueRedeem.event_type == IDXIssueRedeemEventType.REDEEM). \ - filter(IDXIssueRedeem.token_address == token_address) + query = ( + db.query(IDXIssueRedeem) + .filter(IDXIssueRedeem.event_type == IDXIssueRedeemEventType.REDEEM) + .filter(IDXIssueRedeem.token_address == token_address) + ) total = query.count() count = total @@ -829,46 +872,59 @@ def list_redeem_history( history = [] for _event in _events: block_timestamp_utc = timezone("UTC").localize(_event.block_timestamp) - history.append({ - "transaction_hash": _event.transaction_hash, - "token_address": token_address, - "locked_address": _event.locked_address, - "target_address": _event.target_address, - "amount": _event.amount, - "block_timestamp": block_timestamp_utc.astimezone(local_tz).isoformat() - }) + history.append( + { + "transaction_hash": _event.transaction_hash, + "token_address": token_address, + "locked_address": _event.locked_address, + "target_address": _event.target_address, + "amount": _event.amount, + "block_timestamp": block_timestamp_utc.astimezone(local_tz).isoformat(), + } + ) - return json_response({ - "result_set": { - "count": count, - "offset": offset, - "limit": limit, - "total": total - }, - "history": history - }) + return json_response( + { + "result_set": { + "count": count, + "offset": offset, + "limit": limit, + "total": total, + }, + "history": history, + } + ) # POST: /bond/tokens/{token_address}/redeem @router.post( "/tokens/{token_address}/redeem", response_model=None, - responses=get_routers_responses(422, 401, 404, AuthorizationError, InvalidParameterError, SendTransactionError, ContractRevertError) + responses=get_routers_responses( + 422, + 401, + 404, + AuthorizationError, + InvalidParameterError, + SendTransactionError, + ContractRevertError, + ), ) def redeem_token( - request: Request, - token_address: str, - data: IbetStraightBondRedeem, - issuer_address: str = Header(...), - eoa_password: Optional[str] = Header(None), - auth_token: Optional[str] = Header(None), - db: Session = Depends(db_session)): + request: Request, + token_address: str, + data: IbetStraightBondRedeem, + issuer_address: str = Header(...), + eoa_password: Optional[str] = Header(None), + auth_token: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Redeem a token""" # Validate Headers validate_headers( issuer_address=(issuer_address, address_is_valid_address), - eoa_password=(eoa_password, eoa_password_is_encrypted_value) + eoa_password=(eoa_password, eoa_password_is_encrypted_value), ) # Authentication @@ -877,23 +933,24 @@ def redeem_token( db=db, issuer_address=issuer_address, eoa_password=eoa_password, - auth_token=auth_token + auth_token=auth_token, ) # Get private key keyfile_json = _account.keyfile private_key = decode_keyfile_json( - raw_keyfile_json=keyfile_json, - password=decrypt_password.encode("utf-8") + raw_keyfile_json=keyfile_json, password=decrypt_password.encode("utf-8") ) # Get Token - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_STRAIGHT_BOND). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_STRAIGHT_BOND) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: @@ -904,7 +961,7 @@ def redeem_token( IbetStraightBondContract(token_address).redeem( data=RedeemParams(**data.dict()), tx_from=issuer_address, - private_key=private_key + private_key=private_key, ) except SendTransactionError: raise SendTransactionError("failed to send transaction") @@ -916,7 +973,7 @@ def redeem_token( @router.get( "/tokens/{token_address}/redeem/batch", response_model=ListBatchIssueRedeemUploadResponse, - responses=get_routers_responses(422) + responses=get_routers_responses(422), ) def list_all_redeem_upload( token_address: str, @@ -925,13 +982,17 @@ def list_all_redeem_upload( offset: Optional[int] = Query(None), limit: Optional[int] = Query(None), issuer_address: Optional[str] = Header(None), - db: Session = Depends(db_session) + db: Session = Depends(db_session), ): # Get a list of uploads - query = db.query(BatchIssueRedeemUpload). \ - filter(BatchIssueRedeemUpload.token_address == token_address). \ - filter(BatchIssueRedeemUpload.token_type == TokenType.IBET_STRAIGHT_BOND). \ - filter(BatchIssueRedeemUpload.category == BatchIssueRedeemProcessingCategory.REDEEM) + query = ( + db.query(BatchIssueRedeemUpload) + .filter(BatchIssueRedeemUpload.token_address == token_address) + .filter(BatchIssueRedeemUpload.token_type == TokenType.IBET_STRAIGHT_BOND) + .filter( + BatchIssueRedeemUpload.category == BatchIssueRedeemProcessingCategory.REDEEM + ) + ) if issuer_address is not None: query = query.filter(BatchIssueRedeemUpload.issuer_address == issuer_address) @@ -960,23 +1021,25 @@ def list_all_redeem_upload( uploads = [] for _upload in _upload_list: created_utc = timezone("UTC").localize(_upload.created) - uploads.append({ - "batch_id": _upload.upload_id, - "issuer_address": _upload.issuer_address, - "token_type": _upload.token_type, - "token_address": _upload.token_address, - "processed": _upload.processed, - "created": created_utc.astimezone(local_tz).isoformat() - }) + uploads.append( + { + "batch_id": _upload.upload_id, + "issuer_address": _upload.issuer_address, + "token_type": _upload.token_type, + "token_address": _upload.token_address, + "processed": _upload.processed, + "created": created_utc.astimezone(local_tz).isoformat(), + } + ) resp = { "result_set": { "count": count, "offset": offset, "limit": limit, - "total": total + "total": total, }, - "uploads": uploads + "uploads": uploads, } return json_response(resp) @@ -985,22 +1048,25 @@ def list_all_redeem_upload( @router.post( "/tokens/{token_address}/redeem/batch", response_model=BatchIssueRedeemUploadIdResponse, - responses=get_routers_responses(422, 401, 404, AuthorizationError, InvalidParameterError) + responses=get_routers_responses( + 422, 401, 404, AuthorizationError, InvalidParameterError + ), ) def redeem_token_in_batch( - request: Request, - token_address: str, - data: List[IbetStraightBondRedeem], - issuer_address: str = Header(...), - eoa_password: Optional[str] = Header(None), - auth_token: Optional[str] = Header(None), - db: Session = Depends(db_session)): + request: Request, + token_address: str, + data: List[IbetStraightBondRedeem], + issuer_address: str = Header(...), + eoa_password: Optional[str] = Header(None), + auth_token: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Redeem a token (Batch)""" # Validate Headers validate_headers( issuer_address=(issuer_address, address_is_valid_address), - eoa_password=(eoa_password, eoa_password_is_encrypted_value) + eoa_password=(eoa_password, eoa_password_is_encrypted_value), ) # Validate params @@ -1013,16 +1079,18 @@ def redeem_token_in_batch( db=db, issuer_address=issuer_address, eoa_password=eoa_password, - auth_token=auth_token + auth_token=auth_token, ) # Check token status - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_STRAIGHT_BOND). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_STRAIGHT_BOND) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: @@ -1051,96 +1119,109 @@ def redeem_token_in_batch( db.commit() - return json_response({ - "batch_id": str(upload_id) - }) + return json_response({"batch_id": str(upload_id)}) # GET: /bond/tokens/{token_address}/redeem/batch/{batch_id} @router.get( "/tokens/{token_address}/redeem/batch/{batch_id}", response_model=GetBatchIssueRedeemResponse, - responses=get_routers_responses(422, 404) + responses=get_routers_responses(422, 404), ) def retrieve_batch_redeem( - token_address: str, - batch_id: str, - issuer_address: str = Header(...), - db: Session = Depends(db_session)): + token_address: str, + batch_id: str, + issuer_address: str = Header(...), + db: Session = Depends(db_session), +): """Get Batch status for additional issue""" # Validate Headers - validate_headers( - issuer_address=(issuer_address, address_is_valid_address) - ) + validate_headers(issuer_address=(issuer_address, address_is_valid_address)) # Upload Existence Check - batch: Optional[BatchIssueRedeemUpload] = db.query(BatchIssueRedeemUpload). \ - filter(BatchIssueRedeemUpload.upload_id == batch_id). \ - filter(BatchIssueRedeemUpload.issuer_address == issuer_address). \ - filter(BatchIssueRedeemUpload.token_type == TokenType.IBET_STRAIGHT_BOND). \ - filter(BatchIssueRedeemUpload.token_address == token_address). \ - filter(BatchIssueRedeemUpload.category == BatchIssueRedeemProcessingCategory.REDEEM). \ - first() + batch: Optional[BatchIssueRedeemUpload] = ( + db.query(BatchIssueRedeemUpload) + .filter(BatchIssueRedeemUpload.upload_id == batch_id) + .filter(BatchIssueRedeemUpload.issuer_address == issuer_address) + .filter(BatchIssueRedeemUpload.token_type == TokenType.IBET_STRAIGHT_BOND) + .filter(BatchIssueRedeemUpload.token_address == token_address) + .filter( + BatchIssueRedeemUpload.category == BatchIssueRedeemProcessingCategory.REDEEM + ) + .first() + ) if batch is None: raise HTTPException(status_code=404, detail="batch not found") # Get Batch Records - record_list: List[Type[BatchIssueRedeem]] = db.query(BatchIssueRedeem). \ - filter(BatchIssueRedeem.upload_id == batch_id). \ - all() + record_list: List[Type[BatchIssueRedeem]] = ( + db.query(BatchIssueRedeem).filter(BatchIssueRedeem.upload_id == batch_id).all() + ) - return json_response({ - "processed": batch.processed, - "results": [ - { - "account_address": record.account_address, - "amount": record.amount, - "status": record.status - } for record in record_list - ] - }) + return json_response( + { + "processed": batch.processed, + "results": [ + { + "account_address": record.account_address, + "amount": record.amount, + "status": record.status, + } + for record in record_list + ], + } + ) # GET: /bond/tokens/{token_address}/scheduled_events @router.get( "/tokens/{token_address}/scheduled_events", - response_model=List[ScheduledEventResponse] + response_model=List[ScheduledEventResponse], ) def list_all_scheduled_events( - token_address: str, - issuer_address: Optional[str] = Header(None), - db: Session = Depends(db_session)): + token_address: str, + issuer_address: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """List all scheduled update events""" if issuer_address is None: - _token_events = db.query(ScheduledEvents). \ - filter(ScheduledEvents.token_type == TokenType.IBET_STRAIGHT_BOND). \ - filter(ScheduledEvents.token_address == token_address). \ - order_by(ScheduledEvents.id). \ - all() + _token_events = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.token_type == TokenType.IBET_STRAIGHT_BOND) + .filter(ScheduledEvents.token_address == token_address) + .order_by(ScheduledEvents.id) + .all() + ) else: - _token_events = db.query(ScheduledEvents). \ - filter(ScheduledEvents.token_type == TokenType.IBET_STRAIGHT_BOND). \ - filter(ScheduledEvents.issuer_address == issuer_address). \ - filter(ScheduledEvents.token_address == token_address). \ - order_by(ScheduledEvents.id). \ - all() + _token_events = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.token_type == TokenType.IBET_STRAIGHT_BOND) + .filter(ScheduledEvents.issuer_address == issuer_address) + .filter(ScheduledEvents.token_address == token_address) + .order_by(ScheduledEvents.id) + .all() + ) token_events = [] for _token_event in _token_events: - scheduled_datetime_utc = timezone("UTC").localize(_token_event.scheduled_datetime) + scheduled_datetime_utc = timezone("UTC").localize( + _token_event.scheduled_datetime + ) created_utc = timezone("UTC").localize(_token_event.created) token_events.append( { "scheduled_event_id": _token_event.event_id, "token_address": token_address, "token_type": TokenType.IBET_STRAIGHT_BOND.value, - "scheduled_datetime": scheduled_datetime_utc.astimezone(local_tz).isoformat(), + "scheduled_datetime": scheduled_datetime_utc.astimezone( + local_tz + ).isoformat(), "event_type": _token_event.event_type, "status": _token_event.status, "data": _token_event.data, - "created": created_utc.astimezone(local_tz).isoformat() + "created": created_utc.astimezone(local_tz).isoformat(), } ) return json_response(token_events) @@ -1150,22 +1231,25 @@ def list_all_scheduled_events( @router.post( "/tokens/{token_address}/scheduled_events", response_model=ScheduledEventIdResponse, - responses=get_routers_responses(422, 401, 404, AuthorizationError, InvalidParameterError) + responses=get_routers_responses( + 422, 401, 404, AuthorizationError, InvalidParameterError + ), ) def schedule_new_update_event( - request: Request, - token_address: str, - event_data: IbetStraightBondScheduledUpdate, - issuer_address: str = Header(...), - eoa_password: Optional[str] = Header(None), - auth_token: Optional[str] = Header(None), - db: Session = Depends(db_session)): + request: Request, + token_address: str, + event_data: IbetStraightBondScheduledUpdate, + issuer_address: str = Header(...), + eoa_password: Optional[str] = Header(None), + auth_token: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Register a new update event""" # Validate Headers validate_headers( issuer_address=(issuer_address, address_is_valid_address), - eoa_password=(eoa_password, eoa_password_is_encrypted_value) + eoa_password=(eoa_password, eoa_password_is_encrypted_value), ) # Authentication @@ -1174,16 +1258,18 @@ def schedule_new_update_event( db=db, issuer_address=issuer_address, eoa_password=eoa_password, - auth_token=auth_token + auth_token=auth_token, ) # Verify that the token is issued by the issuer - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_STRAIGHT_BOND). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_STRAIGHT_BOND) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: @@ -1202,74 +1288,82 @@ def schedule_new_update_event( db.add(_scheduled_event) db.commit() - return json_response({ - "scheduled_event_id": _scheduled_event.event_id - }) + return json_response({"scheduled_event_id": _scheduled_event.event_id}) # GET: /bond/tokens/{token_address}/scheduled_events/{scheduled_event_id} @router.get( "/tokens/{token_address}/scheduled_events/{scheduled_event_id}", response_model=ScheduledEventResponse, - responses=get_routers_responses(404) + responses=get_routers_responses(404), ) def retrieve_token_event( - scheduled_event_id: str, - token_address: str, - issuer_address: Optional[str] = Header(None), - db: Session = Depends(db_session)): + scheduled_event_id: str, + token_address: str, + issuer_address: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Retrieve a scheduled token event""" if issuer_address is None: - _token_event = db.query(ScheduledEvents). \ - filter(ScheduledEvents.token_type == TokenType.IBET_STRAIGHT_BOND). \ - filter(ScheduledEvents.event_id == scheduled_event_id). \ - filter(ScheduledEvents.token_address == token_address). \ - first() + _token_event = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.token_type == TokenType.IBET_STRAIGHT_BOND) + .filter(ScheduledEvents.event_id == scheduled_event_id) + .filter(ScheduledEvents.token_address == token_address) + .first() + ) else: - _token_event = db.query(ScheduledEvents). \ - filter(ScheduledEvents.token_type == TokenType.IBET_STRAIGHT_BOND). \ - filter(ScheduledEvents.event_id == scheduled_event_id). \ - filter(ScheduledEvents.issuer_address == issuer_address). \ - filter(ScheduledEvents.token_address == token_address). \ - first() + _token_event = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.token_type == TokenType.IBET_STRAIGHT_BOND) + .filter(ScheduledEvents.event_id == scheduled_event_id) + .filter(ScheduledEvents.issuer_address == issuer_address) + .filter(ScheduledEvents.token_address == token_address) + .first() + ) if _token_event is None: raise HTTPException(status_code=404, detail="event not found") scheduled_datetime_utc = timezone("UTC").localize(_token_event.scheduled_datetime) created_utc = timezone("UTC").localize(_token_event.created) - return json_response({ - "scheduled_event_id": _token_event.event_id, - "token_address": token_address, - "token_type": TokenType.IBET_STRAIGHT_BOND.value, - "scheduled_datetime": scheduled_datetime_utc.astimezone(local_tz).isoformat(), - "event_type": _token_event.event_type, - "status": _token_event.status, - "data": _token_event.data, - "created": created_utc.astimezone(local_tz).isoformat() - }) + return json_response( + { + "scheduled_event_id": _token_event.event_id, + "token_address": token_address, + "token_type": TokenType.IBET_STRAIGHT_BOND.value, + "scheduled_datetime": scheduled_datetime_utc.astimezone( + local_tz + ).isoformat(), + "event_type": _token_event.event_type, + "status": _token_event.status, + "data": _token_event.data, + "created": created_utc.astimezone(local_tz).isoformat(), + } + ) # DELETE: /bond/tokens/{token_address}/scheduled_events/{scheduled_event_id} @router.delete( "/tokens/{token_address}/scheduled_events/{scheduled_event_id}", response_model=ScheduledEventResponse, - responses=get_routers_responses(422, 401, 404, AuthorizationError) + responses=get_routers_responses(422, 401, 404, AuthorizationError), ) def delete_scheduled_event( - request: Request, - token_address: str, - scheduled_event_id: str, - issuer_address: str = Header(...), - eoa_password: Optional[str] = Header(None), - auth_token: Optional[str] = Header(None), - db: Session = Depends(db_session)): + request: Request, + token_address: str, + scheduled_event_id: str, + issuer_address: str = Header(...), + eoa_password: Optional[str] = Header(None), + auth_token: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Delete a scheduled event""" # Validate Headers validate_headers( issuer_address=(issuer_address, address_is_valid_address), - eoa_password=(eoa_password, eoa_password_is_encrypted_value) + eoa_password=(eoa_password, eoa_password_is_encrypted_value), ) # Authorization @@ -1278,16 +1372,18 @@ def delete_scheduled_event( db=db, issuer_address=issuer_address, eoa_password=eoa_password, - auth_token=auth_token + auth_token=auth_token, ) # Delete an event - _token_event = db.query(ScheduledEvents). \ - filter(ScheduledEvents.token_type == TokenType.IBET_STRAIGHT_BOND). \ - filter(ScheduledEvents.event_id == scheduled_event_id). \ - filter(ScheduledEvents.issuer_address == issuer_address). \ - filter(ScheduledEvents.token_address == token_address). \ - first() + _token_event = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.token_type == TokenType.IBET_STRAIGHT_BOND) + .filter(ScheduledEvents.event_id == scheduled_event_id) + .filter(ScheduledEvents.issuer_address == issuer_address) + .filter(ScheduledEvents.token_address == token_address) + .first() + ) if _token_event is None: raise HTTPException(status_code=404, detail="event not found") @@ -1301,7 +1397,7 @@ def delete_scheduled_event( "event_type": _token_event.event_type, "status": _token_event.status, "data": _token_event.data, - "created": created_utc.astimezone(local_tz).isoformat() + "created": created_utc.astimezone(local_tz).isoformat(), } db.delete(_token_event) @@ -1313,63 +1409,78 @@ def delete_scheduled_event( @router.get( "/tokens/{token_address}/holders", response_model=List[HolderResponse], - responses=get_routers_responses(422, InvalidParameterError, 404) + responses=get_routers_responses(422, InvalidParameterError, 404), ) def list_all_holders( - token_address: str, - include_former_holder: bool = False, - issuer_address: str = Header(...), - db: Session = Depends(db_session)): + token_address: str, + include_former_holder: bool = False, + issuer_address: str = Header(...), + db: Session = Depends(db_session), +): """List all bond token holders""" # Validate Headers validate_headers(issuer_address=(issuer_address, address_is_valid_address)) # Get Account - _account = db.query(Account). \ - filter(Account.issuer_address == issuer_address). \ - first() + _account = ( + db.query(Account).filter(Account.issuer_address == issuer_address).first() + ) if _account is None: raise InvalidParameterError("issuer does not exist") # Get Token - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_STRAIGHT_BOND). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_STRAIGHT_BOND) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: raise InvalidParameterError("this token is temporarily unavailable") # Get Holders - query = db.query(IDXPosition, func.sum(IDXLockedPosition.value)). \ - outerjoin( + query = ( + db.query(IDXPosition, func.sum(IDXLockedPosition.value)) + .outerjoin( IDXLockedPosition, - and_(IDXLockedPosition.token_address == IDXPosition.token_address, - IDXLockedPosition.account_address == IDXPosition.account_address) - ). \ - filter(IDXPosition.token_address == token_address).\ - group_by(IDXPosition.id, IDXLockedPosition.token_address, IDXLockedPosition.account_address) + and_( + IDXLockedPosition.token_address == IDXPosition.token_address, + IDXLockedPosition.account_address == IDXPosition.account_address, + ), + ) + .filter(IDXPosition.token_address == token_address) + .group_by( + IDXPosition.id, + IDXLockedPosition.token_address, + IDXLockedPosition.account_address, + ) + ) if not include_former_holder: - query = query.filter(or_( - IDXPosition.balance != 0, - IDXPosition.exchange_balance != 0, - IDXPosition.pending_transfer != 0, - IDXPosition.exchange_commitment != 0, - IDXLockedPosition.value != 0 - )) + query = query.filter( + or_( + IDXPosition.balance != 0, + IDXPosition.exchange_balance != 0, + IDXPosition.pending_transfer != 0, + IDXPosition.exchange_commitment != 0, + IDXLockedPosition.value != 0, + ) + ) _holders = query.order_by(IDXPosition.id).all() # Get personal information - _personal_info_list = db.query(IDXPersonalInfo). \ - filter(IDXPersonalInfo.issuer_address == issuer_address). \ - order_by(IDXPersonalInfo.id). \ - all() + _personal_info_list = ( + db.query(IDXPersonalInfo) + .filter(IDXPersonalInfo.issuer_address == issuer_address) + .order_by(IDXPersonalInfo.id) + .all() + ) _personal_info_dict = {} for item in _personal_info_list: _personal_info_dict[item.account_address] = item.personal_info @@ -1382,24 +1493,25 @@ def list_all_holders( "email": None, "birth": None, "is_corporate": None, - "tax_category": None + "tax_category": None, } holders = [] for _position, _locked in _holders: _personal_info = _personal_info_dict.get( - _position.account_address, - personal_info_default - ) - holders.append({ - "account_address": _position.account_address, - "personal_information": _personal_info, - "balance": _position.balance, - "exchange_balance": _position.exchange_balance, - "exchange_commitment": _position.exchange_commitment, - "pending_transfer": _position.pending_transfer, - "locked": _locked if _locked is not None else 0 - }) + _position.account_address, personal_info_default + ) + holders.append( + { + "account_address": _position.account_address, + "personal_information": _personal_info, + "balance": _position.balance, + "exchange_balance": _position.exchange_balance, + "exchange_commitment": _position.exchange_commitment, + "pending_transfer": _position.pending_transfer, + "locked": _locked if _locked is not None else 0, + } + ) return json_response(holders) @@ -1408,105 +1520,127 @@ def list_all_holders( @router.get( "/tokens/{token_address}/holders/count", response_model=HolderCountResponse, - responses=get_routers_responses(422, InvalidParameterError, 404) + responses=get_routers_responses(422, InvalidParameterError, 404), ) def count_number_of_holders( - token_address: str, - issuer_address: str = Header(...), - db: Session = Depends(db_session)): + token_address: str, + issuer_address: str = Header(...), + db: Session = Depends(db_session), +): """Count the number of holders""" # Validate Headers validate_headers(issuer_address=(issuer_address, address_is_valid_address)) # Get Account - _account = db.query(Account). \ - filter(Account.issuer_address == issuer_address). \ - first() + _account = ( + db.query(Account).filter(Account.issuer_address == issuer_address).first() + ) if _account is None: raise InvalidParameterError("issuer does not exist") # Get Token - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_STRAIGHT_BOND). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_STRAIGHT_BOND) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: raise InvalidParameterError("this token is temporarily unavailable") # Get Holders - _count: int = db.query(IDXPosition, func.sum(IDXLockedPosition.value)). \ - outerjoin( + _count: int = ( + db.query(IDXPosition, func.sum(IDXLockedPosition.value)) + .outerjoin( IDXLockedPosition, - and_(IDXLockedPosition.token_address == IDXPosition.token_address, - IDXLockedPosition.account_address == IDXPosition.account_address) - ). \ - filter(IDXPosition.token_address == token_address). \ - filter( - or_(IDXPosition.balance != 0, + and_( + IDXLockedPosition.token_address == IDXPosition.token_address, + IDXLockedPosition.account_address == IDXPosition.account_address, + ), + ) + .filter(IDXPosition.token_address == token_address) + .filter( + or_( + IDXPosition.balance != 0, IDXPosition.exchange_balance != 0, IDXPosition.pending_transfer != 0, IDXPosition.exchange_commitment != 0, - IDXLockedPosition.value != 0) - ). \ - group_by(IDXPosition.id, IDXLockedPosition.token_address, IDXLockedPosition.account_address). \ - count() + IDXLockedPosition.value != 0, + ) + ) + .group_by( + IDXPosition.id, + IDXLockedPosition.token_address, + IDXLockedPosition.account_address, + ) + .count() + ) - return json_response({ - "count": _count - }) + return json_response({"count": _count}) # GET: /bond/tokens/{token_address}/holders/{account_address} @router.get( "/tokens/{token_address}/holders/{account_address}", response_model=HolderResponse, - responses=get_routers_responses(422, InvalidParameterError, 404) + responses=get_routers_responses(422, InvalidParameterError, 404), ) def retrieve_holder( - token_address: str, - account_address: str, - issuer_address: str = Header(...), - db: Session = Depends(db_session)): + token_address: str, + account_address: str, + issuer_address: str = Header(...), + db: Session = Depends(db_session), +): """Retrieve bond token holder""" # Validate Headers validate_headers(issuer_address=(issuer_address, address_is_valid_address)) # Get Issuer - _account = db.query(Account). \ - filter(Account.issuer_address == issuer_address). \ - first() + _account = ( + db.query(Account).filter(Account.issuer_address == issuer_address).first() + ) if _account is None: raise InvalidParameterError("issuer does not exist") # Get Token - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_STRAIGHT_BOND). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_STRAIGHT_BOND) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: raise InvalidParameterError("this token is temporarily unavailable") # Get Holders - _holder = db.query(IDXPosition, func.sum(IDXLockedPosition.value)). \ - outerjoin( + _holder = ( + db.query(IDXPosition, func.sum(IDXLockedPosition.value)) + .outerjoin( IDXLockedPosition, - and_(IDXLockedPosition.token_address == IDXPosition.token_address, - IDXLockedPosition.account_address == IDXPosition.account_address) - ). \ - filter(IDXPosition.token_address == token_address). \ - filter(IDXPosition.account_address == account_address). \ - group_by(IDXPosition.id, IDXLockedPosition.token_address, IDXLockedPosition.account_address). \ - first() + and_( + IDXLockedPosition.token_address == IDXPosition.token_address, + IDXLockedPosition.account_address == IDXPosition.account_address, + ), + ) + .filter(IDXPosition.token_address == token_address) + .filter(IDXPosition.account_address == account_address) + .group_by( + IDXPosition.id, + IDXLockedPosition.token_address, + IDXLockedPosition.account_address, + ) + .first() + ) if _holder is None: balance = 0 @@ -1530,12 +1664,14 @@ def retrieve_holder( "email": None, "birth": None, "is_corporate": None, - "tax_category": None + "tax_category": None, } - _personal_info_record = db.query(IDXPersonalInfo). \ - filter(IDXPersonalInfo.account_address == account_address). \ - filter(IDXPersonalInfo.issuer_address == issuer_address). \ - first() + _personal_info_record = ( + db.query(IDXPersonalInfo) + .filter(IDXPersonalInfo.account_address == account_address) + .filter(IDXPersonalInfo.issuer_address == issuer_address) + .first() + ) if _personal_info_record is None: _personal_info = personal_info_default else: @@ -1548,7 +1684,7 @@ def retrieve_holder( "exchange_balance": exchange_balance, "exchange_commitment": exchange_commitment, "pending_transfer": pending_transfer, - "locked": locked if locked is not None else 0 + "locked": locked if locked is not None else 0, } return json_response(holder) @@ -1558,22 +1694,31 @@ def retrieve_holder( @router.post( "/tokens/{token_address}/personal_info", response_model=None, - responses=get_routers_responses(422, 401, 404, AuthorizationError, InvalidParameterError, SendTransactionError, ContractRevertError) + responses=get_routers_responses( + 422, + 401, + 404, + AuthorizationError, + InvalidParameterError, + SendTransactionError, + ContractRevertError, + ), ) def register_holder_personal_info( - request: Request, - token_address: str, - personal_info: RegisterPersonalInfoRequest, - issuer_address: str = Header(...), - eoa_password: Optional[str] = Header(None), - auth_token: Optional[str] = Header(None), - db: Session = Depends(db_session)): + request: Request, + token_address: str, + personal_info: RegisterPersonalInfoRequest, + issuer_address: str = Header(...), + eoa_password: Optional[str] = Header(None), + auth_token: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Register the holder's personal information""" # Validate Headers validate_headers( issuer_address=(issuer_address, address_is_valid_address), - eoa_password=(eoa_password, eoa_password_is_encrypted_value) + eoa_password=(eoa_password, eoa_password_is_encrypted_value), ) # Authentication @@ -1582,16 +1727,18 @@ def register_holder_personal_info( db=db, issuer_address=issuer_address, eoa_password=eoa_password, - auth_token=auth_token + auth_token=auth_token, ) # Verify that the token is issued by the issuer_address - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_STRAIGHT_BOND). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_STRAIGHT_BOND) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: @@ -1603,12 +1750,12 @@ def register_holder_personal_info( personal_info_contract = PersonalInfoContract( db=db, issuer_address=issuer_address, - contract_address=token_contract.personal_info_contract_address + contract_address=token_contract.personal_info_contract_address, ) personal_info_contract.register_info( account_address=personal_info.account_address, data=personal_info.dict(), - default_value=None + default_value=None, ) except SendTransactionError: raise SendTransactionError("failed to register personal information") @@ -1620,33 +1767,37 @@ def register_holder_personal_info( @router.get( "/tokens/{token_address}/personal_info/batch", response_model=ListBatchRegisterPersonalInfoUploadResponse, - responses=get_routers_responses(422, 404, InvalidParameterError) + responses=get_routers_responses(422, 404, InvalidParameterError), ) def list_all_personal_info_batch_registration_uploads( - token_address: str, - issuer_address: str = Header(...), - status: Optional[str] = Query(None), - sort_order: int = Query(1, ge=0, le=1, description="0:asc, 1:desc (created)"), - offset: Optional[int] = Query(None), - limit: Optional[int] = Query(None), - db: Session = Depends(db_session)): + token_address: str, + issuer_address: str = Header(...), + status: Optional[str] = Query(None), + sort_order: int = Query(1, ge=0, le=1, description="0:asc, 1:desc (created)"), + offset: Optional[int] = Query(None), + limit: Optional[int] = Query(None), + db: Session = Depends(db_session), +): """List all personal information batch registration uploads""" # Verify that the token is issued by the issuer_address - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_STRAIGHT_BOND). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_STRAIGHT_BOND) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: raise InvalidParameterError("this token is temporarily unavailable") # Get a list of uploads - query = db.query(BatchRegisterPersonalInfoUpload). \ - filter(BatchRegisterPersonalInfoUpload.issuer_address == issuer_address) + query = db.query(BatchRegisterPersonalInfoUpload).filter( + BatchRegisterPersonalInfoUpload.issuer_address == issuer_address + ) total = query.count() @@ -1672,44 +1823,51 @@ def list_all_personal_info_batch_registration_uploads( uploads = [] for _upload in _upload_list: created_utc = timezone("UTC").localize(_upload.created) - uploads.append({ - "batch_id": _upload.upload_id, - "issuer_address": _upload.issuer_address, - "status": _upload.status, - "created": created_utc.astimezone(local_tz).isoformat() - }) - - return json_response({ - "result_set": { - "count": count, - "offset": offset, - "limit": limit, - "total": total - }, - "uploads": uploads - }) + uploads.append( + { + "batch_id": _upload.upload_id, + "issuer_address": _upload.issuer_address, + "status": _upload.status, + "created": created_utc.astimezone(local_tz).isoformat(), + } + ) + + return json_response( + { + "result_set": { + "count": count, + "offset": offset, + "limit": limit, + "total": total, + }, + "uploads": uploads, + } + ) # POST: /bond/tokens/{token_address}/personal_info/batch @router.post( "/tokens/{token_address}/personal_info/batch", response_model=BatchRegisterPersonalInfoUploadResponse, - responses=get_routers_responses(422, 401, 404, AuthorizationError, InvalidParameterError) + responses=get_routers_responses( + 422, 401, 404, AuthorizationError, InvalidParameterError + ), ) def batch_register_personal_info( - request: Request, - token_address: str, - personal_info_list: List[RegisterPersonalInfoRequest], - issuer_address: str = Header(...), - eoa_password: Optional[str] = Header(None), - auth_token: Optional[str] = Header(None), - db: Session = Depends(db_session)): + request: Request, + token_address: str, + personal_info_list: List[RegisterPersonalInfoRequest], + issuer_address: str = Header(...), + eoa_password: Optional[str] = Header(None), + auth_token: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Create Batch for register personal information""" # Validate Headers validate_headers( issuer_address=(issuer_address, address_is_valid_address), - eoa_password=(eoa_password, eoa_password_is_encrypted_value) + eoa_password=(eoa_password, eoa_password_is_encrypted_value), ) # Authentication @@ -1718,16 +1876,18 @@ def batch_register_personal_info( db=db, issuer_address=issuer_address, eoa_password=eoa_password, - auth_token=auth_token + auth_token=auth_token, ) # Verify that the token is issued by the issuer_address - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_STRAIGHT_BOND). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_STRAIGHT_BOND) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: @@ -1753,62 +1913,73 @@ def batch_register_personal_info( db.commit() - return json_response({ - "batch_id": batch_id, - "status": batch.status, - "created": timezone("UTC").localize(batch.created).astimezone(local_tz).isoformat() - }) + return json_response( + { + "batch_id": batch_id, + "status": batch.status, + "created": timezone("UTC") + .localize(batch.created) + .astimezone(local_tz) + .isoformat(), + } + ) # GET: /bond/tokens/{token_address}/personal_info/batch/{batch_id} @router.get( "/tokens/{token_address}/personal_info/batch/{batch_id}", response_model=GetBatchRegisterPersonalInfoResponse, - responses=get_routers_responses(422, 401, 404) + responses=get_routers_responses(422, 401, 404), ) def retrieve_batch_register_personal_info( - token_address: str, - batch_id: str, - issuer_address: str = Header(...), - db: Session = Depends(db_session)): + token_address: str, + batch_id: str, + issuer_address: str = Header(...), + db: Session = Depends(db_session), +): """Get Batch status for register personal information""" # Validate Headers - validate_headers( - issuer_address=(issuer_address, address_is_valid_address) - ) + validate_headers(issuer_address=(issuer_address, address_is_valid_address)) # Upload Existence Check - batch: Optional[BatchRegisterPersonalInfoUpload] = db.query(BatchRegisterPersonalInfoUpload). \ - filter(BatchRegisterPersonalInfoUpload.upload_id == batch_id). \ - filter(BatchRegisterPersonalInfoUpload.issuer_address == issuer_address). \ - first() + batch: Optional[BatchRegisterPersonalInfoUpload] = ( + db.query(BatchRegisterPersonalInfoUpload) + .filter(BatchRegisterPersonalInfoUpload.upload_id == batch_id) + .filter(BatchRegisterPersonalInfoUpload.issuer_address == issuer_address) + .first() + ) if batch is None: raise HTTPException(status_code=404, detail="batch not found") # Get Batch Records - record_list = db.query(BatchRegisterPersonalInfo). \ - filter(BatchRegisterPersonalInfo.upload_id == batch_id). \ - filter(BatchRegisterPersonalInfo.token_address == token_address). \ - all() - - return json_response({ - "status": batch.status, - "results": [ - { - "status": record.status, - "account_address": record.account_address, - "key_manager": record.personal_info.get("key_manager"), - "name": record.personal_info.get("name"), - "postal_code": record.personal_info.get("postal_code"), - "address": record.personal_info.get("address"), - "email": record.personal_info.get("email"), - "birth": record.personal_info.get("birth"), - "is_corporate": record.personal_info.get("is_corporate"), - "tax_category": record.personal_info.get("tax_category") - } for record in record_list - ] - }) + record_list = ( + db.query(BatchRegisterPersonalInfo) + .filter(BatchRegisterPersonalInfo.upload_id == batch_id) + .filter(BatchRegisterPersonalInfo.token_address == token_address) + .all() + ) + + return json_response( + { + "status": batch.status, + "results": [ + { + "status": record.status, + "account_address": record.account_address, + "key_manager": record.personal_info.get("key_manager"), + "name": record.personal_info.get("name"), + "postal_code": record.personal_info.get("postal_code"), + "address": record.personal_info.get("address"), + "email": record.personal_info.get("email"), + "birth": record.personal_info.get("birth"), + "is_corporate": record.personal_info.get("is_corporate"), + "tax_category": record.personal_info.get("tax_category"), + } + for record in record_list + ], + } + ) # GET: /bond/tokens/{token_address}/lock_events @@ -1816,13 +1987,13 @@ def retrieve_batch_register_personal_info( "/tokens/{token_address}/lock_events", summary="List all lock/unlock events related to given bond token", response_model=ListAllTokenLockEventsResponse, - responses=get_routers_responses(422) + responses=get_routers_responses(422), ) def list_all_lock_events_by_bond( token_address: str, issuer_address: Optional[str] = Header(None), request_query: ListAllTokenLockEventsQuery = Depends(), - db: Session = Depends(db_session) + db: Session = Depends(db_session), ): # Validate Headers validate_headers(issuer_address=(issuer_address, address_is_valid_address)) @@ -1845,19 +2016,21 @@ def list_all_lock_events_by_bond( IDXLock.value.label("value"), IDXLock.data.label("data"), IDXLock.block_timestamp.label("block_timestamp"), - Token - ). - join(Token, IDXLock.token_address == Token.token_address). - filter(Token.type == TokenType.IBET_STRAIGHT_BOND). - filter(Token.token_address == token_address). - filter(Token.token_status != 2) + Token, + ) + .join(Token, IDXLock.token_address == Token.token_address) + .filter(Token.type == TokenType.IBET_STRAIGHT_BOND) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) ) if issuer_address is not None: query_lock = query_lock.filter(Token.issuer_address == issuer_address) query_unlock = ( db.query( - literal(value=LockEventCategory.Unlock.value, type_=String).label("category"), + literal(value=LockEventCategory.Unlock.value, type_=String).label( + "category" + ), IDXUnlock.transaction_hash.label("transaction_hash"), IDXUnlock.token_address.label("token_address"), IDXUnlock.lock_address.label("lock_address"), @@ -1866,12 +2039,12 @@ def list_all_lock_events_by_bond( IDXUnlock.value.label("value"), IDXUnlock.data.label("data"), IDXUnlock.block_timestamp.label("block_timestamp"), - Token - ). - join(Token, IDXUnlock.token_address == Token.token_address). - filter(Token.type == TokenType.IBET_STRAIGHT_BOND). - filter(Token.token_address == token_address). - filter(Token.token_status != 2) + Token, + ) + .join(Token, IDXUnlock.token_address == Token.token_address) + .filter(Token.type == TokenType.IBET_STRAIGHT_BOND) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) ) if issuer_address is not None: query_unlock = query_unlock.filter(Token.issuer_address == issuer_address) @@ -1892,7 +2065,9 @@ def list_all_lock_events_by_bond( if request_query.lock_address is not None: query = query.filter(column("lock_address") == request_query.lock_address) if request_query.recipient_address is not None: - query = query.filter(column("recipient_address") == request_query.recipient_address) + query = query.filter( + column("recipient_address") == request_query.recipient_address + ) count = query.count() @@ -1905,7 +2080,9 @@ def list_all_lock_events_by_bond( if sort_item != ListAllTokenLockEventsSortItem.block_timestamp.value: # NOTE: Set secondary sort for consistent results - query = query.order_by(desc(column(ListAllTokenLockEventsSortItem.block_timestamp.value))) + query = query.order_by( + desc(column(ListAllTokenLockEventsSortItem.block_timestamp.value)) + ) # Pagination if offset is not None: @@ -1922,29 +2099,31 @@ def list_all_lock_events_by_bond( token_name = _bond.name block_timestamp_utc = timezone("UTC").localize(lock_event[8]) - resp_data.append({ - "category": lock_event[0], - "transaction_hash": lock_event[1], - "issuer_address": _token.issuer_address, - "token_address": lock_event[2], - "token_type": _token.type, - "token_name": token_name, - "lock_address": lock_event[3], - "account_address": lock_event[4], - "recipient_address": lock_event[5], - "value": lock_event[6], - "data": lock_event[7], - "block_timestamp": block_timestamp_utc.astimezone(local_tz).isoformat() - }) + resp_data.append( + { + "category": lock_event[0], + "transaction_hash": lock_event[1], + "issuer_address": _token.issuer_address, + "token_address": lock_event[2], + "token_type": _token.type, + "token_name": token_name, + "lock_address": lock_event[3], + "account_address": lock_event[4], + "recipient_address": lock_event[5], + "value": lock_event[6], + "data": lock_event[7], + "block_timestamp": block_timestamp_utc.astimezone(local_tz).isoformat(), + } + ) data = { "result_set": { "count": count, "offset": offset, "limit": limit, - "total": total + "total": total, }, - "events": resp_data + "events": resp_data, } return json_response(data) @@ -1953,21 +2132,29 @@ def list_all_lock_events_by_bond( @router.post( "/transfers", response_model=None, - responses=get_routers_responses(422, 401, AuthorizationError, InvalidParameterError, SendTransactionError, ContractRevertError) + responses=get_routers_responses( + 422, + 401, + AuthorizationError, + InvalidParameterError, + SendTransactionError, + ContractRevertError, + ), ) def transfer_ownership( - request: Request, - token: IbetStraightBondTransfer, - issuer_address: str = Header(...), - eoa_password: Optional[str] = Header(None), - auth_token: Optional[str] = Header(None), - db: Session = Depends(db_session)): + request: Request, + token: IbetStraightBondTransfer, + issuer_address: str = Header(...), + eoa_password: Optional[str] = Header(None), + auth_token: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Transfer token ownership""" # Validate Headers validate_headers( issuer_address=(issuer_address, address_is_valid_address), - eoa_password=(eoa_password, eoa_password_is_encrypted_value) + eoa_password=(eoa_password, eoa_password_is_encrypted_value), ) # Authentication @@ -1976,23 +2163,24 @@ def transfer_ownership( db=db, issuer_address=issuer_address, eoa_password=eoa_password, - auth_token=auth_token + auth_token=auth_token, ) # Get private key keyfile_json = _account.keyfile private_key = decode_keyfile_json( - raw_keyfile_json=keyfile_json, - password=decrypt_password.encode("utf-8") + raw_keyfile_json=keyfile_json, password=decrypt_password.encode("utf-8") ) # Verify that the token is issued by the issuer_address - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_STRAIGHT_BOND). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_address == token.token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_STRAIGHT_BOND) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_address == token.token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise InvalidParameterError("token not found") if _token.token_status == 0: @@ -2002,7 +2190,7 @@ def transfer_ownership( IbetStraightBondContract(token.token_address).transfer( data=TransferParams(**token.dict()), tx_from=issuer_address, - private_key=private_key + private_key=private_key, ) except SendTransactionError: raise SendTransactionError("failed to send transaction") @@ -2014,34 +2202,37 @@ def transfer_ownership( @router.get( "/transfers/{token_address}", response_model=TransferHistoryResponse, - responses=get_routers_responses(422, 404, InvalidParameterError) + responses=get_routers_responses(422, 404, InvalidParameterError), ) def list_transfer_history( token_address: str, request_query: ListTransferHistoryQuery = Depends(), - db: Session = Depends(db_session) + db: Session = Depends(db_session), ): """List token transfer history""" # Get token - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_STRAIGHT_BOND). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_STRAIGHT_BOND) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: raise InvalidParameterError("this token is temporarily unavailable") # Get transfer history - query = db.query(IDXTransfer). \ - filter(IDXTransfer.token_address == token_address) + query = db.query(IDXTransfer).filter(IDXTransfer.token_address == token_address) total = query.count() if request_query.source_event is not None: query = query.filter(IDXTransfer.source_event == request_query.source_event) if request_query.data is not None: - query = query.filter(cast(IDXTransfer.data, String).like("%" + request_query.data + "%")) + query = query.filter( + cast(IDXTransfer.data, String).like("%" + request_query.data + "%") + ) count = query.count() # Sort @@ -2064,39 +2255,43 @@ def list_transfer_history( transfer_history = [] for _transfer in _transfers: block_timestamp_utc = timezone("UTC").localize(_transfer.block_timestamp) - transfer_history.append({ - "transaction_hash": _transfer.transaction_hash, - "token_address": token_address, - "from_address": _transfer.from_address, - "to_address": _transfer.to_address, - "amount": _transfer.amount, - "source_event": _transfer.source_event, - "data": _transfer.data, - "block_timestamp": block_timestamp_utc.astimezone(local_tz).isoformat() - }) - - return json_response({ - "result_set": { - "count": count, - "offset": request_query.offset, - "limit": request_query.limit, - "total": total - }, - "transfer_history": transfer_history - }) + transfer_history.append( + { + "transaction_hash": _transfer.transaction_hash, + "token_address": token_address, + "from_address": _transfer.from_address, + "to_address": _transfer.to_address, + "amount": _transfer.amount, + "source_event": _transfer.source_event, + "data": _transfer.data, + "block_timestamp": block_timestamp_utc.astimezone(local_tz).isoformat(), + } + ) + + return json_response( + { + "result_set": { + "count": count, + "offset": request_query.offset, + "limit": request_query.limit, + "total": total, + }, + "transfer_history": transfer_history, + } + ) # GET: /bond/transfer_approvals @router.get( "/transfer_approvals", response_model=TransferApprovalsResponse, - responses=get_routers_responses(422) + responses=get_routers_responses(422), ) def list_transfer_approval_history( issuer_address: Optional[str] = Header(None), offset: Optional[int] = Query(None), limit: Optional[int] = Query(None), - db: Session = Depends(db_session) + db: Session = Depends(db_session), ): """List transfer approval history""" # Create a subquery for 'status' added IDXTransferApproval @@ -2107,54 +2302,71 @@ def list_transfer_approval_history( TransferApprovalHistory, case( ( - and_(IDXTransferApproval.escrow_finished == True, - IDXTransferApproval.transfer_approved == None, - TransferApprovalHistory.operation_type == None), - 1 + and_( + IDXTransferApproval.escrow_finished == True, + IDXTransferApproval.transfer_approved == None, + TransferApprovalHistory.operation_type == None, + ), + 1, ), # EscrowFinish(escrow_finished) ( - and_(IDXTransferApproval.transfer_approved == None, - TransferApprovalHistory.operation_type == TransferApprovalOperationType.APPROVE.value), - 2 + and_( + IDXTransferApproval.transfer_approved == None, + TransferApprovalHistory.operation_type + == TransferApprovalOperationType.APPROVE.value, + ), + 2, ), # Approve(operation completed, event synchronizing) ( IDXTransferApproval.transfer_approved == True, - 2 + 2, ), # Approve(transferred) ( - and_(IDXTransferApproval.cancelled == None, - TransferApprovalHistory.operation_type == TransferApprovalOperationType.CANCEL.value), - 3 + and_( + IDXTransferApproval.cancelled == None, + TransferApprovalHistory.operation_type + == TransferApprovalOperationType.CANCEL.value, + ), + 3, ), # Cancel(operation completed, event synchronizing) - ( - IDXTransferApproval.cancelled == True, - 3 - ), # Cancel(canceled) - else_=0 # ApplyFor(unapproved) - ).label("status") - ).outerjoin( + (IDXTransferApproval.cancelled == True, 3), # Cancel(canceled) + else_=0, # ApplyFor(unapproved) + ).label("status"), + ) + .outerjoin( TransferApprovalHistory, - and_(IDXTransferApproval.token_address == TransferApprovalHistory.token_address, - IDXTransferApproval.exchange_address == TransferApprovalHistory.exchange_address, - IDXTransferApproval.application_id == TransferApprovalHistory.application_id) - ).subquery() + and_( + IDXTransferApproval.token_address + == TransferApprovalHistory.token_address, + IDXTransferApproval.exchange_address + == TransferApprovalHistory.exchange_address, + IDXTransferApproval.application_id + == TransferApprovalHistory.application_id, + ), + ) + .subquery(), ) # Get transfer approval history - query = db.query(Token.issuer_address, - subquery.token_address, - func.count(subquery.id), - func.count(or_(literal_column("status") == 0, None)), - func.count(or_(literal_column("status") == 1, None)), - func.count(or_(literal_column("status") == 2, None)), - func.count(or_(literal_column("status") == 3, None))). \ - join(Token, subquery.token_address == Token.token_address). \ - filter(Token.type == TokenType.IBET_STRAIGHT_BOND). \ - filter(Token.token_status != 2) + query = ( + db.query( + Token.issuer_address, + subquery.token_address, + func.count(subquery.id), + func.count(or_(literal_column("status") == 0, None)), + func.count(or_(literal_column("status") == 1, None)), + func.count(or_(literal_column("status") == 2, None)), + func.count(or_(literal_column("status") == 3, None)), + ) + .join(Token, subquery.token_address == Token.token_address) + .filter(Token.type == TokenType.IBET_STRAIGHT_BOND) + .filter(Token.token_status != 2) + ) if issuer_address is not None: query = query.filter(Token.issuer_address == issuer_address) - query = query.group_by(Token.issuer_address, subquery.token_address). \ - order_by(Token.issuer_address, subquery.token_address) + query = query.group_by(Token.issuer_address, subquery.token_address).order_by( + Token.issuer_address, subquery.token_address + ) total = query.count() # NOTE: Because no filtering is performed, `total` and `count` have the same value. @@ -2168,59 +2380,73 @@ def list_transfer_approval_history( _transfer_approvals = query.all() transfer_approvals = [] - for issuer_address, token_address, application_count, \ - unapproved_count, escrow_finished_count, transferred_count, canceled_count \ - in _transfer_approvals: - transfer_approvals.append({ - "issuer_address": issuer_address, - "token_address": token_address, - "application_count": application_count, - "unapproved_count": unapproved_count, - "escrow_finished_count": escrow_finished_count, - "transferred_count": transferred_count, - "canceled_count": canceled_count, - }) - - return json_response({ - "result_set": { - "count": count, - "offset": offset, - "limit": limit, - "total": total - }, - "transfer_approvals": transfer_approvals - }) + for ( + issuer_address, + token_address, + application_count, + unapproved_count, + escrow_finished_count, + transferred_count, + canceled_count, + ) in _transfer_approvals: + transfer_approvals.append( + { + "issuer_address": issuer_address, + "token_address": token_address, + "application_count": application_count, + "unapproved_count": unapproved_count, + "escrow_finished_count": escrow_finished_count, + "transferred_count": transferred_count, + "canceled_count": canceled_count, + } + ) + + return json_response( + { + "result_set": { + "count": count, + "offset": offset, + "limit": limit, + "total": total, + }, + "transfer_approvals": transfer_approvals, + } + ) # GET: /bond/transfer_approvals/{token_address} @router.get( "/transfer_approvals/{token_address}", response_model=TransferApprovalHistoryResponse, - responses=get_routers_responses(422, 404, InvalidParameterError) + responses=get_routers_responses(422, 404, InvalidParameterError), ) def list_token_transfer_approval_history( - token_address: str, - from_address: Optional[str] = Query(None), - to_address: Optional[str] = Query(None), - status: Optional[List[int]] = Query( - None, - ge=0, - le=3, - description="0:unapproved, 1:escrow_finished, 2:transferred, 3:canceled" - ), - sort_item: Optional[IDXTransferApprovalsSortItem] = Query(IDXTransferApprovalsSortItem.ID), - sort_order: Optional[int] = Query(1, ge=0, le=1, description="0:asc, 1:desc"), - offset: Optional[int] = Query(None), - limit: Optional[int] = Query(None), - db: Session = Depends(db_session) + token_address: str, + from_address: Optional[str] = Query(None), + to_address: Optional[str] = Query(None), + status: Optional[List[int]] = Query( + None, + ge=0, + le=3, + description="0:unapproved, 1:escrow_finished, 2:transferred, 3:canceled", + ), + sort_item: Optional[IDXTransferApprovalsSortItem] = Query( + IDXTransferApprovalsSortItem.ID + ), + sort_order: Optional[int] = Query(1, ge=0, le=1, description="0:asc, 1:desc"), + offset: Optional[int] = Query(None), + limit: Optional[int] = Query(None), + db: Session = Depends(db_session), ): """List token transfer approval history""" # Get token - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_STRAIGHT_BOND). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_STRAIGHT_BOND) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: @@ -2234,42 +2460,55 @@ def list_token_transfer_approval_history( TransferApprovalHistory, case( ( - and_(IDXTransferApproval.escrow_finished == True, - IDXTransferApproval.transfer_approved == None, - TransferApprovalHistory.operation_type == None), - 1 + and_( + IDXTransferApproval.escrow_finished == True, + IDXTransferApproval.transfer_approved == None, + TransferApprovalHistory.operation_type == None, + ), + 1, ), # EscrowFinish(escrow_finished) ( - and_(IDXTransferApproval.transfer_approved == None, - TransferApprovalHistory.operation_type == TransferApprovalOperationType.APPROVE), - 2 + and_( + IDXTransferApproval.transfer_approved == None, + TransferApprovalHistory.operation_type + == TransferApprovalOperationType.APPROVE, + ), + 2, ), # Approve(operation completed, event synchronizing) ( IDXTransferApproval.transfer_approved == True, - 2 + 2, ), # Approve(transferred) ( - and_(IDXTransferApproval.cancelled == None, - TransferApprovalHistory.operation_type == TransferApprovalOperationType.CANCEL), - 3 + and_( + IDXTransferApproval.cancelled == None, + TransferApprovalHistory.operation_type + == TransferApprovalOperationType.CANCEL, + ), + 3, ), # Cancel(operation completed, event synchronizing) - ( - IDXTransferApproval.cancelled == True, - 3 - ), # Cancel(canceled) - else_=0 # ApplyFor(unapproved) - ).label("status") - ).outerjoin( + (IDXTransferApproval.cancelled == True, 3), # Cancel(canceled) + else_=0, # ApplyFor(unapproved) + ).label("status"), + ) + .outerjoin( TransferApprovalHistory, - and_(IDXTransferApproval.token_address == TransferApprovalHistory.token_address, - IDXTransferApproval.exchange_address == TransferApprovalHistory.exchange_address, - IDXTransferApproval.application_id == TransferApprovalHistory.application_id) - ).subquery() + and_( + IDXTransferApproval.token_address + == TransferApprovalHistory.token_address, + IDXTransferApproval.exchange_address + == TransferApprovalHistory.exchange_address, + IDXTransferApproval.application_id + == TransferApprovalHistory.application_id, + ), + ) + .subquery(), ) # Get transfer approval history - query = db.query(subquery, literal_column("status")). \ - filter(subquery.token_address == token_address) + query = db.query(subquery, literal_column("status")).filter( + subquery.token_address == token_address + ) total = query.count() # Search Filter @@ -2323,75 +2562,99 @@ def list_token_transfer_approval_history( else: issuer_cancelable = True - application_datetime_utc = timezone("UTC").localize(_transfer_approval.application_datetime) + application_datetime_utc = timezone("UTC").localize( + _transfer_approval.application_datetime + ) application_datetime = application_datetime_utc.astimezone(local_tz).isoformat() - application_blocktimestamp_utc = timezone("UTC").localize(_transfer_approval.application_blocktimestamp) - application_blocktimestamp = application_blocktimestamp_utc.astimezone(local_tz).isoformat() + application_blocktimestamp_utc = timezone("UTC").localize( + _transfer_approval.application_blocktimestamp + ) + application_blocktimestamp = application_blocktimestamp_utc.astimezone( + local_tz + ).isoformat() if _transfer_approval.approval_datetime is not None: - approval_datetime_utc = timezone("UTC").localize(_transfer_approval.approval_datetime) + approval_datetime_utc = timezone("UTC").localize( + _transfer_approval.approval_datetime + ) approval_datetime = approval_datetime_utc.astimezone(local_tz).isoformat() else: approval_datetime = None if _transfer_approval.approval_blocktimestamp is not None: - approval_blocktimestamp_utc = timezone("UTC").localize(_transfer_approval.approval_blocktimestamp) - approval_blocktimestamp = approval_blocktimestamp_utc.astimezone(local_tz).isoformat() + approval_blocktimestamp_utc = timezone("UTC").localize( + _transfer_approval.approval_blocktimestamp + ) + approval_blocktimestamp = approval_blocktimestamp_utc.astimezone( + local_tz + ).isoformat() else: approval_blocktimestamp = None - transfer_approval_history.append({ - "id": _transfer_approval.id, - "token_address": token_address, - "exchange_address": _transfer_approval.exchange_address, - "application_id": _transfer_approval.application_id, - "from_address": _transfer_approval.from_address, - "to_address": _transfer_approval.to_address, - "amount": _transfer_approval.amount, - "application_datetime": application_datetime, - "application_blocktimestamp": application_blocktimestamp, - "approval_datetime": approval_datetime, - "approval_blocktimestamp": approval_blocktimestamp, - "cancelled": cancelled, - "escrow_finished": escrow_finished, - "transfer_approved": transfer_approved, - "status": status, - "issuer_cancelable": issuer_cancelable - }) - - return json_response({ - "result_set": { - "count": count, - "offset": offset, - "limit": limit, - "total": total - }, - "transfer_approval_history": transfer_approval_history - }) + transfer_approval_history.append( + { + "id": _transfer_approval.id, + "token_address": token_address, + "exchange_address": _transfer_approval.exchange_address, + "application_id": _transfer_approval.application_id, + "from_address": _transfer_approval.from_address, + "to_address": _transfer_approval.to_address, + "amount": _transfer_approval.amount, + "application_datetime": application_datetime, + "application_blocktimestamp": application_blocktimestamp, + "approval_datetime": approval_datetime, + "approval_blocktimestamp": approval_blocktimestamp, + "cancelled": cancelled, + "escrow_finished": escrow_finished, + "transfer_approved": transfer_approved, + "status": status, + "issuer_cancelable": issuer_cancelable, + } + ) + + return json_response( + { + "result_set": { + "count": count, + "offset": offset, + "limit": limit, + "total": total, + }, + "transfer_approval_history": transfer_approval_history, + } + ) # POST: /bond/transfer_approvals/{token_address}/{id} @router.post( "/transfer_approvals/{token_address}/{id}", - responses=get_routers_responses(422, 401, 404, AuthorizationError, InvalidParameterError, SendTransactionError, ContractRevertError) + responses=get_routers_responses( + 422, + 401, + 404, + AuthorizationError, + InvalidParameterError, + SendTransactionError, + ContractRevertError, + ), ) def update_transfer_approval( - request: Request, - token_address: str, - id: int, - data: UpdateTransferApprovalRequest, - issuer_address: str = Header(...), - eoa_password: Optional[str] = Header(None), - auth_token: Optional[str] = Header(None), - db: Session = Depends(db_session) + request: Request, + token_address: str, + id: int, + data: UpdateTransferApprovalRequest, + issuer_address: str = Header(...), + eoa_password: Optional[str] = Header(None), + auth_token: Optional[str] = Header(None), + db: Session = Depends(db_session), ): """Update on the status of a bond transfer approval""" # Validate Headers validate_headers( issuer_address=(issuer_address, address_is_valid_address), - eoa_password=(eoa_password, eoa_password_is_encrypted_value) + eoa_password=(eoa_password, eoa_password_is_encrypted_value), ) # Authentication @@ -2400,32 +2663,35 @@ def update_transfer_approval( db=db, issuer_address=issuer_address, eoa_password=eoa_password, - auth_token=auth_token + auth_token=auth_token, ) # Get private key keyfile_json = _account.keyfile private_key = decode_keyfile_json( - raw_keyfile_json=keyfile_json, - password=decrypt_password.encode("utf-8") + raw_keyfile_json=keyfile_json, password=decrypt_password.encode("utf-8") ) # Get token - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_STRAIGHT_BOND). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_STRAIGHT_BOND) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: raise InvalidParameterError("this token is temporarily unavailable") # Get transfer approval history - _transfer_approval: IDXTransferApproval | None = db.query(IDXTransferApproval). \ - filter(IDXTransferApproval.id == id). \ - filter(IDXTransferApproval.token_address == token_address). \ - first() + _transfer_approval: IDXTransferApproval | None = ( + db.query(IDXTransferApproval) + .filter(IDXTransferApproval.id == id) + .filter(IDXTransferApproval.token_address == token_address) + .first() + ) if _transfer_approval is None: raise HTTPException(status_code=404, detail="transfer approval not found") @@ -2433,20 +2699,33 @@ def update_transfer_approval( raise InvalidParameterError("already approved") if _transfer_approval.cancelled is True: raise InvalidParameterError("canceled application") - if _transfer_approval.exchange_address != config.ZERO_ADDRESS and \ - _transfer_approval.escrow_finished is not True: + if ( + _transfer_approval.exchange_address != config.ZERO_ADDRESS + and _transfer_approval.escrow_finished is not True + ): raise InvalidParameterError("escrow has not been finished yet") - if data.operation_type == UpdateTransferApprovalOperationType.CANCEL and \ - _transfer_approval.exchange_address != config.ZERO_ADDRESS: + if ( + data.operation_type == UpdateTransferApprovalOperationType.CANCEL + and _transfer_approval.exchange_address != config.ZERO_ADDRESS + ): # Cancellation is possible only against approval of the transfer of a token contract. raise InvalidParameterError("application that cannot be canceled") - transfer_approval_op: TransferApprovalHistory | None = db.query(TransferApprovalHistory). \ - filter(TransferApprovalHistory.token_address == _transfer_approval.token_address). \ - filter(TransferApprovalHistory.exchange_address == _transfer_approval.exchange_address). \ - filter(TransferApprovalHistory.application_id == _transfer_approval.application_id). \ - filter(TransferApprovalHistory.operation_type == data.operation_type). \ - first() + transfer_approval_op: TransferApprovalHistory | None = ( + db.query(TransferApprovalHistory) + .filter( + TransferApprovalHistory.token_address == _transfer_approval.token_address + ) + .filter( + TransferApprovalHistory.exchange_address + == _transfer_approval.exchange_address + ) + .filter( + TransferApprovalHistory.application_id == _transfer_approval.application_id + ) + .filter(TransferApprovalHistory.operation_type == data.operation_type) + .first() + ) if transfer_approval_op is not None: raise InvalidParameterError("duplicate operation") @@ -2461,10 +2740,12 @@ def update_transfer_approval( if _transfer_approval.exchange_address == config.ZERO_ADDRESS: _data = { "application_id": _transfer_approval.application_id, - "data": now + "data": now, } try: - _, tx_receipt = IbetStraightBondContract(token_address).approve_transfer( + _, tx_receipt = IbetStraightBondContract( + token_address + ).approve_transfer( data=ApproveTransferParams(**_data), tx_from=issuer_address, private_key=private_key, @@ -2486,10 +2767,7 @@ def update_transfer_approval( # If cancel transfer is successful, approve_transfer error is raised. raise else: - _data = { - "escrow_id": _transfer_approval.application_id, - "data": now - } + _data = {"escrow_id": _transfer_approval.application_id, "data": now} escrow = IbetSecurityTokenEscrow(_transfer_approval.exchange_address) try: _, tx_receipt = escrow.approve_transfer( @@ -2503,10 +2781,7 @@ def update_transfer_approval( except Exception: raise SendTransactionError else: # CANCEL - _data = { - "application_id": _transfer_approval.application_id, - "data": now - } + _data = {"application_id": _transfer_approval.application_id, "data": now} try: _, tx_receipt = IbetStraightBondContract(token_address).cancel_transfer( data=CancelTransferParams(**_data), @@ -2535,53 +2810,72 @@ def update_transfer_approval( @router.get( "/transfer_approvals/{token_address}/{id}", response_model=TransferApprovalTokenResponse, - responses=get_routers_responses(422, 404, InvalidParameterError) + responses=get_routers_responses(422, 404, InvalidParameterError), ) def retrieve_transfer_approval_history( - token_address: str, - id: int, - db: Session = Depends(db_session) + token_address: str, id: int, db: Session = Depends(db_session) ): """Retrieve bond token transfer approval history""" # Get token - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_STRAIGHT_BOND). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_STRAIGHT_BOND) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: raise InvalidParameterError("this token is temporarily unavailable") # Get transfer approval history - _transfer_approval: IDXTransferApproval | None = db.query(IDXTransferApproval). \ - filter(IDXTransferApproval.id == id). \ - filter(IDXTransferApproval.token_address == token_address). \ - first() + _transfer_approval: IDXTransferApproval | None = ( + db.query(IDXTransferApproval) + .filter(IDXTransferApproval.id == id) + .filter(IDXTransferApproval.token_address == token_address) + .first() + ) if _transfer_approval is None: raise HTTPException(status_code=404, detail="transfer approval not found") - _transfer_approval_op: TransferApprovalHistory | None = db.query(TransferApprovalHistory). \ - filter(TransferApprovalHistory.token_address == _transfer_approval.token_address). \ - filter(TransferApprovalHistory.exchange_address == _transfer_approval.exchange_address). \ - filter(TransferApprovalHistory.application_id == _transfer_approval.application_id). \ - first() + _transfer_approval_op: TransferApprovalHistory | None = ( + db.query(TransferApprovalHistory) + .filter( + TransferApprovalHistory.token_address == _transfer_approval.token_address + ) + .filter( + TransferApprovalHistory.exchange_address + == _transfer_approval.exchange_address + ) + .filter( + TransferApprovalHistory.application_id == _transfer_approval.application_id + ) + .first() + ) status = 0 - if _transfer_approval.escrow_finished is True and \ - _transfer_approval.transfer_approved is not True and \ - _transfer_approval_op is None: + if ( + _transfer_approval.escrow_finished is True + and _transfer_approval.transfer_approved is not True + and _transfer_approval_op is None + ): status = 1 # EscrowFinish(escrow_finished) - elif _transfer_approval.transfer_approved is not True and \ - _transfer_approval_op is not None and \ - _transfer_approval_op.operation_type == TransferApprovalOperationType.APPROVE.value: + elif ( + _transfer_approval.transfer_approved is not True + and _transfer_approval_op is not None + and _transfer_approval_op.operation_type + == TransferApprovalOperationType.APPROVE.value + ): status = 2 # Approve(operation completed, event synchronizing) elif _transfer_approval.transfer_approved is True: status = 2 # Approve(transferred) - elif _transfer_approval.cancelled is not True and \ - _transfer_approval_op is not None and \ - _transfer_approval_op.operation_type == TransferApprovalOperationType.CANCEL.value: + elif ( + _transfer_approval.cancelled is not True + and _transfer_approval_op is not None + and _transfer_approval_op.operation_type + == TransferApprovalOperationType.CANCEL.value + ): status = 3 # Cancel(operation completed, event synchronizing) elif _transfer_approval.cancelled is True: status = 3 # Cancel(canceled) @@ -2606,21 +2900,33 @@ def retrieve_transfer_approval_history( else: issuer_cancelable = True - application_datetime_utc = timezone("UTC").localize(_transfer_approval.application_datetime) + application_datetime_utc = timezone("UTC").localize( + _transfer_approval.application_datetime + ) application_datetime = application_datetime_utc.astimezone(local_tz).isoformat() - application_blocktimestamp_utc = timezone("UTC").localize(_transfer_approval.application_blocktimestamp) - application_blocktimestamp = application_blocktimestamp_utc.astimezone(local_tz).isoformat() + application_blocktimestamp_utc = timezone("UTC").localize( + _transfer_approval.application_blocktimestamp + ) + application_blocktimestamp = application_blocktimestamp_utc.astimezone( + local_tz + ).isoformat() if _transfer_approval.approval_datetime is not None: - approval_datetime_utc = timezone("UTC").localize(_transfer_approval.approval_datetime) + approval_datetime_utc = timezone("UTC").localize( + _transfer_approval.approval_datetime + ) approval_datetime = approval_datetime_utc.astimezone(local_tz).isoformat() else: approval_datetime = None if _transfer_approval.approval_blocktimestamp is not None: - approval_blocktimestamp_utc = timezone("UTC").localize(_transfer_approval.approval_blocktimestamp) - approval_blocktimestamp = approval_blocktimestamp_utc.astimezone(local_tz).isoformat() + approval_blocktimestamp_utc = timezone("UTC").localize( + _transfer_approval.approval_blocktimestamp + ) + approval_blocktimestamp = approval_blocktimestamp_utc.astimezone( + local_tz + ).isoformat() else: approval_blocktimestamp = None @@ -2640,7 +2946,7 @@ def retrieve_transfer_approval_history( "escrow_finished": escrow_finished, "transfer_approved": transfer_approved, "status": status, - "issuer_cancelable": issuer_cancelable + "issuer_cancelable": issuer_cancelable, } return json_response(history) @@ -2650,21 +2956,24 @@ def retrieve_transfer_approval_history( @router.post( "/bulk_transfer", response_model=BulkTransferUploadIdResponse, - responses=get_routers_responses(422, AuthorizationError, InvalidParameterError, 401) + responses=get_routers_responses( + 422, AuthorizationError, InvalidParameterError, 401 + ), ) def bulk_transfer_ownership( - request: Request, - tokens: List[IbetStraightBondTransfer], - issuer_address: str = Header(...), - eoa_password: Optional[str] = Header(None), - auth_token: Optional[str] = Header(None), - db: Session = Depends(db_session)): + request: Request, + tokens: List[IbetStraightBondTransfer], + issuer_address: str = Header(...), + eoa_password: Optional[str] = Header(None), + auth_token: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Bulk transfer token ownership""" # Validate Headers validate_headers( issuer_address=(issuer_address, address_is_valid_address), - eoa_password=(eoa_password, eoa_password_is_encrypted_value) + eoa_password=(eoa_password, eoa_password_is_encrypted_value), ) if len(tokens) < 1: @@ -2676,21 +2985,25 @@ def bulk_transfer_ownership( db=db, issuer_address=issuer_address, eoa_password=eoa_password, - auth_token=auth_token + auth_token=auth_token, ) # Verify that the tokens are issued by the issuer_address for _token in tokens: - _issued_token = db.query(Token). \ - filter(Token.type == TokenType.IBET_STRAIGHT_BOND). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_address == _token.token_address). \ - filter(Token.token_status != 2). \ - first() + _issued_token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_STRAIGHT_BOND) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_address == _token.token_address) + .filter(Token.token_status != 2) + .first() + ) if _issued_token is None: raise InvalidParameterError(f"token not found: {_token.token_address}") if _issued_token.token_status == 0: - raise InvalidParameterError(f"this token is temporarily unavailable: {_token.token_address}") + raise InvalidParameterError( + f"this token is temporarily unavailable: {_token.token_address}" + ) # generate upload_id upload_id = uuid.uuid4() @@ -2718,20 +3031,18 @@ def bulk_transfer_ownership( db.commit() - return json_response({ - "upload_id": str(upload_id) - }) + return json_response({"upload_id": str(upload_id)}) # GET: /bond/bulk_transfer @router.get( "/bulk_transfer", response_model=List[BulkTransferUploadResponse], - responses=get_routers_responses(422) + responses=get_routers_responses(422), ) def list_bulk_transfer_upload( - issuer_address: Optional[str] = Header(None), - db: Session = Depends(db_session)): + issuer_address: Optional[str] = Header(None), db: Session = Depends(db_session) +): """List bulk transfer uploads""" # Validate Headers @@ -2739,26 +3050,32 @@ def list_bulk_transfer_upload( # Get bulk transfer upload list if issuer_address is None: - _uploads = db.query(BulkTransferUpload). \ - filter(BulkTransferUpload.token_type == TokenType.IBET_STRAIGHT_BOND). \ - order_by(BulkTransferUpload.issuer_address). \ - all() + _uploads = ( + db.query(BulkTransferUpload) + .filter(BulkTransferUpload.token_type == TokenType.IBET_STRAIGHT_BOND) + .order_by(BulkTransferUpload.issuer_address) + .all() + ) else: - _uploads = db.query(BulkTransferUpload). \ - filter(BulkTransferUpload.issuer_address == issuer_address). \ - filter(BulkTransferUpload.token_type == TokenType.IBET_STRAIGHT_BOND). \ - all() + _uploads = ( + db.query(BulkTransferUpload) + .filter(BulkTransferUpload.issuer_address == issuer_address) + .filter(BulkTransferUpload.token_type == TokenType.IBET_STRAIGHT_BOND) + .all() + ) uploads = [] for _upload in _uploads: created_utc = timezone("UTC").localize(_upload.created) - uploads.append({ - "issuer_address": _upload.issuer_address, - "token_type": _upload.token_type, - "upload_id": _upload.upload_id, - "status": _upload.status, - "created": created_utc.astimezone(local_tz).isoformat() - }) + uploads.append( + { + "issuer_address": _upload.issuer_address, + "token_type": _upload.token_type, + "upload_id": _upload.upload_id, + "status": _upload.status, + "created": created_utc.astimezone(local_tz).isoformat(), + } + ) return json_response(uploads) @@ -2767,12 +3084,13 @@ def list_bulk_transfer_upload( @router.get( "/bulk_transfer/{upload_id}", response_model=List[BulkTransferResponse], - responses=get_routers_responses(422, 404) + responses=get_routers_responses(422, 404), ) def retrieve_bulk_transfer( - upload_id: str, - issuer_address: Optional[str] = Header(None), - db: Session = Depends(db_session)): + upload_id: str, + issuer_address: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Retrieve a bulk transfer upload""" # Validate Headers @@ -2780,30 +3098,36 @@ def retrieve_bulk_transfer( # Get bulk transfer upload list if issuer_address is None: - _bulk_transfers = db.query(BulkTransfer). \ - filter(BulkTransfer.upload_id == upload_id). \ - filter(BulkTransfer.token_type == TokenType.IBET_STRAIGHT_BOND). \ - order_by(BulkTransfer.issuer_address). \ - all() + _bulk_transfers = ( + db.query(BulkTransfer) + .filter(BulkTransfer.upload_id == upload_id) + .filter(BulkTransfer.token_type == TokenType.IBET_STRAIGHT_BOND) + .order_by(BulkTransfer.issuer_address) + .all() + ) else: - _bulk_transfers = db.query(BulkTransfer). \ - filter(BulkTransfer.issuer_address == issuer_address). \ - filter(BulkTransfer.upload_id == upload_id). \ - filter(BulkTransfer.token_type == TokenType.IBET_STRAIGHT_BOND). \ - all() + _bulk_transfers = ( + db.query(BulkTransfer) + .filter(BulkTransfer.issuer_address == issuer_address) + .filter(BulkTransfer.upload_id == upload_id) + .filter(BulkTransfer.token_type == TokenType.IBET_STRAIGHT_BOND) + .all() + ) bulk_transfers = [] for _bulk_transfer in _bulk_transfers: - bulk_transfers.append({ - "issuer_address": _bulk_transfer.issuer_address, - "token_type": _bulk_transfer.token_type, - "upload_id": _bulk_transfer.upload_id, - "token_address": _bulk_transfer.token_address, - "from_address": _bulk_transfer.from_address, - "to_address": _bulk_transfer.to_address, - "amount": _bulk_transfer.amount, - "status": _bulk_transfer.status - }) + bulk_transfers.append( + { + "issuer_address": _bulk_transfer.issuer_address, + "token_type": _bulk_transfer.token_type, + "upload_id": _bulk_transfer.upload_id, + "token_address": _bulk_transfer.token_address, + "from_address": _bulk_transfer.from_address, + "to_address": _bulk_transfer.to_address, + "amount": _bulk_transfer.amount, + "status": _bulk_transfer.status, + } + ) if len(bulk_transfers) < 1: raise HTTPException(status_code=404, detail="bulk transfer not found") diff --git a/app/routers/common.py b/app/routers/common.py index 47f4f7ac..d0965728 100644 --- a/app/routers/common.py +++ b/app/routers/common.py @@ -11,25 +11,19 @@ limitations under the License. SPDX-License-Identifier: Apache-2.0 """ -from fastapi import ( - APIRouter, - Depends -) +from fastapi import APIRouter, Depends from sqlalchemy.orm import Session -from config import E2EE_REQUEST_ENABLED +from app import log from app.database import db_session +from app.exceptions import ServiceUnavailableError from app.model.db import Node -from app.utils.fastapi import json_response -from app.utils.e2ee_utils import E2EEUtils +from app.model.schema import BlockNumberResponse, E2EEResponse from app.utils.docs_utils import get_routers_responses +from app.utils.e2ee_utils import E2EEUtils +from app.utils.fastapi import json_response from app.utils.web3_utils import Web3Wrapper -from app.model.schema import ( - E2EEResponse, - BlockNumberResponse -) -from app.exceptions import ServiceUnavailableError -from app import log +from config import E2EE_REQUEST_ENABLED web3 = Web3Wrapper() @@ -39,10 +33,7 @@ # GET: /e2ee -@router.get( - "/e2ee", - response_model=E2EEResponse -) +@router.get("/e2ee", response_model=E2EEResponse) def e2e_encryption_key(): """Get E2EE public key""" @@ -51,20 +42,16 @@ def e2e_encryption_key(): _, public_key = E2EEUtils.get_key() - return json_response({ - "public_key": public_key - }) + return json_response({"public_key": public_key}) # GET: /healthcheck @router.get( "/healthcheck", response_model=None, - responses=get_routers_responses(ServiceUnavailableError) + responses=get_routers_responses(ServiceUnavailableError), ) -def check_health( - db: Session = Depends(db_session) -): +def check_health(db: Session = Depends(db_session)): errors = [] # Check DB Connection @@ -103,12 +90,10 @@ def __check_ethereum(errors: list, db: Session): @router.get( "/block_number", response_model=BlockNumberResponse, - responses=get_routers_responses(ServiceUnavailableError) + responses=get_routers_responses(ServiceUnavailableError), ) def get_block_number(): """Get Block Number in current""" block_number = web3.eth.block_number - return json_response({ - "block_number": block_number - }) + return json_response({"block_number": block_number}) diff --git a/app/routers/e2e_messaging.py b/app/routers/e2e_messaging.py index 7828aea4..605a71f1 100644 --- a/app/routers/e2e_messaging.py +++ b/app/routers/e2e_messaging.py @@ -17,81 +17,64 @@ SPDX-License-Identifier: Apache-2.0 """ import json -import secrets import re -from typing import ( - List, - Optional -) +import secrets from datetime import datetime -import pytz +from typing import List, Optional -from fastapi import ( - APIRouter, - Depends, - Query, - Path -) -from fastapi.exceptions import HTTPException -from sqlalchemy import ( - desc, - asc -) -from sqlalchemy.orm import ( - Session, - aliased -) -from sqlalchemy.sql import func +import boto3 +import eth_keyfile +import pytz from coincurve import PublicKey from Crypto import Random from Crypto.PublicKey import RSA -from eth_utils import to_checksum_address, keccak -import eth_keyfile -import boto3 +from eth_utils import keccak, to_checksum_address +from fastapi import APIRouter, Depends, Path, Query +from fastapi.exceptions import HTTPException +from sqlalchemy import asc, desc +from sqlalchemy.orm import Session, aliased +from sqlalchemy.sql import func -from config import ( - TZ, - EOA_PASSWORD_PATTERN, - EOA_PASSWORD_PATTERN_MSG, - E2E_MESSAGING_CONTRACT_ADDRESS, - E2E_MESSAGING_RSA_PASSPHRASE_PATTERN, - E2E_MESSAGING_RSA_PASSPHRASE_PATTERN_MSG, - E2E_MESSAGING_RSA_DEFAULT_PASSPHRASE, - E2EE_REQUEST_ENABLED, - AWS_REGION_NAME, - AWS_KMS_GENERATE_RANDOM_ENABLED -) from app.database import db_session +from app.exceptions import ( + ContractRevertError, + InvalidParameterError, + SendTransactionError, +) +from app.model.blockchain import E2EMessaging +from app.model.db import ( + E2EMessagingAccount, + E2EMessagingAccountRsaKey, + IDXE2EMessaging, + TransactionLock, +) from app.model.schema import ( - E2EMessagingAccountCreateRequest, - E2EMessagingAccountUpdateRsaKeyRequest, E2EMessagingAccountChangeEOAPasswordRequest, E2EMessagingAccountChangeRSAPassphraseRequest, + E2EMessagingAccountCreateRequest, E2EMessagingAccountResponse, + E2EMessagingAccountUpdateRsaKeyRequest, E2EMessagingResponse, - ListAllE2EMessagingResponse + ListAllE2EMessagingResponse, ) -from app.utils.fastapi import json_response from app.utils.contract_utils import ContractUtils -from app.utils.e2ee_utils import E2EEUtils from app.utils.docs_utils import get_routers_responses -from app.model.db import ( - E2EMessagingAccount, - E2EMessagingAccountRsaKey, - IDXE2EMessaging, - TransactionLock -) -from app.model.blockchain import E2EMessaging -from app.exceptions import ( - InvalidParameterError, - SendTransactionError, - ContractRevertError +from app.utils.e2ee_utils import E2EEUtils +from app.utils.fastapi import json_response +from config import ( + AWS_KMS_GENERATE_RANDOM_ENABLED, + AWS_REGION_NAME, + E2E_MESSAGING_CONTRACT_ADDRESS, + E2E_MESSAGING_RSA_DEFAULT_PASSPHRASE, + E2E_MESSAGING_RSA_PASSPHRASE_PATTERN, + E2E_MESSAGING_RSA_PASSPHRASE_PATTERN_MSG, + E2EE_REQUEST_ENABLED, + EOA_PASSWORD_PATTERN, + EOA_PASSWORD_PATTERN_MSG, + TZ, ) -router = APIRouter( - prefix="/e2e_messaging", - tags=["messaging"] -) +router = APIRouter(prefix="/e2e_messaging", tags=["messaging"]) local_tz = pytz.timezone(TZ) utc_tz = pytz.timezone("UTC") @@ -101,20 +84,30 @@ @router.post( "/accounts", response_model=E2EMessagingAccountResponse, - responses=get_routers_responses(422, InvalidParameterError, SendTransactionError, ContractRevertError) + responses=get_routers_responses( + 422, InvalidParameterError, SendTransactionError, ContractRevertError + ), ) def create_account( - data: E2EMessagingAccountCreateRequest, - db: Session = Depends(db_session)): + data: E2EMessagingAccountCreateRequest, db: Session = Depends(db_session) +): """Create Account""" # Check Password Policy(EOA password) - eoa_password = E2EEUtils.decrypt(data.eoa_password) if E2EE_REQUEST_ENABLED else data.eoa_password + eoa_password = ( + E2EEUtils.decrypt(data.eoa_password) + if E2EE_REQUEST_ENABLED + else data.eoa_password + ) if not re.match(EOA_PASSWORD_PATTERN, eoa_password): raise InvalidParameterError(EOA_PASSWORD_PATTERN_MSG) # Check Password Policy(RSA passphrase) if data.rsa_passphrase: - rsa_passphrase = E2EEUtils.decrypt(data.rsa_passphrase) if E2EE_REQUEST_ENABLED else data.rsa_passphrase + rsa_passphrase = ( + E2EEUtils.decrypt(data.rsa_passphrase) + if E2EE_REQUEST_ENABLED + else data.rsa_passphrase + ) if not re.match(E2E_MESSAGING_RSA_PASSPHRASE_PATTERN, rsa_passphrase): raise InvalidParameterError(E2E_MESSAGING_RSA_PASSPHRASE_PATTERN_MSG) else: @@ -130,9 +123,7 @@ def create_account( public_key = PublicKey.from_valid_secret(private_key).format(compressed=False)[1:] addr = to_checksum_address(keccak(public_key)[-20:]) keyfile_json = eth_keyfile.create_keyfile_json( - private_key=private_key, - password=eoa_password.encode("utf-8"), - kdf="pbkdf2" + private_key=private_key, password=eoa_password.encode("utf-8"), kdf="pbkdf2" ) # Generate RSA Key @@ -147,7 +138,7 @@ def create_account( public_key=rsa_public_key, key_type="RSA4096", tx_from=addr, - private_key=private_key + private_key=private_key, ) except SendTransactionError: raise SendTransactionError("failed to send transaction") @@ -180,20 +171,19 @@ def create_account( db.commit() - return json_response({ - "account_address": _account.account_address, - "rsa_key_generate_interval": _account.rsa_key_generate_interval, - "rsa_generation": _account.rsa_generation, - "rsa_public_key": rsa_public_key, - "is_deleted": _account.is_deleted - }) + return json_response( + { + "account_address": _account.account_address, + "rsa_key_generate_interval": _account.rsa_key_generate_interval, + "rsa_generation": _account.rsa_generation, + "rsa_public_key": rsa_public_key, + "is_deleted": _account.is_deleted, + } + ) # GET: /e2e_messaging/accounts -@router.get( - "/accounts", - response_model=List[E2EMessagingAccountResponse] -) +@router.get("/accounts", response_model=List[E2EMessagingAccountResponse]) def list_all_accounts(db: Session = Depends(db_session)): """List all e2e messaging accounts""" @@ -205,28 +195,44 @@ def list_all_accounts(db: Session = Depends(db_session)): # WHERE t2.account_address = t1.account_address # ) rsa_key_aliased = aliased(E2EMessagingAccountRsaKey) - subquery_max = db.query(func.max(rsa_key_aliased.block_timestamp)).\ - filter(rsa_key_aliased.account_address == E2EMessagingAccountRsaKey.account_address).\ - scalar_subquery() - subquery = db.query(E2EMessagingAccountRsaKey). \ - filter(E2EMessagingAccountRsaKey.block_timestamp == subquery_max) - latest_rsa_key = aliased(E2EMessagingAccountRsaKey, subquery.subquery("latest_rsa_key"), adapt_on_names=True) + subquery_max = ( + db.query(func.max(rsa_key_aliased.block_timestamp)) + .filter( + rsa_key_aliased.account_address == E2EMessagingAccountRsaKey.account_address + ) + .scalar_subquery() + ) + subquery = db.query(E2EMessagingAccountRsaKey).filter( + E2EMessagingAccountRsaKey.block_timestamp == subquery_max + ) + latest_rsa_key = aliased( + E2EMessagingAccountRsaKey, + subquery.subquery("latest_rsa_key"), + adapt_on_names=True, + ) # Get E2E Messaging Accounts - _accounts = db.query(E2EMessagingAccount, latest_rsa_key.rsa_public_key). \ - outerjoin(latest_rsa_key, E2EMessagingAccount.account_address == latest_rsa_key.account_address). \ - order_by(E2EMessagingAccount.account_address). \ - all() + _accounts = ( + db.query(E2EMessagingAccount, latest_rsa_key.rsa_public_key) + .outerjoin( + latest_rsa_key, + E2EMessagingAccount.account_address == latest_rsa_key.account_address, + ) + .order_by(E2EMessagingAccount.account_address) + .all() + ) account_list = [] for _account, rsa_public_key in _accounts: - account_list.append({ - "account_address": _account.account_address, - "rsa_key_generate_interval": _account.rsa_key_generate_interval, - "rsa_generation": _account.rsa_generation, - "rsa_public_key": rsa_public_key, - "is_deleted": _account.is_deleted - }) + account_list.append( + { + "account_address": _account.account_address, + "rsa_key_generate_interval": _account.rsa_key_generate_interval, + "rsa_generation": _account.rsa_generation, + "rsa_public_key": rsa_public_key, + "is_deleted": _account.is_deleted, + } + ) return json_response(account_list) @@ -235,91 +241,112 @@ def list_all_accounts(db: Session = Depends(db_session)): @router.get( "/accounts/{account_address}", response_model=E2EMessagingAccountResponse, - responses=get_routers_responses(404) + responses=get_routers_responses(404), ) def retrieve_account(account_address: str, db: Session = Depends(db_session)): """Retrieve an e2e messaging account""" - _account = db.query(E2EMessagingAccount). \ - filter(E2EMessagingAccount.account_address == account_address). \ - first() + _account = ( + db.query(E2EMessagingAccount) + .filter(E2EMessagingAccount.account_address == account_address) + .first() + ) if _account is None: - raise HTTPException(status_code=404, detail="e2e messaging account is not exists") + raise HTTPException( + status_code=404, detail="e2e messaging account is not exists" + ) rsa_public_key = None if _account.is_deleted is False: - _rsa_key = db.query(E2EMessagingAccountRsaKey). \ - filter(E2EMessagingAccountRsaKey.account_address == account_address). \ - order_by(desc(E2EMessagingAccountRsaKey.block_timestamp)). \ - first() + _rsa_key = ( + db.query(E2EMessagingAccountRsaKey) + .filter(E2EMessagingAccountRsaKey.account_address == account_address) + .order_by(desc(E2EMessagingAccountRsaKey.block_timestamp)) + .first() + ) rsa_public_key = _rsa_key.rsa_public_key - return json_response({ - "account_address": _account.account_address, - "rsa_key_generate_interval": _account.rsa_key_generate_interval, - "rsa_generation": _account.rsa_generation, - "rsa_public_key": rsa_public_key, - "is_deleted": _account.is_deleted - }) + return json_response( + { + "account_address": _account.account_address, + "rsa_key_generate_interval": _account.rsa_key_generate_interval, + "rsa_generation": _account.rsa_generation, + "rsa_public_key": rsa_public_key, + "is_deleted": _account.is_deleted, + } + ) # DELETE: /e2e_messaging/accounts/{account_address} @router.delete( "/accounts/{account_address}", response_model=E2EMessagingAccountResponse, - responses=get_routers_responses(404) + responses=get_routers_responses(404), ) def delete_account(account_address: str, db: Session = Depends(db_session)): """Logically delete an e2e messaging account""" - _account = db.query(E2EMessagingAccount). \ - filter(E2EMessagingAccount.account_address == account_address). \ - first() + _account = ( + db.query(E2EMessagingAccount) + .filter(E2EMessagingAccount.account_address == account_address) + .first() + ) if _account is None: - raise HTTPException(status_code=404, detail="e2e messaging account is not exists") + raise HTTPException( + status_code=404, detail="e2e messaging account is not exists" + ) _account.is_deleted = True db.merge(_account) # NOTE: RSA key is physically delete - db.query(E2EMessagingAccountRsaKey). \ - filter(E2EMessagingAccountRsaKey.account_address == account_address). \ - delete() + db.query(E2EMessagingAccountRsaKey).filter( + E2EMessagingAccountRsaKey.account_address == account_address + ).delete() db.commit() - return json_response({ - "account_address": _account.account_address, - "rsa_key_generate_interval": _account.rsa_key_generate_interval, - "rsa_generation": _account.rsa_generation, - "rsa_public_key": None, - "is_deleted": _account.is_deleted - }) + return json_response( + { + "account_address": _account.account_address, + "rsa_key_generate_interval": _account.rsa_key_generate_interval, + "rsa_generation": _account.rsa_generation, + "rsa_public_key": None, + "is_deleted": _account.is_deleted, + } + ) # POST: /e2e_messaging/accounts/{account_address}/rsa_key @router.post( "/accounts/{account_address}/rsa_key", response_model=E2EMessagingAccountResponse, - responses=get_routers_responses(422, 404) + responses=get_routers_responses(422, 404), ) def update_account_rsa_key( - account_address: str, - data: E2EMessagingAccountUpdateRsaKeyRequest, - db: Session = Depends(db_session)): + account_address: str, + data: E2EMessagingAccountUpdateRsaKeyRequest, + db: Session = Depends(db_session), +): """Update an e2e messaging account rsa key""" - _account = db.query(E2EMessagingAccount). \ - filter(E2EMessagingAccount.account_address == account_address). \ - filter(E2EMessagingAccount.is_deleted == False). \ - first() + _account = ( + db.query(E2EMessagingAccount) + .filter(E2EMessagingAccount.account_address == account_address) + .filter(E2EMessagingAccount.is_deleted == False) + .first() + ) if _account is None: - raise HTTPException(status_code=404, detail="e2e messaging account is not exists") + raise HTTPException( + status_code=404, detail="e2e messaging account is not exists" + ) - _rsa_key = db.query(E2EMessagingAccountRsaKey). \ - filter(E2EMessagingAccountRsaKey.account_address == account_address). \ - order_by(desc(E2EMessagingAccountRsaKey.block_timestamp)). \ - first() + _rsa_key = ( + db.query(E2EMessagingAccountRsaKey) + .filter(E2EMessagingAccountRsaKey.account_address == account_address) + .order_by(desc(E2EMessagingAccountRsaKey.block_timestamp)) + .first() + ) _account.rsa_key_generate_interval = data.rsa_key_generate_interval _account.rsa_generation = data.rsa_generation @@ -327,40 +354,56 @@ def update_account_rsa_key( db.commit() - return json_response({ - "account_address": _account.account_address, - "rsa_key_generate_interval": _account.rsa_key_generate_interval, - "rsa_generation": _account.rsa_generation, - "rsa_public_key": _rsa_key.rsa_public_key, - "is_deleted": _account.is_deleted - }) + return json_response( + { + "account_address": _account.account_address, + "rsa_key_generate_interval": _account.rsa_key_generate_interval, + "rsa_generation": _account.rsa_generation, + "rsa_public_key": _rsa_key.rsa_public_key, + "is_deleted": _account.is_deleted, + } + ) # POST: /e2e_messaging/accounts/{account_address}/eoa_password @router.post( "/accounts/{account_address}/eoa_password", response_model=None, - responses=get_routers_responses(422, 404, InvalidParameterError)) + responses=get_routers_responses(422, 404, InvalidParameterError), +) def change_eoa_password( - account_address: str, - data: E2EMessagingAccountChangeEOAPasswordRequest, - db: Session = Depends(db_session)): + account_address: str, + data: E2EMessagingAccountChangeEOAPasswordRequest, + db: Session = Depends(db_session), +): """Change Account's EOA Password""" # Get E2E Messaging Account - _account = db.query(E2EMessagingAccount). \ - filter(E2EMessagingAccount.account_address == account_address). \ - first() + _account = ( + db.query(E2EMessagingAccount) + .filter(E2EMessagingAccount.account_address == account_address) + .first() + ) if _account is None: - raise HTTPException(status_code=404, detail="e2e messaging account is not exists") + raise HTTPException( + status_code=404, detail="e2e messaging account is not exists" + ) # Check Password Policy - eoa_password = E2EEUtils.decrypt(data.eoa_password) if E2EE_REQUEST_ENABLED else data.eoa_password + eoa_password = ( + E2EEUtils.decrypt(data.eoa_password) + if E2EE_REQUEST_ENABLED + else data.eoa_password + ) if not re.match(EOA_PASSWORD_PATTERN, eoa_password): raise InvalidParameterError(EOA_PASSWORD_PATTERN_MSG) # Check Old Password - old_eoa_password = E2EEUtils.decrypt(data.old_eoa_password) if E2EE_REQUEST_ENABLED else data.old_eoa_password + old_eoa_password = ( + E2EEUtils.decrypt(data.old_eoa_password) + if E2EE_REQUEST_ENABLED + else data.old_eoa_password + ) correct_eoa_password = E2EEUtils.decrypt(_account.eoa_password) if old_eoa_password != correct_eoa_password: raise InvalidParameterError("old password mismatch") @@ -368,15 +411,12 @@ def change_eoa_password( # Get Ethereum Key old_keyfile_json = _account.keyfile private_key = eth_keyfile.decode_keyfile_json( - raw_keyfile_json=old_keyfile_json, - password=old_eoa_password.encode("utf-8") + raw_keyfile_json=old_keyfile_json, password=old_eoa_password.encode("utf-8") ) # Create New Ethereum Key File keyfile_json = eth_keyfile.create_keyfile_json( - private_key=private_key, - password=eoa_password.encode("utf-8"), - kdf="pbkdf2" + private_key=private_key, password=eoa_password.encode("utf-8"), kdf="pbkdf2" ) # Update data to the DB @@ -393,43 +433,63 @@ def change_eoa_password( @router.post( "/accounts/{account_address}/rsa_passphrase", response_model=None, - responses=get_routers_responses(422, 404, InvalidParameterError)) + responses=get_routers_responses(422, 404, InvalidParameterError), +) def change_rsa_passphrase( - account_address: str, - data: E2EMessagingAccountChangeRSAPassphraseRequest, - db: Session = Depends(db_session)): + account_address: str, + data: E2EMessagingAccountChangeRSAPassphraseRequest, + db: Session = Depends(db_session), +): """Change Account's RSA Passphrase""" # Get E2E Messaging Account - _account = db.query(E2EMessagingAccount). \ - filter(E2EMessagingAccount.account_address == account_address). \ - first() + _account = ( + db.query(E2EMessagingAccount) + .filter(E2EMessagingAccount.account_address == account_address) + .first() + ) if _account is None: - raise HTTPException(status_code=404, detail="e2e messaging account is not exists") + raise HTTPException( + status_code=404, detail="e2e messaging account is not exists" + ) # Get latest RSA key - _rsa_key = db.query(E2EMessagingAccountRsaKey). \ - filter(E2EMessagingAccountRsaKey.account_address == account_address). \ - order_by(desc(E2EMessagingAccountRsaKey.block_timestamp)). \ - first() + _rsa_key = ( + db.query(E2EMessagingAccountRsaKey) + .filter(E2EMessagingAccountRsaKey.account_address == account_address) + .order_by(desc(E2EMessagingAccountRsaKey.block_timestamp)) + .first() + ) if _rsa_key is None: - raise HTTPException(status_code=404, detail="e2e messaging rsa key is not exists") + raise HTTPException( + status_code=404, detail="e2e messaging rsa key is not exists" + ) # Check Old Passphrase - old_rsa_passphrase = E2EEUtils.decrypt(data.old_rsa_passphrase) if E2EE_REQUEST_ENABLED else data.old_rsa_passphrase + old_rsa_passphrase = ( + E2EEUtils.decrypt(data.old_rsa_passphrase) + if E2EE_REQUEST_ENABLED + else data.old_rsa_passphrase + ) correct_rsa_passphrase = E2EEUtils.decrypt(_rsa_key.rsa_passphrase) if old_rsa_passphrase != correct_rsa_passphrase: raise InvalidParameterError("old passphrase mismatch") # Check Password Policy - rsa_passphrase = E2EEUtils.decrypt(data.rsa_passphrase) if E2EE_REQUEST_ENABLED else data.rsa_passphrase + rsa_passphrase = ( + E2EEUtils.decrypt(data.rsa_passphrase) + if E2EE_REQUEST_ENABLED + else data.rsa_passphrase + ) if not re.match(E2E_MESSAGING_RSA_PASSPHRASE_PATTERN, rsa_passphrase): raise InvalidParameterError(E2E_MESSAGING_RSA_PASSPHRASE_PATTERN_MSG) # Update RSA Passphrase old_rsa_private_key = _rsa_key.rsa_private_key rsa_key = RSA.importKey(old_rsa_private_key, old_rsa_passphrase) - rsa_private_key = rsa_key.exportKey(format="PEM", passphrase=rsa_passphrase).decode() + rsa_private_key = rsa_key.exportKey( + format="PEM", passphrase=rsa_passphrase + ).decode() # Update data to the DB _rsa_key.rsa_private_key = rsa_private_key @@ -445,21 +505,21 @@ def change_rsa_passphrase( @router.get( "/messages", response_model=ListAllE2EMessagingResponse, - responses=get_routers_responses(422) + responses=get_routers_responses(422), ) def list_all_e2e_messages( - from_address: Optional[str] = Query(None), - to_address: Optional[str] = Query(None), - _type: Optional[str] = Query(None, alias="type"), - message: Optional[str] = Query(None, description="partial match"), - offset: Optional[int] = Query(None), - limit: Optional[int] = Query(None), - db: Session = Depends(db_session)): + from_address: Optional[str] = Query(None), + to_address: Optional[str] = Query(None), + _type: Optional[str] = Query(None, alias="type"), + message: Optional[str] = Query(None, description="partial match"), + offset: Optional[int] = Query(None), + limit: Optional[int] = Query(None), + db: Session = Depends(db_session), +): """List all e2e message""" # Get E2E Messaging - query = db.query(IDXE2EMessaging). \ - order_by(asc(IDXE2EMessaging.id)) + query = db.query(IDXE2EMessaging).order_by(asc(IDXE2EMessaging.id)) total = query.count() # Search Filter @@ -483,29 +543,35 @@ def list_all_e2e_messages( e2e_messages = [] for _e2e_messaging in _e2e_messaging_list: - send_timestamp_formatted = utc_tz.localize(_e2e_messaging.send_timestamp).astimezone(local_tz).isoformat() + send_timestamp_formatted = ( + utc_tz.localize(_e2e_messaging.send_timestamp) + .astimezone(local_tz) + .isoformat() + ) try: # json or list string decode message = json.loads(_e2e_messaging.message) except json.decoder.JSONDecodeError: message = _e2e_messaging.message - e2e_messages.append({ - "id": _e2e_messaging.id, - "from_address": _e2e_messaging.from_address, - "to_address": _e2e_messaging.to_address, - "type": _e2e_messaging.type, - "message": message, - "send_timestamp": send_timestamp_formatted, - }) + e2e_messages.append( + { + "id": _e2e_messaging.id, + "from_address": _e2e_messaging.from_address, + "to_address": _e2e_messaging.to_address, + "type": _e2e_messaging.type, + "message": message, + "send_timestamp": send_timestamp_formatted, + } + ) resp = { "result_set": { "count": count, "offset": offset, "limit": limit, - "total": total + "total": total, }, - "e2e_messages": e2e_messages + "e2e_messages": e2e_messages, } return json_response(resp) @@ -515,32 +581,35 @@ def list_all_e2e_messages( @router.get( "/messages/{id}", response_model=E2EMessagingResponse, - responses=get_routers_responses(422, 404) + responses=get_routers_responses(422, 404), ) def retrieve_e2e_messaging( - _id: int = Path(..., alias="id"), - db: Session = Depends(db_session)): + _id: int = Path(..., alias="id"), db: Session = Depends(db_session) +): """Retrieve an e2e message""" # Get E2E Messaging - query = db.query(IDXE2EMessaging). \ - filter(IDXE2EMessaging.id == _id) + query = db.query(IDXE2EMessaging).filter(IDXE2EMessaging.id == _id) _e2e_messaging = query.first() if _e2e_messaging is None: raise HTTPException(status_code=404, detail="e2e messaging not found") - send_timestamp_formatted = utc_tz.localize(_e2e_messaging.send_timestamp).astimezone(local_tz).isoformat() + send_timestamp_formatted = ( + utc_tz.localize(_e2e_messaging.send_timestamp).astimezone(local_tz).isoformat() + ) try: # json or list string decode message = json.loads(_e2e_messaging.message) except json.decoder.JSONDecodeError: message = _e2e_messaging.message - return json_response({ - "id": _e2e_messaging.id, - "from_address": _e2e_messaging.from_address, - "to_address": _e2e_messaging.to_address, - "type": _e2e_messaging.type, - "message": message, - "send_timestamp": send_timestamp_formatted, - }) + return json_response( + { + "id": _e2e_messaging.id, + "from_address": _e2e_messaging.from_address, + "to_address": _e2e_messaging.to_address, + "type": _e2e_messaging.type, + "message": message, + "send_timestamp": send_timestamp_formatted, + } + ) diff --git a/app/routers/file.py b/app/routers/file.py index e33beaa4..aa3a60b1 100644 --- a/app/routers/file.py +++ b/app/routers/file.py @@ -19,38 +19,27 @@ import base64 import uuid from typing import Optional -import pytz -from fastapi import ( - APIRouter, - Depends, - Header, - Query -) +import pytz +from fastapi import APIRouter, Depends, Header, Query from fastapi.exceptions import HTTPException from sqlalchemy import desc from sqlalchemy.orm import Session -from config import TZ from app.database import db_session from app.model.db import UploadFile from app.model.schema import ( - UploadFileRequest, + DownloadFileResponse, FileResponse, ListAllFilesResponse, - DownloadFileResponse -) -from app.utils.fastapi import json_response -from app.utils.check_utils import ( - validate_headers, - address_is_valid_address + UploadFileRequest, ) +from app.utils.check_utils import address_is_valid_address, validate_headers from app.utils.docs_utils import get_routers_responses +from app.utils.fastapi import json_response +from config import TZ -router = APIRouter( - prefix="/files", - tags=["utility"] -) +router = APIRouter(prefix="/files", tags=["utility"]) local_tz = pytz.timezone(TZ) utc_tz = pytz.timezone("UTC") @@ -58,18 +47,17 @@ # GET: /files @router.get( - "", - response_model=ListAllFilesResponse, - responses=get_routers_responses(422) + "", response_model=ListAllFilesResponse, responses=get_routers_responses(422) ) def list_all_upload_files( - issuer_address: Optional[str] = Header(None), - relation: Optional[str] = Query(None), - file_name: Optional[str] = Query(None, description="partial match"), - label: Optional[str] = Query(None, description="partial match"), - offset: Optional[int] = Query(None), - limit: Optional[int] = Query(None), - db: Session = Depends(db_session)): + issuer_address: Optional[str] = Header(None), + relation: Optional[str] = Query(None), + file_name: Optional[str] = Query(None, description="partial match"), + label: Optional[str] = Query(None, description="partial match"), + offset: Optional[int] = Query(None), + limit: Optional[int] = Query(None), + db: Session = Depends(db_session), +): """List all files""" # Validate Headers @@ -83,11 +71,10 @@ def list_all_upload_files( UploadFile.content_size, UploadFile.description, UploadFile.label, - UploadFile.created + UploadFile.created, ] - query = db.query(*rows). \ - order_by(desc(UploadFile.modified)) + query = db.query(*rows).order_by(desc(UploadFile.modified)) total = query.count() # Search Filter @@ -114,41 +101,42 @@ def list_all_upload_files( files = [] for _upload_file in _upload_file_list: - created_formatted = utc_tz.localize(_upload_file[7]).astimezone(local_tz).isoformat() - files.append({ - "file_id": _upload_file[0], - "issuer_address": _upload_file[1], - "relation": _upload_file[2], - "file_name": _upload_file[3], - "content_size": _upload_file[4], - "description": _upload_file[5], - "label": _upload_file[6], - "created": created_formatted, - }) + created_formatted = ( + utc_tz.localize(_upload_file[7]).astimezone(local_tz).isoformat() + ) + files.append( + { + "file_id": _upload_file[0], + "issuer_address": _upload_file[1], + "relation": _upload_file[2], + "file_name": _upload_file[3], + "content_size": _upload_file[4], + "description": _upload_file[5], + "label": _upload_file[6], + "created": created_formatted, + } + ) resp = { "result_set": { "count": count, "offset": offset, "limit": limit, - "total": total + "total": total, }, - "files": files + "files": files, } return json_response(resp) # POST: /files -@router.post( - "", - response_model=FileResponse, - responses=get_routers_responses(422) -) +@router.post("", response_model=FileResponse, responses=get_routers_responses(422)) def upload_file( - data: UploadFileRequest, - issuer_address: str = Header(...), - db: Session = Depends(db_session)): + data: UploadFileRequest, + issuer_address: str = Header(...), + db: Session = Depends(db_session), +): """Upload file""" # Validate Headers @@ -178,7 +166,9 @@ def upload_file( "content_size": _upload_file.content_size, "description": _upload_file.description, "label": _upload_file.label, - "created": utc_tz.localize(_upload_file.created).astimezone(local_tz).isoformat() + "created": utc_tz.localize(_upload_file.created) + .astimezone(local_tz) + .isoformat(), } return json_response(resp) @@ -188,12 +178,13 @@ def upload_file( @router.get( "/{file_id}", response_model=DownloadFileResponse, - responses=get_routers_responses(404) + responses=get_routers_responses(404), ) def download_file( - file_id: str, - issuer_address: Optional[str] = Header(None), - db: Session = Depends(db_session)): + file_id: str, + issuer_address: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Download file""" # Validate Headers @@ -201,14 +192,16 @@ def download_file( # Get Upload File if issuer_address is None: - _upload_file = db.query(UploadFile). \ - filter(UploadFile.file_id == file_id). \ - first() + _upload_file = ( + db.query(UploadFile).filter(UploadFile.file_id == file_id).first() + ) else: - _upload_file = db.query(UploadFile). \ - filter(UploadFile.file_id == file_id). \ - filter(UploadFile.issuer_address == issuer_address). \ - first() + _upload_file = ( + db.query(UploadFile) + .filter(UploadFile.file_id == file_id) + .filter(UploadFile.issuer_address == issuer_address) + .first() + ) if _upload_file is None: raise HTTPException(status_code=404, detail="file not found") @@ -231,24 +224,23 @@ def download_file( # DELETE: /files/{file_id} @router.delete( - "/{file_id}", - response_model=None, - responses=get_routers_responses(422, 404) + "/{file_id}", response_model=None, responses=get_routers_responses(422, 404) ) def delete_file( - file_id: str, - issuer_address: str = Header(...), - db: Session = Depends(db_session)): + file_id: str, issuer_address: str = Header(...), db: Session = Depends(db_session) +): """Delete file""" # Validate Headers validate_headers(issuer_address=(issuer_address, address_is_valid_address)) # Get Upload File - _upload_file = db.query(UploadFile). \ - filter(UploadFile.file_id == file_id). \ - filter(UploadFile.issuer_address == issuer_address). \ - first() + _upload_file = ( + db.query(UploadFile) + .filter(UploadFile.file_id == file_id) + .filter(UploadFile.issuer_address == issuer_address) + .first() + ) if _upload_file is None: raise HTTPException(status_code=404, detail="file not found") diff --git a/app/routers/ledger.py b/app/routers/ledger.py index 714c9312..dfce3917 100644 --- a/app/routers/ledger.py +++ b/app/routers/ledger.py @@ -17,60 +17,46 @@ SPDX-License-Identifier: Apache-2.0 """ import uuid -import pytz -from typing import ( - List, - Optional -) +from typing import List, Optional -from fastapi import ( - APIRouter, - Header, - Query, - Depends -) +import pytz +from fastapi import APIRouter, Depends, Header, Query from fastapi.exceptions import HTTPException -from sqlalchemy import ( - func, - desc -) +from sqlalchemy import desc, func from sqlalchemy.orm import Session -from config import TZ from app.database import db_session +from app.exceptions import InvalidParameterError from app.model.blockchain import ( IbetShareContract, IbetStraightBondContract, - PersonalInfoContract -) -from app.utils.fastapi import json_response -from app.utils.check_utils import ( - validate_headers, - address_is_valid_address + PersonalInfoContract, ) -from app.utils.ledger_utils import create_ledger -from app.utils.docs_utils import get_routers_responses from app.model.db import ( - Token, - TokenType, IDXPersonalInfo, Ledger, LedgerDetailsData, - LedgerTemplate, + LedgerDetailsDataType, LedgerDetailsTemplate, - LedgerDetailsDataType + LedgerTemplate, + Token, + TokenType, ) from app.model.schema import ( - CreateUpdateLedgerTemplateRequest, CreateUpdateLedgerDetailsDataRequest, - ListAllLedgerHistoryResponse, - RetrieveLedgerHistoryResponse, + CreateUpdateLedgerTemplateRequest, + LedgerDetailsDataResponse, LedgerTemplateResponse, ListAllLedgerDetailsDataResponse, - LedgerDetailsDataResponse, - RetrieveLedgerDetailsDataResponse + ListAllLedgerHistoryResponse, + RetrieveLedgerDetailsDataResponse, + RetrieveLedgerHistoryResponse, ) -from app.exceptions import InvalidParameterError +from app.utils.check_utils import address_is_valid_address, validate_headers +from app.utils.docs_utils import get_routers_responses +from app.utils.fastapi import json_response +from app.utils.ledger_utils import create_ledger +from config import TZ router = APIRouter( prefix="/ledger", @@ -85,14 +71,15 @@ @router.get( "/{token_address}/history", response_model=ListAllLedgerHistoryResponse, - responses=get_routers_responses(422, 404, InvalidParameterError) + responses=get_routers_responses(422, 404, InvalidParameterError), ) def list_all_ledger_history( - token_address: str, - issuer_address: Optional[str] = Header(None), - offset: int = Query(None), - limit: int = Query(None), - db: Session = Depends(db_session)): + token_address: str, + issuer_address: Optional[str] = Header(None), + offset: int = Query(None), + limit: int = Query(None), + db: Session = Depends(db_session), +): """List all Ledger""" # Validate Headers @@ -100,24 +87,30 @@ def list_all_ledger_history( # Token Exist Check if issuer_address is None: - _token = db.query(Token). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) else: - _token = db.query(Token). \ - filter(Token.token_address == token_address). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.token_address == token_address) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token does not exist") if _token.token_status == 0: raise InvalidParameterError("this token is temporarily unavailable") - query = db.query(Ledger). \ - filter(Ledger.token_address == token_address). \ - order_by(desc(Ledger.id)) + query = ( + db.query(Ledger) + .filter(Ledger.token_address == token_address) + .order_by(desc(Ledger.id)) + ) total = query.count() # NOTE: Because it don`t filter, `total` and `count` will be the same. @@ -132,22 +125,26 @@ def list_all_ledger_history( ledgers = [] for _ledger in _ledger_list: - created_formatted = utc_tz.localize(_ledger.ledger_created).astimezone(local_tz).isoformat() - ledgers.append({ - "id": _ledger.id, - "token_address": _ledger.token_address, - "token_type": _ledger.token_type, - "created": created_formatted, - }) + created_formatted = ( + utc_tz.localize(_ledger.ledger_created).astimezone(local_tz).isoformat() + ) + ledgers.append( + { + "id": _ledger.id, + "token_address": _ledger.token_address, + "token_type": _ledger.token_type, + "created": created_formatted, + } + ) resp = { "result_set": { "count": count, "offset": offset, "limit": limit, - "total": total + "total": total, }, - "ledgers": ledgers + "ledgers": ledgers, } return json_response(resp) @@ -157,14 +154,15 @@ def list_all_ledger_history( @router.get( "/{token_address}/history/{ledger_id}", response_model=RetrieveLedgerHistoryResponse, - responses=get_routers_responses(422, 404, InvalidParameterError) + responses=get_routers_responses(422, 404, InvalidParameterError), ) def retrieve_ledger_history( - token_address: str, - ledger_id: int, - issuer_address: Optional[str] = Header(None), - latest_flg: int = Query(..., ge=0, le=1), - db: Session = Depends(db_session)): + token_address: str, + ledger_id: int, + issuer_address: Optional[str] = Header(None), + latest_flg: int = Query(..., ge=0, le=1), + db: Session = Depends(db_session), +): """Retrieve Ledger""" # Validate Headers @@ -172,26 +170,32 @@ def retrieve_ledger_history( # Token Exist Check if issuer_address is None: - _token = db.query(Token). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) else: - _token = db.query(Token). \ - filter(Token.token_address == token_address). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.token_address == token_address) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token does not exist") if _token.token_status == 0: raise InvalidParameterError("this token is temporarily unavailable") # Ledger Exist Check - _ledger = db.query(Ledger). \ - filter(Ledger.id == ledger_id). \ - filter(Ledger.token_address == token_address). \ - first() + _ledger = ( + db.query(Ledger) + .filter(Ledger.id == ledger_id) + .filter(Ledger.token_address == token_address) + .first() + ) if _ledger is None: raise HTTPException(status_code=404, detail="ledger does not exist") @@ -199,12 +203,16 @@ def retrieve_ledger_history( if latest_flg == 1: # Get the latest personal info # Get ibet fin token_detail_type - _ibet_fin_details_list = db.query(LedgerDetailsTemplate). \ - filter(LedgerDetailsTemplate.token_address == token_address). \ - filter(LedgerDetailsTemplate.data_type == LedgerDetailsDataType.IBET_FIN). \ - order_by(LedgerDetailsTemplate.id). \ - all() - _ibet_fin_token_detail_type_list = [_details.token_detail_type for _details in _ibet_fin_details_list] + _ibet_fin_details_list = ( + db.query(LedgerDetailsTemplate) + .filter(LedgerDetailsTemplate.token_address == token_address) + .filter(LedgerDetailsTemplate.data_type == LedgerDetailsDataType.IBET_FIN) + .order_by(LedgerDetailsTemplate.id) + .all() + ) + _ibet_fin_token_detail_type_list = [ + _details.token_detail_type for _details in _ibet_fin_details_list + ] # Update PersonalInfo for details in resp["details"]: if details["token_detail_type"] in _ibet_fin_token_detail_type_list: @@ -213,7 +221,7 @@ def retrieve_ledger_history( token_address=token_address, token_type=_token.type, account_address=data["account_address"], - db=db + db=db, ) if personal_info is not None: data["name"] = personal_info.get("name", None) @@ -226,12 +234,13 @@ def retrieve_ledger_history( @router.get( "/{token_address}/template", response_model=LedgerTemplateResponse, - responses=get_routers_responses(422, 404, InvalidParameterError) + responses=get_routers_responses(422, 404, InvalidParameterError), ) def retrieve_ledger_template( - token_address: str, - issuer_address: Optional[str] = Header(None), - db: Session = Depends(db_session)): + token_address: str, + issuer_address: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Retrieve Ledger Template""" # Validate Headers @@ -239,44 +248,54 @@ def retrieve_ledger_template( # Token Exist Check if issuer_address is None: - _token = db.query(Token). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) else: - _token = db.query(Token). \ - filter(Token.token_address == token_address). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.token_address == token_address) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token does not exist") if _token.token_status == 0: raise InvalidParameterError("this token is temporarily unavailable") # Ledger Template Exist Check - _template = db.query(LedgerTemplate). \ - filter(LedgerTemplate.token_address == token_address). \ - first() + _template = ( + db.query(LedgerTemplate) + .filter(LedgerTemplate.token_address == token_address) + .first() + ) if _template is None: raise HTTPException(status_code=404, detail="ledger template does not exist") # Get Ledger Details Template - _details_list = db.query(LedgerDetailsTemplate). \ - filter(LedgerDetailsTemplate.token_address == token_address). \ - order_by(LedgerDetailsTemplate.id). \ - all() + _details_list = ( + db.query(LedgerDetailsTemplate) + .filter(LedgerDetailsTemplate.token_address == token_address) + .order_by(LedgerDetailsTemplate.id) + .all() + ) details = [] for _details in _details_list: - details.append({ - "token_detail_type": _details.token_detail_type, - "headers": _details.headers, - "data": { - "type": _details.data_type, - "source": _details.data_source, - }, - "footers": _details.footers, - }) + details.append( + { + "token_detail_type": _details.token_detail_type, + "headers": _details.headers, + "data": { + "type": _details.data_type, + "source": _details.data_source, + }, + "footers": _details.footers, + } + ) resp = { "token_name": _template.token_name, @@ -292,33 +311,38 @@ def retrieve_ledger_template( @router.post( "/{token_address}/template", response_model=None, - responses=get_routers_responses(422, 404, InvalidParameterError) + responses=get_routers_responses(422, 404, InvalidParameterError), ) def create_update_ledger_template( - token_address: str, - data: CreateUpdateLedgerTemplateRequest, - issuer_address: str = Header(...), - db: Session = Depends(db_session)): + token_address: str, + data: CreateUpdateLedgerTemplateRequest, + issuer_address: str = Header(...), + db: Session = Depends(db_session), +): """Create or Update Ledger Template""" # Validate Headers validate_headers(issuer_address=(issuer_address, address_is_valid_address)) # Issuer Management Token Check - _token = db.query(Token). \ - filter(Token.token_address == token_address). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.token_address == token_address) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token does not exist") if _token.token_status == 0: raise InvalidParameterError("this token is temporarily unavailable") # Get Ledger Template - _template = db.query(LedgerTemplate). \ - filter(LedgerTemplate.token_address == token_address). \ - first() + _template = ( + db.query(LedgerTemplate) + .filter(LedgerTemplate.token_address == token_address) + .first() + ) if _template is None: # Create Template:Ledger @@ -337,17 +361,24 @@ def create_update_ledger_template( db.merge(_template) # NOTE: Data that is not subject to the updater will be deleted later - _details_list = db.query(LedgerDetailsTemplate). \ - filter(LedgerDetailsTemplate.token_address == token_address). \ - all() - delete_details_token_detail_type = [_details.token_detail_type for _details in _details_list] + _details_list = ( + db.query(LedgerDetailsTemplate) + .filter(LedgerDetailsTemplate.token_address == token_address) + .all() + ) + delete_details_token_detail_type = [ + _details.token_detail_type for _details in _details_list + ] for details in data.details: - - _details = db.query(LedgerDetailsTemplate). \ - filter(LedgerDetailsTemplate.token_address == token_address). \ - filter(LedgerDetailsTemplate.token_detail_type == details.token_detail_type). \ - first() + _details = ( + db.query(LedgerDetailsTemplate) + .filter(LedgerDetailsTemplate.token_address == token_address) + .filter( + LedgerDetailsTemplate.token_detail_type == details.token_detail_type + ) + .first() + ) if _details is None: # Create Ledger Details Template _details = LedgerDetailsTemplate() @@ -370,10 +401,12 @@ def create_update_ledger_template( # Delete Ledger Details Template for token_detail_type in delete_details_token_detail_type: - _details = db.query(LedgerDetailsTemplate). \ - filter(LedgerDetailsTemplate.token_address == token_address). \ - filter(LedgerDetailsTemplate.token_detail_type == token_detail_type). \ - first() + _details = ( + db.query(LedgerDetailsTemplate) + .filter(LedgerDetailsTemplate.token_address == token_address) + .filter(LedgerDetailsTemplate.token_detail_type == token_detail_type) + .first() + ) db.delete(_details) # Create Ledger @@ -387,40 +420,47 @@ def create_update_ledger_template( @router.delete( "/{token_address}/template", response_model=None, - responses=get_routers_responses(422, 404, InvalidParameterError) + responses=get_routers_responses(422, 404, InvalidParameterError), ) def delete_ledger_template( - token_address: str, - issuer_address: str = Header(...), - db: Session = Depends(db_session)): + token_address: str, + issuer_address: str = Header(...), + db: Session = Depends(db_session), +): """Delete Ledger Template""" # Validate Headers validate_headers(issuer_address=(issuer_address, address_is_valid_address)) # Issuer Management Token Check - _token = db.query(Token). \ - filter(Token.token_address == token_address). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.token_address == token_address) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token does not exist") if _token.token_status == 0: raise InvalidParameterError("this token is temporarily unavailable") # Delete Ledger Template - _template = db.query(LedgerTemplate). \ - filter(LedgerTemplate.token_address == token_address). \ - first() + _template = ( + db.query(LedgerTemplate) + .filter(LedgerTemplate.token_address == token_address) + .first() + ) if _template is None: raise HTTPException(status_code=404, detail="ledger template does not exist") db.delete(_template) # Delete Ledger Details Template - _details_list = db.query(LedgerDetailsTemplate). \ - filter(LedgerDetailsTemplate.token_address == token_address). \ - all() + _details_list = ( + db.query(LedgerDetailsTemplate) + .filter(LedgerDetailsTemplate.token_address == token_address) + .all() + ) for _details in _details_list: db.delete(_details) @@ -432,14 +472,15 @@ def delete_ledger_template( @router.get( "/{token_address}/details_data", response_model=ListAllLedgerDetailsDataResponse, - responses=get_routers_responses(422, 404, InvalidParameterError) + responses=get_routers_responses(422, 404, InvalidParameterError), ) def list_all_ledger_details_data( - token_address: str, - issuer_address: Optional[str] = Header(None), - offset: int = Query(None), - limit: int = Query(None), - db: Session = Depends(db_session)): + token_address: str, + issuer_address: Optional[str] = Header(None), + offset: int = Query(None), + limit: int = Query(None), + db: Session = Depends(db_session), +): """List all Ledger Details Data""" # Validate Headers @@ -447,28 +488,36 @@ def list_all_ledger_details_data( # Token Exist Check if issuer_address is None: - _token = db.query(Token). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) else: - _token = db.query(Token). \ - filter(Token.token_address == token_address). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.token_address == token_address) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token does not exist") if _token.token_status == 0: raise InvalidParameterError("this token is temporarily unavailable") # Get Ledger Details Data(summary data_id) - query = db.query(LedgerDetailsData.data_id, - func.count(LedgerDetailsData.data_id), - func.max(LedgerDetailsData.data_created)). \ - filter(LedgerDetailsData.token_address == token_address). \ - group_by(LedgerDetailsData.data_id). \ - order_by(LedgerDetailsData.data_id) + query = ( + db.query( + LedgerDetailsData.data_id, + func.count(LedgerDetailsData.data_id), + func.max(LedgerDetailsData.data_created), + ) + .filter(LedgerDetailsData.token_address == token_address) + .group_by(LedgerDetailsData.data_id) + .order_by(LedgerDetailsData.data_id) + ) total = query.count() # NOTE: Because it don`t filter, `total` and `count` will be the same. @@ -484,20 +533,22 @@ def list_all_ledger_details_data( details_data = [] for _data_id, _count, _created in _details_data_list: created_formatted = utc_tz.localize(_created).astimezone(local_tz).isoformat() - details_data.append({ - "data_id": _data_id, - "count": _count, - "created": created_formatted, - }) + details_data.append( + { + "data_id": _data_id, + "count": _count, + "created": created_formatted, + } + ) resp = { "result_set": { "count": count, "offset": offset, "limit": limit, - "total": total + "total": total, }, - "details_data": details_data + "details_data": details_data, } return json_response(resp) @@ -507,24 +558,27 @@ def list_all_ledger_details_data( @router.post( "/{token_address}/details_data", response_model=LedgerDetailsDataResponse, - responses=get_routers_responses(422, 404, InvalidParameterError) + responses=get_routers_responses(422, 404, InvalidParameterError), ) def create_ledger_details_data( - token_address: str, - data_list: List[CreateUpdateLedgerDetailsDataRequest], - issuer_address: str = Header(...), - db: Session = Depends(db_session)): + token_address: str, + data_list: List[CreateUpdateLedgerDetailsDataRequest], + issuer_address: str = Header(...), + db: Session = Depends(db_session), +): """Create Ledger Details Data""" # Validate Headers validate_headers(issuer_address=(issuer_address, address_is_valid_address)) # Issuer Management Token Check - _token = db.query(Token). \ - filter(Token.token_address == token_address). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.token_address == token_address) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token does not exist") if _token.token_status == 0: @@ -544,22 +598,21 @@ def create_ledger_details_data( db.add(_details_data) db.commit() - return json_response({ - "data_id": data_id - }) + return json_response({"data_id": data_id}) # GET: /ledger/{token_address}/details_data/{data_id} @router.get( "/{token_address}/details_data/{data_id}", response_model=List[RetrieveLedgerDetailsDataResponse], - responses=get_routers_responses(422, 404, InvalidParameterError) + responses=get_routers_responses(422, 404, InvalidParameterError), ) def retrieve_ledger_details_data( - token_address: str, - data_id: str, - issuer_address: Optional[str] = Header(None), - db: Session = Depends(db_session)): + token_address: str, + data_id: str, + issuer_address: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Retrieve Ledger Details Data""" # Validate Headers @@ -567,37 +620,45 @@ def retrieve_ledger_details_data( # Token Exist Check if issuer_address is None: - _token = db.query(Token). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) else: - _token = db.query(Token). \ - filter(Token.token_address == token_address). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.token_address == token_address) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token does not exist") if _token.token_status == 0: raise InvalidParameterError("this token is temporarily unavailable") # Get Ledger Details Data - _details_data_list = db.query(LedgerDetailsData). \ - filter(LedgerDetailsData.token_address == token_address). \ - filter(LedgerDetailsData.data_id == data_id). \ - all() + _details_data_list = ( + db.query(LedgerDetailsData) + .filter(LedgerDetailsData.token_address == token_address) + .filter(LedgerDetailsData.data_id == data_id) + .all() + ) resp = [] for _details_data in _details_data_list: - resp.append({ - "name": _details_data.name, - "address": _details_data.address, - "amount": _details_data.amount, - "price": _details_data.price, - "balance": _details_data.balance, - "acquisition_date": _details_data.acquisition_date, - }) + resp.append( + { + "name": _details_data.name, + "address": _details_data.address, + "amount": _details_data.amount, + "price": _details_data.price, + "balance": _details_data.balance, + "acquisition_date": _details_data.acquisition_date, + } + ) return json_response(resp) @@ -606,35 +667,40 @@ def retrieve_ledger_details_data( @router.post( "/{token_address}/details_data/{data_id}", response_model=None, - responses=get_routers_responses(422, 404, InvalidParameterError) + responses=get_routers_responses(422, 404, InvalidParameterError), ) def update_ledger_details_data( - token_address: str, - data_id: str, - data_list: List[CreateUpdateLedgerDetailsDataRequest], - issuer_address: str = Header(...), - db: Session = Depends(db_session)): + token_address: str, + data_id: str, + data_list: List[CreateUpdateLedgerDetailsDataRequest], + issuer_address: str = Header(...), + db: Session = Depends(db_session), +): """Update Ledger Details Data""" # Validate Headers validate_headers(issuer_address=(issuer_address, address_is_valid_address)) # Issuer Management Token Check - _token = db.query(Token). \ - filter(Token.token_address == token_address). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.token_address == token_address) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token does not exist") if _token.token_status == 0: raise InvalidParameterError("this token is temporarily unavailable") # Delete + Insert Ledger Details Data - _details_data_list = db.query(LedgerDetailsData). \ - filter(LedgerDetailsData.token_address == token_address). \ - filter(LedgerDetailsData.data_id == data_id). \ - all() + _details_data_list = ( + db.query(LedgerDetailsData) + .filter(LedgerDetailsData.token_address == token_address) + .filter(LedgerDetailsData.data_id == data_id) + .all() + ) for _details_data in _details_data_list: db.delete(_details_data) for data_list in data_list: @@ -660,34 +726,39 @@ def update_ledger_details_data( @router.delete( "/{token_address}/details_data/{data_id}", response_model=None, - responses=get_routers_responses(422, 404, InvalidParameterError) + responses=get_routers_responses(422, 404, InvalidParameterError), ) def delete_ledger_details_data( - token_address: str, - data_id: str, - issuer_address: str = Header(...), - db: Session = Depends(db_session)): + token_address: str, + data_id: str, + issuer_address: str = Header(...), + db: Session = Depends(db_session), +): """Delete Ledger Details Data""" # Validate Headers validate_headers(issuer_address=(issuer_address, address_is_valid_address)) # Issuer Management Token Check - _token = db.query(Token). \ - filter(Token.token_address == token_address). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.token_address == token_address) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token does not exist") if _token.token_status == 0: raise InvalidParameterError("this token is temporarily unavailable") # Delete Ledger Details Data - _details_data_list = db.query(LedgerDetailsData). \ - filter(LedgerDetailsData.token_address == token_address). \ - filter(LedgerDetailsData.data_id == data_id). \ - all() + _details_data_list = ( + db.query(LedgerDetailsData) + .filter(LedgerDetailsData.token_address == token_address) + .filter(LedgerDetailsData.data_id == data_id) + .all() + ) for _details_data in _details_data_list: db.delete(_details_data) @@ -696,18 +767,20 @@ def delete_ledger_details_data( return -def __get_personal_info(token_address: str, token_type: str, account_address: str, db: Session): - token = db.query(Token). \ - filter(Token.token_address == token_address). \ - first() +def __get_personal_info( + token_address: str, token_type: str, account_address: str, db: Session +): + token = db.query(Token).filter(Token.token_address == token_address).first() if token is None: return None else: issuer_address = token.issuer_address - _idx_personal_info = db.query(IDXPersonalInfo). \ - filter(IDXPersonalInfo.account_address == account_address). \ - filter(IDXPersonalInfo.issuer_address == issuer_address). \ - first() + _idx_personal_info = ( + db.query(IDXPersonalInfo) + .filter(IDXPersonalInfo.account_address == account_address) + .filter(IDXPersonalInfo.issuer_address == issuer_address) + .first() + ) if _idx_personal_info is not None: # Get personal info from DB personal_info = _idx_personal_info.personal_info @@ -721,10 +794,9 @@ def __get_personal_info(token_address: str, token_type: str, account_address: st personal_info_contract = PersonalInfoContract( db=db, issuer_address=issuer_address, - contract_address=token_contract.personal_info_contract_address + contract_address=token_contract.personal_info_contract_address, ) personal_info = personal_info_contract.get_info( - account_address=account_address, - default_value=None + account_address=account_address, default_value=None ) return personal_info diff --git a/app/routers/notification.py b/app/routers/notification.py index d43f4d0c..e5a78eb4 100644 --- a/app/routers/notification.py +++ b/app/routers/notification.py @@ -17,27 +17,19 @@ SPDX-License-Identifier: Apache-2.0 """ from typing import Optional -import pytz -from fastapi import ( - APIRouter, - Header, - Query, - Depends -) +import pytz +from fastapi import APIRouter, Depends, Header, Query from fastapi.exceptions import HTTPException from sqlalchemy.orm import Session -from config import TZ from app.database import db_session from app.model.db import Notification from app.model.schema import ListAllNotificationsResponse -from app.utils.check_utils import ( - validate_headers, - address_is_valid_address -) -from app.utils.fastapi import json_response +from app.utils.check_utils import address_is_valid_address, validate_headers from app.utils.docs_utils import get_routers_responses +from app.utils.fastapi import json_response +from config import TZ router = APIRouter(tags=["notification"]) @@ -49,22 +41,21 @@ @router.get( "/notifications", response_model=ListAllNotificationsResponse, - responses=get_routers_responses(422) + responses=get_routers_responses(422), ) def list_all_notifications( issuer_address: Optional[str] = Header(None), notice_type: str = Query(None), offset: int = Query(None), limit: int = Query(None), - db: Session = Depends(db_session) + db: Session = Depends(db_session), ): """List all notifications""" # Validate Headers validate_headers(issuer_address=(issuer_address, address_is_valid_address)) - query = db.query(Notification). \ - order_by(Notification.created) + query = db.query(Notification).order_by(Notification.created) total = query.count() # Search Filter @@ -84,25 +75,29 @@ def list_all_notifications( notifications = [] for _notification in _notification_list: - created_formatted = utc_tz.localize(_notification.created).astimezone(local_tz).isoformat() - notifications.append({ - "notice_id": _notification.notice_id, - "issuer_address": _notification.issuer_address, - "priority": _notification.priority, - "notice_type": _notification.type, - "notice_code": _notification.code, - "metainfo": _notification.metainfo, - "created": created_formatted - }) + created_formatted = ( + utc_tz.localize(_notification.created).astimezone(local_tz).isoformat() + ) + notifications.append( + { + "notice_id": _notification.notice_id, + "issuer_address": _notification.issuer_address, + "priority": _notification.priority, + "notice_type": _notification.type, + "notice_code": _notification.code, + "metainfo": _notification.metainfo, + "created": created_formatted, + } + ) resp = { "result_set": { "count": count, "offset": offset, "limit": limit, - "total": total + "total": total, }, - "notifications": notifications + "notifications": notifications, } return json_response(resp) @@ -112,12 +107,10 @@ def list_all_notifications( @router.delete( "/notifications/{notice_id}", response_model=None, - responses=get_routers_responses(422, 404) + responses=get_routers_responses(422, 404), ) def delete_notification( - notice_id: str, - issuer_address: str = Header(...), - db: Session = Depends(db_session) + notice_id: str, issuer_address: str = Header(...), db: Session = Depends(db_session) ): """Delete notification""" @@ -125,10 +118,12 @@ def delete_notification( validate_headers(issuer_address=(issuer_address, address_is_valid_address)) # Get Notification - _notification = db.query(Notification). \ - filter(Notification.notice_id == notice_id). \ - filter(Notification.issuer_address == issuer_address). \ - first() + _notification = ( + db.query(Notification) + .filter(Notification.notice_id == notice_id) + .filter(Notification.issuer_address == issuer_address) + .first() + ) if _notification is None: raise HTTPException(status_code=404, detail="notification does not exist") diff --git a/app/routers/position.py b/app/routers/position.py index b26b3605..081b7ada 100644 --- a/app/routers/position.py +++ b/app/routers/position.py @@ -19,72 +19,54 @@ from typing import Optional from eth_keyfile import decode_keyfile_json -from fastapi import ( - APIRouter, - Depends, - Header, - Query, - Request -) +from fastapi import APIRouter, Depends, Header, Query, Request from fastapi.exceptions import HTTPException from pytz import timezone -from sqlalchemy import ( - String, - or_, - and_, - func, - literal, - null, - column, - desc -) +from sqlalchemy import String, and_, column, desc, func, literal, null, or_ from sqlalchemy.orm import Session from app.database import db_session +from app.exceptions import ( + AuthorizationError, + ContractRevertError, + InvalidParameterError, + SendTransactionError, +) from app.model.blockchain import ( IbetSecurityTokenInterface, + IbetShareContract, IbetStraightBondContract, - IbetShareContract -) -from app.model.blockchain.tx_params.ibet_security_token import ( - ForceUnlockParams ) +from app.model.blockchain.tx_params.ibet_security_token import ForceUnlockParams from app.model.db import ( - IDXPosition, - IDXLockedPosition, IDXLock, + IDXLockedPosition, + IDXPosition, IDXUnlock, Token, - TokenType + TokenType, ) from app.model.schema import ( - PositionResponse, - ListAllPositionResponse, + ForceUnlockRequest, ListAllLockedPositionResponse, - LockEventCategory, - ListAllLockEventsSortItem, ListAllLockEventsQuery, ListAllLockEventsResponse, - ForceUnlockRequest + ListAllLockEventsSortItem, + ListAllPositionResponse, + LockEventCategory, + PositionResponse, ) -from app.utils.fastapi import json_response -from app.utils.docs_utils import get_routers_responses from app.utils.check_utils import ( + address_is_valid_address, + check_auth, + eoa_password_is_encrypted_value, validate_headers, - address_is_valid_address, eoa_password_is_encrypted_value, check_auth -) -from app.exceptions import ( - InvalidParameterError, - AuthorizationError, - SendTransactionError, - ContractRevertError ) +from app.utils.docs_utils import get_routers_responses +from app.utils.fastapi import json_response from config import TZ -router = APIRouter( - prefix="/positions", - tags=["token_common"] -) +router = APIRouter(prefix="/positions", tags=["token_common"]) local_tz = timezone(TZ) @@ -94,7 +76,7 @@ "/{account_address}", summary="List all positions in the account", response_model=ListAllPositionResponse, - responses=get_routers_responses(422) + responses=get_routers_responses(422), ) def list_all_position( account_address: str, @@ -103,7 +85,7 @@ def list_all_position( token_type: Optional[TokenType] = Query(None), offset: Optional[int] = Query(None), limit: Optional[int] = Query(None), - db: Session = Depends(db_session) + db: Session = Depends(db_session), ): """List all account's position""" @@ -111,25 +93,36 @@ def list_all_position( validate_headers(issuer_address=(issuer_address, address_is_valid_address)) # Get a list of positions - query = db.query(IDXPosition, func.sum(IDXLockedPosition.value), Token). \ - join(Token, IDXPosition.token_address == Token.token_address). \ - outerjoin( + query = ( + db.query(IDXPosition, func.sum(IDXLockedPosition.value), Token) + .join(Token, IDXPosition.token_address == Token.token_address) + .outerjoin( IDXLockedPosition, - and_(IDXLockedPosition.token_address == IDXPosition.token_address, - IDXLockedPosition.account_address == IDXPosition.account_address) - ). \ - filter(IDXPosition.account_address == account_address). \ - filter(Token.token_status != 2). \ - group_by(IDXPosition.id, Token.id, IDXLockedPosition.token_address, IDXLockedPosition.account_address) + and_( + IDXLockedPosition.token_address == IDXPosition.token_address, + IDXLockedPosition.account_address == IDXPosition.account_address, + ), + ) + .filter(IDXPosition.account_address == account_address) + .filter(Token.token_status != 2) + .group_by( + IDXPosition.id, + Token.id, + IDXLockedPosition.token_address, + IDXLockedPosition.account_address, + ) + ) if not include_former_position: - query = query.filter(or_( - IDXPosition.balance != 0, - IDXPosition.exchange_balance != 0, - IDXPosition.pending_transfer != 0, - IDXPosition.exchange_commitment != 0, - IDXLockedPosition.value != 0 - )) + query = query.filter( + or_( + IDXPosition.balance != 0, + IDXPosition.exchange_balance != 0, + IDXPosition.pending_transfer != 0, + IDXPosition.exchange_commitment != 0, + IDXLockedPosition.value != 0, + ) + ) query = query.order_by(IDXPosition.token_address, IDXPosition.account_address) @@ -160,26 +153,28 @@ def list_all_position( elif _token.type == TokenType.IBET_SHARE.value: _share = IbetShareContract(_token.token_address).get() token_name = _share.name - positions.append({ - "issuer_address": _token.issuer_address, - "token_address": _token.token_address, - "token_type": _token.type, - "token_name": token_name, - "balance": _position.balance, - "exchange_balance": _position.exchange_balance, - "exchange_commitment": _position.exchange_commitment, - "pending_transfer": _position.pending_transfer, - "locked": _locked if _locked is not None else 0 - }) + positions.append( + { + "issuer_address": _token.issuer_address, + "token_address": _token.token_address, + "token_type": _token.type, + "token_name": token_name, + "balance": _position.balance, + "exchange_balance": _position.exchange_balance, + "exchange_commitment": _position.exchange_commitment, + "pending_transfer": _position.pending_transfer, + "locked": _locked if _locked is not None else 0, + } + ) resp = { "result_set": { "count": count, "offset": offset, "limit": limit, - "total": total + "total": total, }, - "positions": positions + "positions": positions, } return json_response(resp) @@ -190,7 +185,7 @@ def list_all_position( "/{account_address}/lock", summary="List all locked positions in the account", response_model=ListAllLockedPositionResponse, - responses=get_routers_responses(422) + responses=get_routers_responses(422), ) def list_all_locked_position( account_address: str, @@ -198,7 +193,7 @@ def list_all_locked_position( token_type: Optional[TokenType] = Query(None), offset: Optional[int] = Query(None), limit: Optional[int] = Query(None), - db: Session = Depends(db_session) + db: Session = Depends(db_session), ): """List all account's locked position""" @@ -206,12 +201,14 @@ def list_all_locked_position( validate_headers(issuer_address=(issuer_address, address_is_valid_address)) # Get a list of locked positions - query = db.query(IDXLockedPosition, Token).\ - join(Token, IDXLockedPosition.token_address == Token.token_address).\ - filter(IDXLockedPosition.account_address == account_address).\ - filter(IDXLockedPosition.value > 0).\ - filter(Token.token_status != 2).\ - order_by(IDXLockedPosition.token_address) + query = ( + db.query(IDXLockedPosition, Token) + .join(Token, IDXLockedPosition.token_address == Token.token_address) + .filter(IDXLockedPosition.account_address == account_address) + .filter(IDXLockedPosition.value > 0) + .filter(Token.token_status != 2) + .order_by(IDXLockedPosition.token_address) + ) if issuer_address is not None: query = query.filter(Token.issuer_address == issuer_address) @@ -242,23 +239,25 @@ def list_all_locked_position( elif _token.type == TokenType.IBET_SHARE.value: _share = IbetShareContract(_token.token_address).get() token_name = _share.name - positions.append({ - "issuer_address": _token.issuer_address, - "token_address": _token.token_address, - "token_type": _token.type, - "token_name": token_name, - "lock_address": _locked_position.lock_address, - "locked": _locked_position.value - }) + positions.append( + { + "issuer_address": _token.issuer_address, + "token_address": _token.token_address, + "token_type": _token.type, + "token_name": token_name, + "lock_address": _locked_position.lock_address, + "locked": _locked_position.value, + } + ) resp = { "result_set": { "count": count, "offset": offset, "limit": limit, - "total": total + "total": total, }, - "locked_positions": positions + "locked_positions": positions, } return json_response(resp) @@ -268,13 +267,13 @@ def list_all_locked_position( "/{account_address}/lock/events", summary="List all lock/unlock events in the account", response_model=ListAllLockEventsResponse, - responses=get_routers_responses(422) + responses=get_routers_responses(422), ) def list_all_lock_events( account_address: str, issuer_address: Optional[str] = Header(None), request_query: ListAllLockEventsQuery = Depends(), - db: Session = Depends(db_session) + db: Session = Depends(db_session), ): """List all lock/unlock events in the account""" @@ -288,39 +287,45 @@ def list_all_lock_events( sort_order = request_query.sort_order # Base query - query_lock = db.query( - literal(value=LockEventCategory.Lock.value, type_=String).label("category"), - IDXLock.transaction_hash.label("transaction_hash"), - IDXLock.token_address.label("token_address"), - IDXLock.lock_address.label("lock_address"), - IDXLock.account_address.label("account_address"), - null().label("recipient_address"), - IDXLock.value.label("value"), - IDXLock.data.label("data"), - IDXLock.block_timestamp.label("block_timestamp"), - Token - ).\ - join(Token, IDXLock.token_address == Token.token_address). \ - filter(column("account_address") == account_address).\ - filter(Token.token_status != 2) + query_lock = ( + db.query( + literal(value=LockEventCategory.Lock.value, type_=String).label("category"), + IDXLock.transaction_hash.label("transaction_hash"), + IDXLock.token_address.label("token_address"), + IDXLock.lock_address.label("lock_address"), + IDXLock.account_address.label("account_address"), + null().label("recipient_address"), + IDXLock.value.label("value"), + IDXLock.data.label("data"), + IDXLock.block_timestamp.label("block_timestamp"), + Token, + ) + .join(Token, IDXLock.token_address == Token.token_address) + .filter(column("account_address") == account_address) + .filter(Token.token_status != 2) + ) if issuer_address is not None: query_lock = query_lock.filter(Token.issuer_address == issuer_address) - query_unlock = db.query( - literal(value=LockEventCategory.Unlock.value, type_=String).label("category"), - IDXUnlock.transaction_hash.label("transaction_hash"), - IDXUnlock.token_address.label("token_address"), - IDXUnlock.lock_address.label("lock_address"), - IDXUnlock.account_address.label("account_address"), - IDXUnlock.recipient_address.label("recipient_address"), - IDXUnlock.value.label("value"), - IDXUnlock.data.label("data"), - IDXUnlock.block_timestamp.label("block_timestamp"), - Token - ).\ - join(Token, IDXUnlock.token_address == Token.token_address). \ - filter(column("account_address") == account_address).\ - filter(Token.token_status != 2) + query_unlock = ( + db.query( + literal(value=LockEventCategory.Unlock.value, type_=String).label( + "category" + ), + IDXUnlock.transaction_hash.label("transaction_hash"), + IDXUnlock.token_address.label("token_address"), + IDXUnlock.lock_address.label("lock_address"), + IDXUnlock.account_address.label("account_address"), + IDXUnlock.recipient_address.label("recipient_address"), + IDXUnlock.value.label("value"), + IDXUnlock.data.label("data"), + IDXUnlock.block_timestamp.label("block_timestamp"), + Token, + ) + .join(Token, IDXUnlock.token_address == Token.token_address) + .filter(column("account_address") == account_address) + .filter(Token.token_status != 2) + ) if issuer_address is not None: query_unlock = query_unlock.filter(Token.issuer_address == issuer_address) @@ -344,7 +349,9 @@ def list_all_lock_events( if request_query.lock_address is not None: query = query.filter(column("lock_address") == request_query.lock_address) if request_query.recipient_address is not None: - query = query.filter(column("recipient_address") == request_query.recipient_address) + query = query.filter( + column("recipient_address") == request_query.recipient_address + ) count = query.count() @@ -357,7 +364,9 @@ def list_all_lock_events( if sort_item != ListAllLockEventsSortItem.block_timestamp.value: # NOTE: Set secondary sort for consistent results - query = query.order_by(desc(column(ListAllLockEventsSortItem.block_timestamp.value))) + query = query.order_by( + desc(column(ListAllLockEventsSortItem.block_timestamp.value)) + ) # Pagination if offset is not None: @@ -379,29 +388,31 @@ def list_all_lock_events( token_name = _share.name block_timestamp_utc = timezone("UTC").localize(lock_event[8]) - resp_data.append({ - "category": lock_event[0], - "transaction_hash": lock_event[1], - "issuer_address": _token.issuer_address, - "token_address": lock_event[2], - "token_type": _token.type, - "token_name": token_name, - "lock_address": lock_event[3], - "account_address": lock_event[4], - "recipient_address": lock_event[5], - "value": lock_event[6], - "data": lock_event[7], - "block_timestamp": block_timestamp_utc.astimezone(local_tz).isoformat() - }) + resp_data.append( + { + "category": lock_event[0], + "transaction_hash": lock_event[1], + "issuer_address": _token.issuer_address, + "token_address": lock_event[2], + "token_type": _token.type, + "token_name": token_name, + "lock_address": lock_event[3], + "account_address": lock_event[4], + "recipient_address": lock_event[5], + "value": lock_event[6], + "data": lock_event[7], + "block_timestamp": block_timestamp_utc.astimezone(local_tz).isoformat(), + } + ) data = { "result_set": { "count": count, "offset": offset, "limit": limit, - "total": total + "total": total, }, - "events": resp_data + "events": resp_data, } return json_response(data) @@ -410,9 +421,14 @@ def list_all_lock_events( "/{account_address}/force_unlock", summary="Force unlock the locked position", response_model=None, - responses=get_routers_responses(401, 422, - AuthorizationError, InvalidParameterError, - SendTransactionError, ContractRevertError) + responses=get_routers_responses( + 401, + 422, + AuthorizationError, + InvalidParameterError, + SendTransactionError, + ContractRevertError, + ), ) def force_unlock( request: Request, @@ -420,14 +436,14 @@ def force_unlock( issuer_address: str = Header(...), eoa_password: Optional[str] = Header(None), auth_token: Optional[str] = Header(None), - db: Session = Depends(db_session) + db: Session = Depends(db_session), ): """Force unlock the locked position""" # Validate Headers validate_headers( issuer_address=(issuer_address, address_is_valid_address), - eoa_password=(eoa_password, eoa_password_is_encrypted_value) + eoa_password=(eoa_password, eoa_password_is_encrypted_value), ) # Authentication @@ -436,22 +452,23 @@ def force_unlock( db=db, issuer_address=issuer_address, eoa_password=eoa_password, - auth_token=auth_token + auth_token=auth_token, ) # Get private key keyfile_json = _account.keyfile private_key = decode_keyfile_json( - raw_keyfile_json=keyfile_json, - password=decrypt_password.encode("utf-8") + raw_keyfile_json=keyfile_json, password=decrypt_password.encode("utf-8") ) # Verify that the token is issued by the issuer_address - _token = db.query(Token). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_address == data.token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_address == data.token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise InvalidParameterError("token not found") if _token.token_status == 0: @@ -463,13 +480,13 @@ def force_unlock( "account_address": data.account_address, "recipient_address": data.recipient_address, "value": data.value, - "data": "" + "data": "", } try: IbetSecurityTokenInterface(data.token_address).force_unlock( data=ForceUnlockParams(**unlock_data), tx_from=issuer_address, - private_key=private_key + private_key=private_key, ) except ContractRevertError: raise @@ -484,13 +501,13 @@ def force_unlock( "/{account_address}/{token_address}", summary="Token position in the account", response_model=PositionResponse, - responses=get_routers_responses(422, InvalidParameterError, 404) + responses=get_routers_responses(422, InvalidParameterError, 404), ) def retrieve_position( account_address: str, token_address: str, issuer_address: Optional[str] = Header(None), - db: Session = Depends(db_session) + db: Session = Depends(db_session), ): """Retrieve account's position""" @@ -498,9 +515,11 @@ def retrieve_position( validate_headers(issuer_address=(issuer_address, address_is_valid_address)) # Get Token - query = db.query(Token). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2) + query = ( + db.query(Token) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + ) if issuer_address is not None: query = query.filter(Token.issuer_address == issuer_address) _token = query.first() @@ -510,16 +529,24 @@ def retrieve_position( raise InvalidParameterError("this token is temporarily unavailable") # Get Position - _record = db.query(IDXPosition, func.sum(IDXLockedPosition.value)). \ - outerjoin( + _record = ( + db.query(IDXPosition, func.sum(IDXLockedPosition.value)) + .outerjoin( IDXLockedPosition, - and_(IDXLockedPosition.token_address == IDXPosition.token_address, - IDXLockedPosition.account_address == IDXPosition.account_address) - ). \ - filter(IDXPosition.token_address == token_address). \ - filter(IDXPosition.account_address == account_address). \ - group_by(IDXPosition.id, IDXLockedPosition.token_address, IDXLockedPosition.account_address). \ - first() + and_( + IDXLockedPosition.token_address == IDXPosition.token_address, + IDXLockedPosition.account_address == IDXPosition.account_address, + ), + ) + .filter(IDXPosition.token_address == token_address) + .filter(IDXPosition.account_address == account_address) + .group_by( + IDXPosition.id, + IDXLockedPosition.token_address, + IDXLockedPosition.account_address, + ) + .first() + ) if _record is not None: _position = _record[0] @@ -531,10 +558,7 @@ def retrieve_position( if _position is None: # If there is no position, set default value(0) to each balance. _position = IDXPosition( - balance=0, - exchange_balance=0, - exchange_commitment=0, - pending_transfer=0 + balance=0, exchange_balance=0, exchange_commitment=0, pending_transfer=0 ) # Get Token Name @@ -555,7 +579,7 @@ def retrieve_position( "exchange_balance": _position.exchange_balance, "exchange_commitment": _position.exchange_commitment, "pending_transfer": _position.pending_transfer, - "locked": _locked if _locked is not None else 0 + "locked": _locked if _locked is not None else 0, } return json_response(resp) diff --git a/app/routers/share.py b/app/routers/share.py index 4db2f851..9f479cfa 100644 --- a/app/routers/share.py +++ b/app/routers/share.py @@ -19,143 +19,128 @@ import uuid from datetime import datetime from decimal import Decimal -from typing import ( - List, - Optional, - Type -) +from typing import List, Optional, Type -from fastapi import ( - APIRouter, - Depends, - Header, - Query, - Request -) +from eth_keyfile import decode_keyfile_json +from fastapi import APIRouter, Depends, Header, Query, Request from fastapi.exceptions import HTTPException +from pytz import timezone from sqlalchemy import ( - desc, - case, + String, and_, - or_, - func, - literal_column, + case, cast, - String, + column, + desc, + func, literal, + literal_column, null, - column -) -from sqlalchemy.orm import ( - Session, - aliased + or_, ) -from eth_keyfile import decode_keyfile_json -from pytz import timezone +from sqlalchemy.orm import Session, aliased import config from app import log from app.database import db_session -from app.model.schema import ( - # Request - IbetShareCreate, - IbetShareUpdate, - IbetShareTransfer, - IbetShareAdditionalIssue, - IbetShareRedeem, - RegisterPersonalInfoRequest, - IbetShareScheduledUpdate, - UpdateTransferApprovalOperationType, - UpdateTransferApprovalRequest, - ListTransferHistorySortItem, - ListTransferHistoryQuery, - ListAllTokenLockEventsQuery, - LockEventCategory, - ListAllTokenLockEventsSortItem, - # Response - IbetShareResponse, - TokenAddressResponse, - HolderResponse, - HolderCountResponse, - TransferHistoryResponse, - BulkTransferUploadIdResponse, - BulkTransferUploadResponse, - BulkTransferResponse, - ScheduledEventIdResponse, - ScheduledEventResponse, - TransferApprovalsResponse, - TransferApprovalHistoryResponse, - TransferApprovalTokenResponse, - BatchIssueRedeemUploadIdResponse, - GetBatchIssueRedeemResponse, - ListBatchIssueRedeemUploadResponse, - IssueRedeemHistoryResponse, - BatchRegisterPersonalInfoUploadResponse, - ListBatchRegisterPersonalInfoUploadResponse, - GetBatchRegisterPersonalInfoResponse, - ListAllTokenLockEventsResponse +from app.exceptions import ( + AuthorizationError, + ContractRevertError, + InvalidParameterError, + SendTransactionError, +) +from app.model.blockchain import ( + IbetSecurityTokenEscrow, + IbetShareContract, + PersonalInfoContract, + TokenListContract, +) +from app.model.blockchain.tx_params.ibet_security_token_escrow import ( + ApproveTransferParams as EscrowApproveTransferParams, +) +from app.model.blockchain.tx_params.ibet_share import ( + AdditionalIssueParams, + ApproveTransferParams, + CancelTransferParams, + RedeemParams, + TransferParams, + UpdateParams, ) from app.model.db import ( + UTXO, Account, - Token, - TokenType, - UpdateToken, - IDXPosition, - IDXLockedPosition, - IDXPersonalInfo, + BatchIssueRedeem, + BatchIssueRedeemProcessingCategory, + BatchIssueRedeemUpload, + BatchRegisterPersonalInfo, + BatchRegisterPersonalInfoUpload, + BatchRegisterPersonalInfoUploadStatus, BulkTransfer, BulkTransferUpload, - IDXTransfer, - IDXTransferApproval, - IDXTransferApprovalsSortItem, IDXIssueRedeem, IDXIssueRedeemEventType, IDXIssueRedeemSortItem, + IDXLock, + IDXLockedPosition, + IDXPersonalInfo, + IDXPosition, + IDXTransfer, + IDXTransferApproval, + IDXTransferApprovalsSortItem, + IDXUnlock, ScheduledEvents, - UTXO, - BatchIssueRedeemUpload, - BatchIssueRedeem, - BatchIssueRedeemProcessingCategory, - BatchRegisterPersonalInfoUpload, - BatchRegisterPersonalInfoUploadStatus, - BatchRegisterPersonalInfo, + Token, + TokenType, TransferApprovalHistory, TransferApprovalOperationType, - IDXLock, - IDXUnlock -) -from app.model.blockchain import ( - IbetShareContract, - TokenListContract, - PersonalInfoContract, - IbetSecurityTokenEscrow -) -from app.model.blockchain.tx_params.ibet_share import ( - UpdateParams, - TransferParams, - AdditionalIssueParams, - RedeemParams, - ApproveTransferParams, - CancelTransferParams + UpdateToken, ) -from app.model.blockchain.tx_params.ibet_security_token_escrow import ( - ApproveTransferParams as EscrowApproveTransferParams +from app.model.schema import ( # Request; Response + BatchIssueRedeemUploadIdResponse, + BatchRegisterPersonalInfoUploadResponse, + BulkTransferResponse, + BulkTransferUploadIdResponse, + BulkTransferUploadResponse, + GetBatchIssueRedeemResponse, + GetBatchRegisterPersonalInfoResponse, + HolderCountResponse, + HolderResponse, + IbetShareAdditionalIssue, + IbetShareCreate, + IbetShareRedeem, + IbetShareResponse, + IbetShareScheduledUpdate, + IbetShareTransfer, + IbetShareUpdate, + IssueRedeemHistoryResponse, + ListAllTokenLockEventsQuery, + ListAllTokenLockEventsResponse, + ListAllTokenLockEventsSortItem, + ListBatchIssueRedeemUploadResponse, + ListBatchRegisterPersonalInfoUploadResponse, + ListTransferHistoryQuery, + ListTransferHistorySortItem, + LockEventCategory, + RegisterPersonalInfoRequest, + ScheduledEventIdResponse, + ScheduledEventResponse, + TokenAddressResponse, + TransferApprovalHistoryResponse, + TransferApprovalsResponse, + TransferApprovalTokenResponse, + TransferHistoryResponse, + UpdateTransferApprovalOperationType, + UpdateTransferApprovalRequest, ) -from app.utils.fastapi import json_response -from app.utils.contract_utils import ContractUtils from app.utils.check_utils import ( - validate_headers, address_is_valid_address, + check_auth, eoa_password_is_encrypted_value, - check_auth + validate_headers, ) +from app.utils.contract_utils import ContractUtils from app.utils.docs_utils import get_routers_responses -from app.exceptions import ( - InvalidParameterError, - SendTransactionError, - ContractRevertError, - AuthorizationError -) +from app.utils.fastapi import json_response router = APIRouter( prefix="/share", @@ -170,21 +155,24 @@ @router.post( "/tokens", response_model=TokenAddressResponse, - responses=get_routers_responses(422, 401, AuthorizationError, SendTransactionError, ContractRevertError) + responses=get_routers_responses( + 422, 401, AuthorizationError, SendTransactionError, ContractRevertError + ), ) def issue_token( - request: Request, - token: IbetShareCreate, - issuer_address: str = Header(...), - eoa_password: Optional[str] = Header(None), - auth_token: Optional[str] = Header(None), - db: Session = Depends(db_session)): + request: Request, + token: IbetShareCreate, + issuer_address: str = Header(...), + eoa_password: Optional[str] = Header(None), + auth_token: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Issue ibetShare token""" # Validate Headers validate_headers( issuer_address=(issuer_address, address_is_valid_address), - eoa_password=(eoa_password, eoa_password_is_encrypted_value) + eoa_password=(eoa_password, eoa_password_is_encrypted_value), ) # Authentication @@ -193,22 +181,27 @@ def issue_token( db=db, issuer_address=issuer_address, eoa_password=eoa_password, - auth_token=auth_token + auth_token=auth_token, ) # Get private key keyfile_json = _account.keyfile private_key = decode_keyfile_json( - raw_keyfile_json=keyfile_json, - password=decrypt_password.encode("utf-8") + raw_keyfile_json=keyfile_json, password=decrypt_password.encode("utf-8") ) # Deploy _symbol = token.symbol if token.symbol is not None else "" _dividends = token.dividends if token.dividends is not None else 0 - _dividend_record_date = token.dividend_record_date if token.dividend_record_date is not None else "" - _dividend_payment_date = token.dividend_payment_date if token.dividend_payment_date is not None else "" - _cancellation_date = token.cancellation_date if token.cancellation_date is not None else "" + _dividend_record_date = ( + token.dividend_record_date if token.dividend_record_date is not None else "" + ) + _dividend_payment_date = ( + token.dividend_payment_date if token.dividend_payment_date is not None else "" + ) + _cancellation_date = ( + token.cancellation_date if token.cancellation_date is not None else "" + ) arguments = [ token.name, _symbol, @@ -218,21 +211,27 @@ def issue_token( _dividend_record_date, _dividend_payment_date, _cancellation_date, - token.principal_value + token.principal_value, ] try: contract_address, abi, tx_hash = IbetShareContract().create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) except SendTransactionError as e: raise SendTransactionError("failed to send transaction") # Check need update - update_items = ["tradable_exchange_contract_address", "personal_info_contract_address", "transferable", - "status", "is_offering", "contact_information", "privacy_policy", "transfer_approval_required", - "is_canceled"] + update_items = [ + "tradable_exchange_contract_address", + "personal_info_contract_address", + "transferable", + "status", + "is_offering", + "contact_information", + "privacy_policy", + "transfer_approval_required", + "is_canceled", + ] token_dict = token.__dict__ is_update = False for key in update_items: @@ -260,7 +259,7 @@ def issue_token( token_address=contract_address, token_template=TokenType.IBET_SHARE.value, tx_from=issuer_address, - private_key=private_key + private_key=private_key, ) except SendTransactionError: raise SendTransactionError("failed to register token address token list") @@ -300,42 +299,43 @@ def issue_token( db.commit() - return json_response({ - "token_address": _token.token_address, - "token_status": token_status - }) + return json_response( + {"token_address": _token.token_address, "token_status": token_status} + ) # GET: /share/tokens @router.get( "/tokens", response_model=List[IbetShareResponse], - responses=get_routers_responses(422) + responses=get_routers_responses(422), ) def list_all_tokens( - issuer_address: Optional[str] = Header(None), - db: Session = Depends(db_session)): + issuer_address: Optional[str] = Header(None), db: Session = Depends(db_session) +): # Validate Headers validate_headers(issuer_address=(issuer_address, address_is_valid_address)) """List all issued tokens""" # Get issued token list if issuer_address is None: - tokens = db.query(Token). \ - filter(Token.type == TokenType.IBET_SHARE). \ - all() + tokens = db.query(Token).filter(Token.type == TokenType.IBET_SHARE).all() else: - tokens = db.query(Token). \ - filter(Token.type == TokenType.IBET_SHARE). \ - filter(Token.issuer_address == issuer_address). \ - all() + tokens = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_SHARE) + .filter(Token.issuer_address == issuer_address) + .all() + ) share_tokens = [] for token in tokens: # Get contract data share_token = IbetShareContract(token.token_address).get().__dict__ issue_datetime_utc = timezone("UTC").localize(token.created) - share_token["issue_datetime"] = issue_datetime_utc.astimezone(local_tz).isoformat() + share_token["issue_datetime"] = issue_datetime_utc.astimezone( + local_tz + ).isoformat() share_token["token_status"] = token.token_status share_token.pop("contract_name") share_tokens.append(share_token) @@ -347,18 +347,18 @@ def list_all_tokens( @router.get( "/tokens/{token_address}", response_model=IbetShareResponse, - responses=get_routers_responses(404, InvalidParameterError) + responses=get_routers_responses(404, InvalidParameterError), ) -def retrieve_token( - token_address: str, - db: Session = Depends(db_session)): +def retrieve_token(token_address: str, db: Session = Depends(db_session)): """Retrieve token""" # Get Token - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_SHARE). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_SHARE) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: @@ -378,22 +378,31 @@ def retrieve_token( @router.post( "/tokens/{token_address}", response_model=None, - responses=get_routers_responses(422, 401, 404, AuthorizationError, InvalidParameterError, SendTransactionError, ContractRevertError) + responses=get_routers_responses( + 422, + 401, + 404, + AuthorizationError, + InvalidParameterError, + SendTransactionError, + ContractRevertError, + ), ) def update_token( - request: Request, - token_address: str, - token: IbetShareUpdate, - issuer_address: str = Header(...), - eoa_password: Optional[str] = Header(None), - auth_token: Optional[str] = Header(None), - db: Session = Depends(db_session)): + request: Request, + token_address: str, + token: IbetShareUpdate, + issuer_address: str = Header(...), + eoa_password: Optional[str] = Header(None), + auth_token: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Update a token""" # Validate Headers validate_headers( issuer_address=(issuer_address, address_is_valid_address), - eoa_password=(eoa_password, eoa_password_is_encrypted_value) + eoa_password=(eoa_password, eoa_password_is_encrypted_value), ) # Authentication @@ -402,23 +411,24 @@ def update_token( db=db, issuer_address=issuer_address, eoa_password=eoa_password, - auth_token=auth_token + auth_token=auth_token, ) # Get private key keyfile_json = _account.keyfile private_key = decode_keyfile_json( - raw_keyfile_json=keyfile_json, - password=decrypt_password.encode("utf-8") + raw_keyfile_json=keyfile_json, password=decrypt_password.encode("utf-8") ) # Get Token - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_SHARE). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_SHARE) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: @@ -429,7 +439,7 @@ def update_token( IbetShareContract(token_address).update( data=UpdateParams(**token.dict()), tx_from=issuer_address, - private_key=private_key + private_key=private_key, ) except SendTransactionError: raise SendTransactionError("failed to send transaction") @@ -443,32 +453,37 @@ def update_token( @router.get( "/tokens/{token_address}/additional_issue", response_model=IssueRedeemHistoryResponse, - responses=get_routers_responses(422, 404, InvalidParameterError) + responses=get_routers_responses(422, 404, InvalidParameterError), ) def list_additional_issuance_history( - token_address: str, - sort_item: IDXIssueRedeemSortItem = Query(IDXIssueRedeemSortItem.BLOCK_TIMESTAMP), - sort_order: int = Query(1, ge=0, le=1, description="0:asc, 1:desc"), - offset: Optional[int] = Query(None), - limit: Optional[int] = Query(None), - db: Session = Depends(db_session)): + token_address: str, + sort_item: IDXIssueRedeemSortItem = Query(IDXIssueRedeemSortItem.BLOCK_TIMESTAMP), + sort_order: int = Query(1, ge=0, le=1, description="0:asc, 1:desc"), + offset: Optional[int] = Query(None), + limit: Optional[int] = Query(None), + db: Session = Depends(db_session), +): """List additional issuance history""" # Get token - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_SHARE). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_SHARE) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: raise InvalidParameterError("this token is temporarily unavailable") # Get history record - query = db.query(IDXIssueRedeem). \ - filter(IDXIssueRedeem.event_type == IDXIssueRedeemEventType.ISSUE). \ - filter(IDXIssueRedeem.token_address == token_address) + query = ( + db.query(IDXIssueRedeem) + .filter(IDXIssueRedeem.event_type == IDXIssueRedeemEventType.ISSUE) + .filter(IDXIssueRedeem.token_address == token_address) + ) total = query.count() count = total @@ -492,46 +507,59 @@ def list_additional_issuance_history( history = [] for _event in _events: block_timestamp_utc = timezone("UTC").localize(_event.block_timestamp) - history.append({ - "transaction_hash": _event.transaction_hash, - "token_address": token_address, - "locked_address": _event.locked_address, - "target_address": _event.target_address, - "amount": _event.amount, - "block_timestamp": block_timestamp_utc.astimezone(local_tz).isoformat() - }) + history.append( + { + "transaction_hash": _event.transaction_hash, + "token_address": token_address, + "locked_address": _event.locked_address, + "target_address": _event.target_address, + "amount": _event.amount, + "block_timestamp": block_timestamp_utc.astimezone(local_tz).isoformat(), + } + ) - return json_response({ - "result_set": { - "count": count, - "offset": offset, - "limit": limit, - "total": total - }, - "history": history - }) + return json_response( + { + "result_set": { + "count": count, + "offset": offset, + "limit": limit, + "total": total, + }, + "history": history, + } + ) # POST: /share/tokens/{token_address}/additional_issue @router.post( "/tokens/{token_address}/additional_issue", response_model=None, - responses=get_routers_responses(422, 401, 404, AuthorizationError, InvalidParameterError, SendTransactionError, ContractRevertError) + responses=get_routers_responses( + 422, + 401, + 404, + AuthorizationError, + InvalidParameterError, + SendTransactionError, + ContractRevertError, + ), ) def additional_issue( - request: Request, - token_address: str, - data: IbetShareAdditionalIssue, - issuer_address: str = Header(...), - eoa_password: Optional[str] = Header(None), - auth_token: Optional[str] = Header(None), - db: Session = Depends(db_session)): + request: Request, + token_address: str, + data: IbetShareAdditionalIssue, + issuer_address: str = Header(...), + eoa_password: Optional[str] = Header(None), + auth_token: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Additional issue""" # Validate Headers validate_headers( issuer_address=(issuer_address, address_is_valid_address), - eoa_password=(eoa_password, eoa_password_is_encrypted_value) + eoa_password=(eoa_password, eoa_password_is_encrypted_value), ) # Authentication @@ -540,23 +568,24 @@ def additional_issue( db=db, issuer_address=issuer_address, eoa_password=eoa_password, - auth_token=auth_token + auth_token=auth_token, ) # Get private key keyfile_json = _account.keyfile private_key = decode_keyfile_json( - raw_keyfile_json=keyfile_json, - password=decrypt_password.encode("utf-8") + raw_keyfile_json=keyfile_json, password=decrypt_password.encode("utf-8") ) # Get Token - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_SHARE). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_SHARE) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: @@ -567,7 +596,7 @@ def additional_issue( IbetShareContract(token_address).additional_issue( data=AdditionalIssueParams(**data.dict()), tx_from=issuer_address, - private_key=private_key + private_key=private_key, ) except SendTransactionError: raise SendTransactionError("failed to send transaction") @@ -579,7 +608,7 @@ def additional_issue( @router.get( "/tokens/{token_address}/additional_issue/batch", response_model=ListBatchIssueRedeemUploadResponse, - responses=get_routers_responses(422) + responses=get_routers_responses(422), ) def list_all_additional_issue_upload( token_address: str, @@ -588,13 +617,17 @@ def list_all_additional_issue_upload( offset: Optional[int] = Query(None), limit: Optional[int] = Query(None), issuer_address: Optional[str] = Header(None), - db: Session = Depends(db_session) + db: Session = Depends(db_session), ): # Get a list of uploads - query = db.query(BatchIssueRedeemUpload). \ - filter(BatchIssueRedeemUpload.token_address == token_address). \ - filter(BatchIssueRedeemUpload.token_type == TokenType.IBET_SHARE). \ - filter(BatchIssueRedeemUpload.category == BatchIssueRedeemProcessingCategory.ISSUE) + query = ( + db.query(BatchIssueRedeemUpload) + .filter(BatchIssueRedeemUpload.token_address == token_address) + .filter(BatchIssueRedeemUpload.token_type == TokenType.IBET_SHARE) + .filter( + BatchIssueRedeemUpload.category == BatchIssueRedeemProcessingCategory.ISSUE + ) + ) if issuer_address is not None: query = query.filter(BatchIssueRedeemUpload.issuer_address == issuer_address) @@ -623,23 +656,25 @@ def list_all_additional_issue_upload( uploads = [] for _upload in _upload_list: created_utc = timezone("UTC").localize(_upload.created) - uploads.append({ - "batch_id": _upload.upload_id, - "issuer_address": _upload.issuer_address, - "token_type": _upload.token_type, - "token_address": _upload.token_address, - "processed": _upload.processed, - "created": created_utc.astimezone(local_tz).isoformat() - }) + uploads.append( + { + "batch_id": _upload.upload_id, + "issuer_address": _upload.issuer_address, + "token_type": _upload.token_type, + "token_address": _upload.token_address, + "processed": _upload.processed, + "created": created_utc.astimezone(local_tz).isoformat(), + } + ) resp = { "result_set": { "count": count, "offset": offset, "limit": limit, - "total": total + "total": total, }, - "uploads": uploads + "uploads": uploads, } return json_response(resp) @@ -648,22 +683,25 @@ def list_all_additional_issue_upload( @router.post( "/tokens/{token_address}/additional_issue/batch", response_model=BatchIssueRedeemUploadIdResponse, - responses=get_routers_responses(422, 401, 404, AuthorizationError, InvalidParameterError) + responses=get_routers_responses( + 422, 401, 404, AuthorizationError, InvalidParameterError + ), ) def additional_issue_in_batch( - request: Request, - token_address: str, - data: List[IbetShareAdditionalIssue], - issuer_address: str = Header(...), - eoa_password: Optional[str] = Header(None), - auth_token: Optional[str] = Header(None), - db: Session = Depends(db_session)): + request: Request, + token_address: str, + data: List[IbetShareAdditionalIssue], + issuer_address: str = Header(...), + eoa_password: Optional[str] = Header(None), + auth_token: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Additional issue (Batch)""" # Validate headers validate_headers( issuer_address=(issuer_address, address_is_valid_address), - eoa_password=(eoa_password, eoa_password_is_encrypted_value) + eoa_password=(eoa_password, eoa_password_is_encrypted_value), ) # Validate params @@ -676,16 +714,18 @@ def additional_issue_in_batch( db=db, issuer_address=issuer_address, eoa_password=eoa_password, - auth_token=auth_token + auth_token=auth_token, ) # Check token status - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_SHARE). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_SHARE) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: @@ -714,87 +754,96 @@ def additional_issue_in_batch( db.commit() - return json_response({ - "batch_id": str(upload_id) - }) + return json_response({"batch_id": str(upload_id)}) # GET: /share/tokens/{token_address}/additional_issue/batch/{batch_id} @router.get( "/tokens/{token_address}/additional_issue/batch/{batch_id}", response_model=GetBatchIssueRedeemResponse, - responses=get_routers_responses(422, 404) + responses=get_routers_responses(422, 404), ) def retrieve_batch_additional_issue( - token_address: str, - batch_id: str, - issuer_address: str = Header(...), - db: Session = Depends(db_session)): + token_address: str, + batch_id: str, + issuer_address: str = Header(...), + db: Session = Depends(db_session), +): """Get Batch status for additional issue""" # Validate Headers - validate_headers( - issuer_address=(issuer_address, address_is_valid_address) - ) + validate_headers(issuer_address=(issuer_address, address_is_valid_address)) # Upload Existence Check - batch: Optional[BatchIssueRedeemUpload] = db.query(BatchIssueRedeemUpload). \ - filter(BatchIssueRedeemUpload.upload_id == batch_id). \ - filter(BatchIssueRedeemUpload.issuer_address == issuer_address). \ - filter(BatchIssueRedeemUpload.token_type == TokenType.IBET_SHARE). \ - filter(BatchIssueRedeemUpload.token_address == token_address). \ - filter(BatchIssueRedeemUpload.category == BatchIssueRedeemProcessingCategory.ISSUE). \ - first() + batch: Optional[BatchIssueRedeemUpload] = ( + db.query(BatchIssueRedeemUpload) + .filter(BatchIssueRedeemUpload.upload_id == batch_id) + .filter(BatchIssueRedeemUpload.issuer_address == issuer_address) + .filter(BatchIssueRedeemUpload.token_type == TokenType.IBET_SHARE) + .filter(BatchIssueRedeemUpload.token_address == token_address) + .filter( + BatchIssueRedeemUpload.category == BatchIssueRedeemProcessingCategory.ISSUE + ) + .first() + ) if batch is None: raise HTTPException(status_code=404, detail="batch not found") # Get Batch Records - record_list: List[Type[BatchIssueRedeem]] = db.query(BatchIssueRedeem). \ - filter(BatchIssueRedeem.upload_id == batch_id). \ - all() + record_list: List[Type[BatchIssueRedeem]] = ( + db.query(BatchIssueRedeem).filter(BatchIssueRedeem.upload_id == batch_id).all() + ) - return json_response({ - "processed": batch.processed, - "results": [ - { - "account_address": record.account_address, - "amount": record.amount, - "status": record.status - } for record in record_list - ] - }) + return json_response( + { + "processed": batch.processed, + "results": [ + { + "account_address": record.account_address, + "amount": record.amount, + "status": record.status, + } + for record in record_list + ], + } + ) # GET: /share/tokens/{token_address}/redeem @router.get( "/tokens/{token_address}/redeem", response_model=IssueRedeemHistoryResponse, - responses=get_routers_responses(422, 404, InvalidParameterError) + responses=get_routers_responses(422, 404, InvalidParameterError), ) def list_redeem_history( - token_address: str, - sort_item: IDXIssueRedeemSortItem = Query(IDXIssueRedeemSortItem.BLOCK_TIMESTAMP), - sort_order: int = Query(1, ge=0, le=1, description="0:asc, 1:desc"), - offset: Optional[int] = Query(None), - limit: Optional[int] = Query(None), - db: Session = Depends(db_session)): + token_address: str, + sort_item: IDXIssueRedeemSortItem = Query(IDXIssueRedeemSortItem.BLOCK_TIMESTAMP), + sort_order: int = Query(1, ge=0, le=1, description="0:asc, 1:desc"), + offset: Optional[int] = Query(None), + limit: Optional[int] = Query(None), + db: Session = Depends(db_session), +): """List redemption history""" # Get token - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_SHARE). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_SHARE) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: raise InvalidParameterError("this token is temporarily unavailable") # Get history record - query = db.query(IDXIssueRedeem). \ - filter(IDXIssueRedeem.event_type == IDXIssueRedeemEventType.REDEEM). \ - filter(IDXIssueRedeem.token_address == token_address) + query = ( + db.query(IDXIssueRedeem) + .filter(IDXIssueRedeem.event_type == IDXIssueRedeemEventType.REDEEM) + .filter(IDXIssueRedeem.token_address == token_address) + ) total = query.count() count = total @@ -818,46 +867,59 @@ def list_redeem_history( history = [] for _event in _events: block_timestamp_utc = timezone("UTC").localize(_event.block_timestamp) - history.append({ - "transaction_hash": _event.transaction_hash, - "token_address": token_address, - "locked_address": _event.locked_address, - "target_address": _event.target_address, - "amount": _event.amount, - "block_timestamp": block_timestamp_utc.astimezone(local_tz).isoformat() - }) + history.append( + { + "transaction_hash": _event.transaction_hash, + "token_address": token_address, + "locked_address": _event.locked_address, + "target_address": _event.target_address, + "amount": _event.amount, + "block_timestamp": block_timestamp_utc.astimezone(local_tz).isoformat(), + } + ) - return json_response({ - "result_set": { - "count": count, - "offset": offset, - "limit": limit, - "total": total - }, - "history": history - }) + return json_response( + { + "result_set": { + "count": count, + "offset": offset, + "limit": limit, + "total": total, + }, + "history": history, + } + ) # POST: /share/tokens/{token_address}/redeem @router.post( "/tokens/{token_address}/redeem", response_model=None, - responses=get_routers_responses(422, 401, 404, AuthorizationError, InvalidParameterError, SendTransactionError, ContractRevertError) + responses=get_routers_responses( + 422, + 401, + 404, + AuthorizationError, + InvalidParameterError, + SendTransactionError, + ContractRevertError, + ), ) def redeem_token( - request: Request, - token_address: str, - data: IbetShareRedeem, - issuer_address: str = Header(...), - eoa_password: Optional[str] = Header(None), - auth_token: Optional[str] = Header(None), - db: Session = Depends(db_session)): + request: Request, + token_address: str, + data: IbetShareRedeem, + issuer_address: str = Header(...), + eoa_password: Optional[str] = Header(None), + auth_token: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Redeem a token""" # Validate Headers validate_headers( issuer_address=(issuer_address, address_is_valid_address), - eoa_password=(eoa_password, eoa_password_is_encrypted_value) + eoa_password=(eoa_password, eoa_password_is_encrypted_value), ) # Authentication @@ -866,23 +928,24 @@ def redeem_token( db=db, issuer_address=issuer_address, eoa_password=eoa_password, - auth_token=auth_token + auth_token=auth_token, ) # Get private key keyfile_json = _account.keyfile private_key = decode_keyfile_json( - raw_keyfile_json=keyfile_json, - password=decrypt_password.encode("utf-8") + raw_keyfile_json=keyfile_json, password=decrypt_password.encode("utf-8") ) # Get Token - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_SHARE). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_SHARE) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: @@ -893,7 +956,7 @@ def redeem_token( IbetShareContract(token_address).redeem( data=RedeemParams(**data.dict()), tx_from=issuer_address, - private_key=private_key + private_key=private_key, ) except SendTransactionError: raise SendTransactionError("failed to send transaction") @@ -905,7 +968,7 @@ def redeem_token( @router.get( "/tokens/{token_address}/redeem/batch", response_model=ListBatchIssueRedeemUploadResponse, - responses=get_routers_responses(422) + responses=get_routers_responses(422), ) def list_all_redeem_upload( token_address: str, @@ -914,13 +977,17 @@ def list_all_redeem_upload( offset: Optional[int] = Query(None), limit: Optional[int] = Query(None), issuer_address: Optional[str] = Header(None), - db: Session = Depends(db_session) + db: Session = Depends(db_session), ): # Get a list of uploads - query = db.query(BatchIssueRedeemUpload). \ - filter(BatchIssueRedeemUpload.token_address == token_address). \ - filter(BatchIssueRedeemUpload.token_type == TokenType.IBET_SHARE). \ - filter(BatchIssueRedeemUpload.category == BatchIssueRedeemProcessingCategory.REDEEM) + query = ( + db.query(BatchIssueRedeemUpload) + .filter(BatchIssueRedeemUpload.token_address == token_address) + .filter(BatchIssueRedeemUpload.token_type == TokenType.IBET_SHARE) + .filter( + BatchIssueRedeemUpload.category == BatchIssueRedeemProcessingCategory.REDEEM + ) + ) if issuer_address is not None: query = query.filter(BatchIssueRedeemUpload.issuer_address == issuer_address) @@ -949,23 +1016,25 @@ def list_all_redeem_upload( uploads = [] for _upload in _upload_list: created_utc = timezone("UTC").localize(_upload.created) - uploads.append({ - "batch_id": _upload.upload_id, - "issuer_address": _upload.issuer_address, - "token_type": _upload.token_type, - "token_address": _upload.token_address, - "processed": _upload.processed, - "created": created_utc.astimezone(local_tz).isoformat() - }) + uploads.append( + { + "batch_id": _upload.upload_id, + "issuer_address": _upload.issuer_address, + "token_type": _upload.token_type, + "token_address": _upload.token_address, + "processed": _upload.processed, + "created": created_utc.astimezone(local_tz).isoformat(), + } + ) resp = { "result_set": { "count": count, "offset": offset, "limit": limit, - "total": total + "total": total, }, - "uploads": uploads + "uploads": uploads, } return json_response(resp) @@ -974,22 +1043,25 @@ def list_all_redeem_upload( @router.post( "/tokens/{token_address}/redeem/batch", response_model=BatchIssueRedeemUploadIdResponse, - responses=get_routers_responses(422, 401, 404, AuthorizationError, InvalidParameterError) + responses=get_routers_responses( + 422, 401, 404, AuthorizationError, InvalidParameterError + ), ) def redeem_token_in_batch( - request: Request, - token_address: str, - data: List[IbetShareRedeem], - issuer_address: str = Header(...), - eoa_password: Optional[str] = Header(None), - auth_token: Optional[str] = Header(None), - db: Session = Depends(db_session)): + request: Request, + token_address: str, + data: List[IbetShareRedeem], + issuer_address: str = Header(...), + eoa_password: Optional[str] = Header(None), + auth_token: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Redeem a token (Batch)""" # Validate Headers validate_headers( issuer_address=(issuer_address, address_is_valid_address), - eoa_password=(eoa_password, eoa_password_is_encrypted_value) + eoa_password=(eoa_password, eoa_password_is_encrypted_value), ) # Validate params @@ -1002,16 +1074,18 @@ def redeem_token_in_batch( db=db, issuer_address=issuer_address, eoa_password=eoa_password, - auth_token=auth_token + auth_token=auth_token, ) # Check token status - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_SHARE). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_SHARE) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: @@ -1040,96 +1114,109 @@ def redeem_token_in_batch( db.commit() - return json_response({ - "batch_id": str(upload_id) - }) + return json_response({"batch_id": str(upload_id)}) # GET: /share/tokens/{token_address}/redeem/batch/{batch_id} @router.get( "/tokens/{token_address}/redeem/batch/{batch_id}", response_model=GetBatchIssueRedeemResponse, - responses=get_routers_responses(422, 404) + responses=get_routers_responses(422, 404), ) def retrieve_batch_additional_issue( - token_address: str, - batch_id: str, - issuer_address: str = Header(...), - db: Session = Depends(db_session)): + token_address: str, + batch_id: str, + issuer_address: str = Header(...), + db: Session = Depends(db_session), +): """Get Batch status for additional issue""" # Validate Headers - validate_headers( - issuer_address=(issuer_address, address_is_valid_address) - ) + validate_headers(issuer_address=(issuer_address, address_is_valid_address)) # Upload Existence Check - batch: Optional[BatchIssueRedeemUpload] = db.query(BatchIssueRedeemUpload). \ - filter(BatchIssueRedeemUpload.upload_id == batch_id). \ - filter(BatchIssueRedeemUpload.issuer_address == issuer_address). \ - filter(BatchIssueRedeemUpload.token_type == TokenType.IBET_SHARE). \ - filter(BatchIssueRedeemUpload.token_address == token_address). \ - filter(BatchIssueRedeemUpload.category == BatchIssueRedeemProcessingCategory.REDEEM). \ - first() + batch: Optional[BatchIssueRedeemUpload] = ( + db.query(BatchIssueRedeemUpload) + .filter(BatchIssueRedeemUpload.upload_id == batch_id) + .filter(BatchIssueRedeemUpload.issuer_address == issuer_address) + .filter(BatchIssueRedeemUpload.token_type == TokenType.IBET_SHARE) + .filter(BatchIssueRedeemUpload.token_address == token_address) + .filter( + BatchIssueRedeemUpload.category == BatchIssueRedeemProcessingCategory.REDEEM + ) + .first() + ) if batch is None: raise HTTPException(status_code=404, detail="batch not found") # Get Batch Records - record_list: List[Type[BatchIssueRedeem]] = db.query(BatchIssueRedeem). \ - filter(BatchIssueRedeem.upload_id == batch_id). \ - all() + record_list: List[Type[BatchIssueRedeem]] = ( + db.query(BatchIssueRedeem).filter(BatchIssueRedeem.upload_id == batch_id).all() + ) - return json_response({ - "processed": batch.processed, - "results": [ - { - "account_address": record.account_address, - "amount": record.amount, - "status": record.status - } for record in record_list - ] - }) + return json_response( + { + "processed": batch.processed, + "results": [ + { + "account_address": record.account_address, + "amount": record.amount, + "status": record.status, + } + for record in record_list + ], + } + ) # GET: /share/tokens/{token_address}/scheduled_events @router.get( "/tokens/{token_address}/scheduled_events", - response_model=List[ScheduledEventResponse] + response_model=List[ScheduledEventResponse], ) def list_all_scheduled_events( - token_address: str, - issuer_address: Optional[str] = Header(None), - db: Session = Depends(db_session)): + token_address: str, + issuer_address: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """List all scheduled update events""" if issuer_address is None: - _token_events = db.query(ScheduledEvents). \ - filter(ScheduledEvents.token_type == TokenType.IBET_SHARE). \ - filter(ScheduledEvents.token_address == token_address). \ - order_by(ScheduledEvents.id). \ - all() + _token_events = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.token_type == TokenType.IBET_SHARE) + .filter(ScheduledEvents.token_address == token_address) + .order_by(ScheduledEvents.id) + .all() + ) else: - _token_events = db.query(ScheduledEvents). \ - filter(ScheduledEvents.token_type == TokenType.IBET_SHARE). \ - filter(ScheduledEvents.issuer_address == issuer_address). \ - filter(ScheduledEvents.token_address == token_address). \ - order_by(ScheduledEvents.id). \ - all() + _token_events = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.token_type == TokenType.IBET_SHARE) + .filter(ScheduledEvents.issuer_address == issuer_address) + .filter(ScheduledEvents.token_address == token_address) + .order_by(ScheduledEvents.id) + .all() + ) token_events = [] for _token_event in _token_events: - scheduled_datetime_utc = timezone("UTC").localize(_token_event.scheduled_datetime) + scheduled_datetime_utc = timezone("UTC").localize( + _token_event.scheduled_datetime + ) created_utc = timezone("UTC").localize(_token_event.created) token_events.append( { "scheduled_event_id": _token_event.event_id, "token_address": token_address, "token_type": TokenType.IBET_SHARE.value, - "scheduled_datetime": scheduled_datetime_utc.astimezone(local_tz).isoformat(), + "scheduled_datetime": scheduled_datetime_utc.astimezone( + local_tz + ).isoformat(), "event_type": _token_event.event_type, "status": _token_event.status, "data": _token_event.data, - "created": created_utc.astimezone(local_tz).isoformat() + "created": created_utc.astimezone(local_tz).isoformat(), } ) return json_response(token_events) @@ -1139,22 +1226,25 @@ def list_all_scheduled_events( @router.post( "/tokens/{token_address}/scheduled_events", response_model=ScheduledEventIdResponse, - responses=get_routers_responses(422, 401, 404, AuthorizationError, InvalidParameterError) + responses=get_routers_responses( + 422, 401, 404, AuthorizationError, InvalidParameterError + ), ) def schedule_new_update_event( - request: Request, - token_address: str, - event_data: IbetShareScheduledUpdate, - issuer_address: str = Header(...), - eoa_password: Optional[str] = Header(None), - auth_token: Optional[str] = Header(None), - db: Session = Depends(db_session)): + request: Request, + token_address: str, + event_data: IbetShareScheduledUpdate, + issuer_address: str = Header(...), + eoa_password: Optional[str] = Header(None), + auth_token: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Register a new update event""" # Validate Headers validate_headers( issuer_address=(issuer_address, address_is_valid_address), - eoa_password=(eoa_password, eoa_password_is_encrypted_value) + eoa_password=(eoa_password, eoa_password_is_encrypted_value), ) # Authentication @@ -1163,16 +1253,18 @@ def schedule_new_update_event( db=db, issuer_address=issuer_address, eoa_password=eoa_password, - auth_token=auth_token + auth_token=auth_token, ) # Verify that the token is issued by the issuer - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_SHARE). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_SHARE) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: @@ -1191,74 +1283,82 @@ def schedule_new_update_event( db.add(_scheduled_event) db.commit() - return json_response({ - "scheduled_event_id": _scheduled_event.event_id - }) + return json_response({"scheduled_event_id": _scheduled_event.event_id}) # GET: /share/tokens/{token_address}/scheduled_events/{scheduled_event_id} @router.get( "/tokens/{token_address}/scheduled_events/{scheduled_event_id}", response_model=ScheduledEventResponse, - responses=get_routers_responses(404) + responses=get_routers_responses(404), ) def retrieve_token_event( - token_address: str, - scheduled_event_id: str, - issuer_address: Optional[str] = Header(None), - db: Session = Depends(db_session)): + token_address: str, + scheduled_event_id: str, + issuer_address: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Retrieve a scheduled token event""" if issuer_address is None: - _token_event = db.query(ScheduledEvents). \ - filter(ScheduledEvents.token_type == TokenType.IBET_SHARE). \ - filter(ScheduledEvents.event_id == scheduled_event_id). \ - filter(ScheduledEvents.token_address == token_address). \ - first() + _token_event = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.token_type == TokenType.IBET_SHARE) + .filter(ScheduledEvents.event_id == scheduled_event_id) + .filter(ScheduledEvents.token_address == token_address) + .first() + ) else: - _token_event = db.query(ScheduledEvents). \ - filter(ScheduledEvents.token_type == TokenType.IBET_SHARE). \ - filter(ScheduledEvents.event_id == scheduled_event_id). \ - filter(ScheduledEvents.issuer_address == issuer_address). \ - filter(ScheduledEvents.token_address == token_address). \ - first() + _token_event = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.token_type == TokenType.IBET_SHARE) + .filter(ScheduledEvents.event_id == scheduled_event_id) + .filter(ScheduledEvents.issuer_address == issuer_address) + .filter(ScheduledEvents.token_address == token_address) + .first() + ) if _token_event is None: raise HTTPException(status_code=404, detail="event not found") scheduled_datetime_utc = timezone("UTC").localize(_token_event.scheduled_datetime) created_utc = timezone("UTC").localize(_token_event.created) - return json_response({ - "scheduled_event_id": _token_event.event_id, - "token_address": token_address, - "token_type": TokenType.IBET_SHARE.value, - "scheduled_datetime": scheduled_datetime_utc.astimezone(local_tz).isoformat(), - "event_type": _token_event.event_type, - "status": _token_event.status, - "data": _token_event.data, - "created": created_utc.astimezone(local_tz).isoformat() - }) + return json_response( + { + "scheduled_event_id": _token_event.event_id, + "token_address": token_address, + "token_type": TokenType.IBET_SHARE.value, + "scheduled_datetime": scheduled_datetime_utc.astimezone( + local_tz + ).isoformat(), + "event_type": _token_event.event_type, + "status": _token_event.status, + "data": _token_event.data, + "created": created_utc.astimezone(local_tz).isoformat(), + } + ) # DELETE: /share/tokens/{token_address}/scheduled_events/{scheduled_event_id} @router.delete( "/tokens/{token_address}/scheduled_events/{scheduled_event_id}", response_model=ScheduledEventResponse, - responses=get_routers_responses(422, 401, 404, AuthorizationError) + responses=get_routers_responses(422, 401, 404, AuthorizationError), ) def delete_scheduled_event( - request: Request, - token_address: str, - scheduled_event_id: str, - issuer_address: str = Header(...), - eoa_password: Optional[str] = Header(None), - auth_token: Optional[str] = Header(None), - db: Session = Depends(db_session)): + request: Request, + token_address: str, + scheduled_event_id: str, + issuer_address: str = Header(...), + eoa_password: Optional[str] = Header(None), + auth_token: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Delete a scheduled event""" # Validate Headers validate_headers( issuer_address=(issuer_address, address_is_valid_address), - eoa_password=(eoa_password, eoa_password_is_encrypted_value) + eoa_password=(eoa_password, eoa_password_is_encrypted_value), ) # Authentication @@ -1267,16 +1367,18 @@ def delete_scheduled_event( db=db, issuer_address=issuer_address, eoa_password=eoa_password, - auth_token=auth_token + auth_token=auth_token, ) # Delete an event - _token_event = db.query(ScheduledEvents). \ - filter(ScheduledEvents.token_type == TokenType.IBET_SHARE). \ - filter(ScheduledEvents.event_id == scheduled_event_id). \ - filter(ScheduledEvents.issuer_address == issuer_address). \ - filter(ScheduledEvents.token_address == token_address). \ - first() + _token_event = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.token_type == TokenType.IBET_SHARE) + .filter(ScheduledEvents.event_id == scheduled_event_id) + .filter(ScheduledEvents.issuer_address == issuer_address) + .filter(ScheduledEvents.token_address == token_address) + .first() + ) if _token_event is None: raise HTTPException(status_code=404, detail="event not found") @@ -1290,7 +1392,7 @@ def delete_scheduled_event( "event_type": _token_event.event_type, "status": _token_event.status, "data": _token_event.data, - "created": created_utc.astimezone(local_tz).isoformat() + "created": created_utc.astimezone(local_tz).isoformat(), } db.delete(_token_event) @@ -1303,61 +1405,76 @@ def delete_scheduled_event( @router.get( "/tokens/{token_address}/holders", response_model=List[HolderResponse], - responses=get_routers_responses(422, InvalidParameterError, 404) + responses=get_routers_responses(422, InvalidParameterError, 404), ) def list_all_holders( - token_address: str, - include_former_holder: bool = False, - issuer_address: str = Header(...), - db: Session = Depends(db_session)): + token_address: str, + include_former_holder: bool = False, + issuer_address: str = Header(...), + db: Session = Depends(db_session), +): """List all share token holders""" # Validate Headers validate_headers(issuer_address=(issuer_address, address_is_valid_address)) # Get Account - _account = db.query(Account). \ - filter(Account.issuer_address == issuer_address). \ - first() + _account = ( + db.query(Account).filter(Account.issuer_address == issuer_address).first() + ) if _account is None: raise InvalidParameterError("issuer does not exist") # Get Token - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_SHARE). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_SHARE) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: raise InvalidParameterError("this token is temporarily unavailable") # Get Holders - query = db.query(IDXPosition, func.sum(IDXLockedPosition.value)). \ - outerjoin( + query = ( + db.query(IDXPosition, func.sum(IDXLockedPosition.value)) + .outerjoin( IDXLockedPosition, - and_(IDXLockedPosition.token_address == IDXPosition.token_address, - IDXLockedPosition.account_address == IDXPosition.account_address) - ). \ - filter(IDXPosition.token_address == token_address).\ - group_by(IDXPosition.id, IDXLockedPosition.token_address, IDXLockedPosition.account_address) + and_( + IDXLockedPosition.token_address == IDXPosition.token_address, + IDXLockedPosition.account_address == IDXPosition.account_address, + ), + ) + .filter(IDXPosition.token_address == token_address) + .group_by( + IDXPosition.id, + IDXLockedPosition.token_address, + IDXLockedPosition.account_address, + ) + ) if not include_former_holder: - query = query.filter(or_( - IDXPosition.balance != 0, - IDXPosition.exchange_balance != 0, - IDXPosition.pending_transfer != 0, - IDXPosition.exchange_commitment != 0, - IDXLockedPosition.value != 0 - )) + query = query.filter( + or_( + IDXPosition.balance != 0, + IDXPosition.exchange_balance != 0, + IDXPosition.pending_transfer != 0, + IDXPosition.exchange_commitment != 0, + IDXLockedPosition.value != 0, + ) + ) _holders = query.order_by(IDXPosition.id).all() # Get personal information - _personal_info_list = db.query(IDXPersonalInfo). \ - filter(IDXPersonalInfo.issuer_address == issuer_address). \ - all() + _personal_info_list = ( + db.query(IDXPersonalInfo) + .filter(IDXPersonalInfo.issuer_address == issuer_address) + .all() + ) _personal_info_dict = {} for item in _personal_info_list: _personal_info_dict[item.account_address] = item.personal_info @@ -1370,24 +1487,25 @@ def list_all_holders( "email": None, "birth": None, "is_corporate": None, - "tax_category": None + "tax_category": None, } holders = [] for _position, _locked in _holders: _personal_info = _personal_info_dict.get( - _position.account_address, - personal_info_default - ) - holders.append({ - "account_address": _position.account_address, - "personal_information": _personal_info, - "balance": _position.balance, - "exchange_balance": _position.exchange_balance, - "exchange_commitment": _position.exchange_commitment, - "pending_transfer": _position.pending_transfer, - "locked": _locked if _locked is not None else 0 - }) + _position.account_address, personal_info_default + ) + holders.append( + { + "account_address": _position.account_address, + "personal_information": _personal_info, + "balance": _position.balance, + "exchange_balance": _position.exchange_balance, + "exchange_commitment": _position.exchange_commitment, + "pending_transfer": _position.pending_transfer, + "locked": _locked if _locked is not None else 0, + } + ) return json_response(holders) @@ -1396,105 +1514,127 @@ def list_all_holders( @router.get( "/tokens/{token_address}/holders/count", response_model=HolderCountResponse, - responses=get_routers_responses(422, InvalidParameterError, 404) + responses=get_routers_responses(422, InvalidParameterError, 404), ) def count_number_of_holders( - token_address: str, - issuer_address: str = Header(...), - db: Session = Depends(db_session)): + token_address: str, + issuer_address: str = Header(...), + db: Session = Depends(db_session), +): """Count the number of holders""" # Validate Headers validate_headers(issuer_address=(issuer_address, address_is_valid_address)) # Get Account - _account = db.query(Account). \ - filter(Account.issuer_address == issuer_address). \ - first() + _account = ( + db.query(Account).filter(Account.issuer_address == issuer_address).first() + ) if _account is None: raise InvalidParameterError("issuer does not exist") # Get Token - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_SHARE). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_SHARE) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: raise InvalidParameterError("this token is temporarily unavailable") # Get Holders - _count: int = db.query(IDXPosition, func.sum(IDXLockedPosition.value)). \ - outerjoin( + _count: int = ( + db.query(IDXPosition, func.sum(IDXLockedPosition.value)) + .outerjoin( IDXLockedPosition, - and_(IDXLockedPosition.token_address == IDXPosition.token_address, - IDXLockedPosition.account_address == IDXPosition.account_address) - ). \ - filter(IDXPosition.token_address == token_address). \ - filter( - or_(IDXPosition.balance != 0, + and_( + IDXLockedPosition.token_address == IDXPosition.token_address, + IDXLockedPosition.account_address == IDXPosition.account_address, + ), + ) + .filter(IDXPosition.token_address == token_address) + .filter( + or_( + IDXPosition.balance != 0, IDXPosition.exchange_balance != 0, IDXPosition.pending_transfer != 0, IDXPosition.exchange_commitment != 0, - IDXLockedPosition.value != 0) - ). \ - group_by(IDXPosition.id, IDXLockedPosition.token_address, IDXLockedPosition.account_address). \ - count() + IDXLockedPosition.value != 0, + ) + ) + .group_by( + IDXPosition.id, + IDXLockedPosition.token_address, + IDXLockedPosition.account_address, + ) + .count() + ) - return json_response({ - "count": _count - }) + return json_response({"count": _count}) # GET: /share/tokens/{token_address}/holders/{account_address} @router.get( "/tokens/{token_address}/holders/{account_address}", response_model=HolderResponse, - responses=get_routers_responses(422, InvalidParameterError, 404) + responses=get_routers_responses(422, InvalidParameterError, 404), ) def retrieve_holder( - token_address: str, - account_address: str, - issuer_address: str = Header(...), - db: Session = Depends(db_session)): + token_address: str, + account_address: str, + issuer_address: str = Header(...), + db: Session = Depends(db_session), +): """Retrieve share token holder""" # Validate Headers validate_headers(issuer_address=(issuer_address, address_is_valid_address)) # Get Issuer - _account = db.query(Account). \ - filter(Account.issuer_address == issuer_address). \ - first() + _account = ( + db.query(Account).filter(Account.issuer_address == issuer_address).first() + ) if _account is None: raise InvalidParameterError("issuer does not exist") # Get Token - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_SHARE). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_SHARE) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: raise InvalidParameterError("this token is temporarily unavailable") # Get Holders - _holder = db.query(IDXPosition, func.sum(IDXLockedPosition.value)). \ - outerjoin( + _holder = ( + db.query(IDXPosition, func.sum(IDXLockedPosition.value)) + .outerjoin( IDXLockedPosition, - and_(IDXLockedPosition.token_address == IDXPosition.token_address, - IDXLockedPosition.account_address == IDXPosition.account_address) - ). \ - filter(IDXPosition.token_address == token_address). \ - filter(IDXPosition.account_address == account_address). \ - group_by(IDXPosition.id, IDXLockedPosition.token_address, IDXLockedPosition.account_address). \ - first() + and_( + IDXLockedPosition.token_address == IDXPosition.token_address, + IDXLockedPosition.account_address == IDXPosition.account_address, + ), + ) + .filter(IDXPosition.token_address == token_address) + .filter(IDXPosition.account_address == account_address) + .group_by( + IDXPosition.id, + IDXLockedPosition.token_address, + IDXLockedPosition.account_address, + ) + .first() + ) if _holder is None: balance = 0 @@ -1518,12 +1658,14 @@ def retrieve_holder( "email": None, "birth": None, "is_corporate": None, - "tax_category": None + "tax_category": None, } - _personal_info_record = db.query(IDXPersonalInfo). \ - filter(IDXPersonalInfo.account_address == account_address). \ - filter(IDXPersonalInfo.issuer_address == issuer_address). \ - first() + _personal_info_record = ( + db.query(IDXPersonalInfo) + .filter(IDXPersonalInfo.account_address == account_address) + .filter(IDXPersonalInfo.issuer_address == issuer_address) + .first() + ) if _personal_info_record is None: _personal_info = personal_info_default else: @@ -1536,33 +1678,41 @@ def retrieve_holder( "exchange_balance": exchange_balance, "exchange_commitment": exchange_commitment, "pending_transfer": pending_transfer, - "locked": locked if locked is not None else 0 + "locked": locked if locked is not None else 0, } return json_response(holder) - # POST: /share/tokens/{token_address}/personal_info @router.post( "/tokens/{token_address}/personal_info", response_model=None, - responses=get_routers_responses(422, 401, 404, AuthorizationError, InvalidParameterError, SendTransactionError, ContractRevertError) + responses=get_routers_responses( + 422, + 401, + 404, + AuthorizationError, + InvalidParameterError, + SendTransactionError, + ContractRevertError, + ), ) def register_holder_personal_info( - request: Request, - token_address: str, - personal_info: RegisterPersonalInfoRequest, - issuer_address: str = Header(...), - eoa_password: Optional[str] = Header(None), - auth_token: Optional[str] = Header(None), - db: Session = Depends(db_session)): + request: Request, + token_address: str, + personal_info: RegisterPersonalInfoRequest, + issuer_address: str = Header(...), + eoa_password: Optional[str] = Header(None), + auth_token: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Register the holder's personal information""" # Validate Headers validate_headers( issuer_address=(issuer_address, address_is_valid_address), - eoa_password=(eoa_password, eoa_password_is_encrypted_value) + eoa_password=(eoa_password, eoa_password_is_encrypted_value), ) # Authentication @@ -1571,16 +1721,18 @@ def register_holder_personal_info( db=db, issuer_address=issuer_address, eoa_password=eoa_password, - auth_token=auth_token + auth_token=auth_token, ) # Verify that the token is issued by the issuer_address - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_SHARE). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_SHARE) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: @@ -1592,12 +1744,12 @@ def register_holder_personal_info( personal_info_contract = PersonalInfoContract( db=db, issuer_address=issuer_address, - contract_address=token_contract.personal_info_contract_address + contract_address=token_contract.personal_info_contract_address, ) personal_info_contract.register_info( account_address=personal_info.account_address, data=personal_info.dict(), - default_value=None + default_value=None, ) except SendTransactionError: raise SendTransactionError("failed to register personal information") @@ -1609,33 +1761,37 @@ def register_holder_personal_info( @router.get( "/tokens/{token_address}/personal_info/batch", response_model=ListBatchRegisterPersonalInfoUploadResponse, - responses=get_routers_responses(422, 404, InvalidParameterError) + responses=get_routers_responses(422, 404, InvalidParameterError), ) def list_all_personal_info_batch_registration_uploads( - token_address: str, - issuer_address: str = Header(...), - status: Optional[str] = Query(None), - sort_order: int = Query(1, ge=0, le=1, description="0:asc, 1:desc (created)"), - offset: Optional[int] = Query(None), - limit: Optional[int] = Query(None), - db: Session = Depends(db_session)): + token_address: str, + issuer_address: str = Header(...), + status: Optional[str] = Query(None), + sort_order: int = Query(1, ge=0, le=1, description="0:asc, 1:desc (created)"), + offset: Optional[int] = Query(None), + limit: Optional[int] = Query(None), + db: Session = Depends(db_session), +): """List all personal information batch registration uploads""" # Verify that the token is issued by the issuer_address - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_SHARE). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_SHARE) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: raise InvalidParameterError("this token is temporarily unavailable") # Get a list of uploads - query = db.query(BatchRegisterPersonalInfoUpload). \ - filter(BatchRegisterPersonalInfoUpload.issuer_address == issuer_address) + query = db.query(BatchRegisterPersonalInfoUpload).filter( + BatchRegisterPersonalInfoUpload.issuer_address == issuer_address + ) total = query.count() @@ -1661,44 +1817,51 @@ def list_all_personal_info_batch_registration_uploads( uploads = [] for _upload in _upload_list: created_utc = timezone("UTC").localize(_upload.created) - uploads.append({ - "batch_id": _upload.upload_id, - "issuer_address": _upload.issuer_address, - "status": _upload.status, - "created": created_utc.astimezone(local_tz).isoformat() - }) - - return json_response({ - "result_set": { - "count": count, - "offset": offset, - "limit": limit, - "total": total - }, - "uploads": uploads - }) + uploads.append( + { + "batch_id": _upload.upload_id, + "issuer_address": _upload.issuer_address, + "status": _upload.status, + "created": created_utc.astimezone(local_tz).isoformat(), + } + ) + + return json_response( + { + "result_set": { + "count": count, + "offset": offset, + "limit": limit, + "total": total, + }, + "uploads": uploads, + } + ) # POST: /share/tokens/{token_address}/personal_info/batch @router.post( "/tokens/{token_address}/personal_info/batch", response_model=BatchRegisterPersonalInfoUploadResponse, - responses=get_routers_responses(422, 401, 404, AuthorizationError, InvalidParameterError) + responses=get_routers_responses( + 422, 401, 404, AuthorizationError, InvalidParameterError + ), ) def batch_register_personal_info( - request: Request, - token_address: str, - personal_info_list: List[RegisterPersonalInfoRequest], - issuer_address: str = Header(...), - eoa_password: Optional[str] = Header(None), - auth_token: Optional[str] = Header(None), - db: Session = Depends(db_session)): + request: Request, + token_address: str, + personal_info_list: List[RegisterPersonalInfoRequest], + issuer_address: str = Header(...), + eoa_password: Optional[str] = Header(None), + auth_token: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Create Batch for register personal information""" # Validate Headers validate_headers( issuer_address=(issuer_address, address_is_valid_address), - eoa_password=(eoa_password, eoa_password_is_encrypted_value) + eoa_password=(eoa_password, eoa_password_is_encrypted_value), ) # Authentication @@ -1707,16 +1870,18 @@ def batch_register_personal_info( db=db, issuer_address=issuer_address, eoa_password=eoa_password, - auth_token=auth_token + auth_token=auth_token, ) # Verify that the token is issued by the issuer_address - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_SHARE). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_SHARE) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: @@ -1742,24 +1907,30 @@ def batch_register_personal_info( db.commit() - return json_response({ - "batch_id": batch_id, - "status": batch.status, - "created": timezone("UTC").localize(batch.created).astimezone(local_tz).isoformat() - }) + return json_response( + { + "batch_id": batch_id, + "status": batch.status, + "created": timezone("UTC") + .localize(batch.created) + .astimezone(local_tz) + .isoformat(), + } + ) # GET: /share/tokens/{token_address}/personal_info/batch/{batch_id} @router.get( "/tokens/{token_address}/personal_info/batch/{batch_id}", response_model=GetBatchRegisterPersonalInfoResponse, - responses=get_routers_responses(422, 404) + responses=get_routers_responses(422, 404), ) def retrieve_batch_register_personal_info( - token_address: str, - batch_id: str, - issuer_address: str = Header(...), - db: Session = Depends(db_session)): + token_address: str, + batch_id: str, + issuer_address: str = Header(...), + db: Session = Depends(db_session), +): """Get Batch status for register personal information""" # Validate Headers @@ -1768,36 +1939,43 @@ def retrieve_batch_register_personal_info( ) # Upload Existence Check - batch: Optional[BatchRegisterPersonalInfoUpload] = db.query(BatchRegisterPersonalInfoUpload). \ - filter(BatchRegisterPersonalInfoUpload.upload_id == batch_id). \ - filter(BatchRegisterPersonalInfoUpload.issuer_address == issuer_address). \ - first() + batch: Optional[BatchRegisterPersonalInfoUpload] = ( + db.query(BatchRegisterPersonalInfoUpload) + .filter(BatchRegisterPersonalInfoUpload.upload_id == batch_id) + .filter(BatchRegisterPersonalInfoUpload.issuer_address == issuer_address) + .first() + ) if batch is None: raise HTTPException(status_code=404, detail="batch not found") # Get Batch Records - record_list = db.query(BatchRegisterPersonalInfo). \ - filter(BatchRegisterPersonalInfo.upload_id == batch_id). \ - filter(BatchRegisterPersonalInfo.token_address == token_address). \ - all() - - return json_response({ - "status": batch.status, - "results": [ - { - "status": record.status, - "account_address": record.account_address, - "key_manager": record.personal_info.get("key_manager"), - "name": record.personal_info.get("name"), - "postal_code": record.personal_info.get("postal_code"), - "address": record.personal_info.get("address"), - "email": record.personal_info.get("email"), - "birth": record.personal_info.get("birth"), - "is_corporate": record.personal_info.get("is_corporate"), - "tax_category": record.personal_info.get("tax_category") - } for record in record_list - ] - }) + record_list = ( + db.query(BatchRegisterPersonalInfo) + .filter(BatchRegisterPersonalInfo.upload_id == batch_id) + .filter(BatchRegisterPersonalInfo.token_address == token_address) + .all() + ) + + return json_response( + { + "status": batch.status, + "results": [ + { + "status": record.status, + "account_address": record.account_address, + "key_manager": record.personal_info.get("key_manager"), + "name": record.personal_info.get("name"), + "postal_code": record.personal_info.get("postal_code"), + "address": record.personal_info.get("address"), + "email": record.personal_info.get("email"), + "birth": record.personal_info.get("birth"), + "is_corporate": record.personal_info.get("is_corporate"), + "tax_category": record.personal_info.get("tax_category"), + } + for record in record_list + ], + } + ) # GET: /share/tokens/{token_address}/lock_events @@ -1805,13 +1983,13 @@ def retrieve_batch_register_personal_info( "/tokens/{token_address}/lock_events", summary="List all lock/unlock events related to given share token", response_model=ListAllTokenLockEventsResponse, - responses=get_routers_responses(422) + responses=get_routers_responses(422), ) def list_all_lock_events_by_share( token_address: str, issuer_address: Optional[str] = Header(None), request_query: ListAllTokenLockEventsQuery = Depends(), - db: Session = Depends(db_session) + db: Session = Depends(db_session), ): # Validate Headers validate_headers(issuer_address=(issuer_address, address_is_valid_address)) @@ -1834,19 +2012,21 @@ def list_all_lock_events_by_share( IDXLock.value.label("value"), IDXLock.data.label("data"), IDXLock.block_timestamp.label("block_timestamp"), - Token - ). - join(Token, IDXLock.token_address == Token.token_address). - filter(Token.type == TokenType.IBET_SHARE). - filter(Token.token_address == token_address). - filter(Token.token_status != 2) + Token, + ) + .join(Token, IDXLock.token_address == Token.token_address) + .filter(Token.type == TokenType.IBET_SHARE) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) ) if issuer_address is not None: query_lock = query_lock.filter(Token.issuer_address == issuer_address) query_unlock = ( db.query( - literal(value=LockEventCategory.Unlock.value, type_=String).label("category"), + literal(value=LockEventCategory.Unlock.value, type_=String).label( + "category" + ), IDXUnlock.transaction_hash.label("transaction_hash"), IDXUnlock.token_address.label("token_address"), IDXUnlock.lock_address.label("lock_address"), @@ -1855,12 +2035,12 @@ def list_all_lock_events_by_share( IDXUnlock.value.label("value"), IDXUnlock.data.label("data"), IDXUnlock.block_timestamp.label("block_timestamp"), - Token - ). - join(Token, IDXUnlock.token_address == Token.token_address). - filter(Token.type == TokenType.IBET_SHARE). - filter(Token.token_address == token_address). - filter(Token.token_status != 2) + Token, + ) + .join(Token, IDXUnlock.token_address == Token.token_address) + .filter(Token.type == TokenType.IBET_SHARE) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) ) if issuer_address is not None: query_unlock = query_unlock.filter(Token.issuer_address == issuer_address) @@ -1881,7 +2061,9 @@ def list_all_lock_events_by_share( if request_query.lock_address is not None: query = query.filter(column("lock_address") == request_query.lock_address) if request_query.recipient_address is not None: - query = query.filter(column("recipient_address") == request_query.recipient_address) + query = query.filter( + column("recipient_address") == request_query.recipient_address + ) count = query.count() @@ -1894,7 +2076,9 @@ def list_all_lock_events_by_share( if sort_item != ListAllTokenLockEventsSortItem.block_timestamp.value: # NOTE: Set secondary sort for consistent results - query = query.order_by(desc(column(ListAllTokenLockEventsSortItem.block_timestamp.value))) + query = query.order_by( + desc(column(ListAllTokenLockEventsSortItem.block_timestamp.value)) + ) # Pagination if offset is not None: @@ -1911,29 +2095,31 @@ def list_all_lock_events_by_share( token_name = _share.name block_timestamp_utc = timezone("UTC").localize(lock_event[8]) - resp_data.append({ - "category": lock_event[0], - "transaction_hash": lock_event[1], - "issuer_address": _token.issuer_address, - "token_address": lock_event[2], - "token_type": _token.type, - "token_name": token_name, - "lock_address": lock_event[3], - "account_address": lock_event[4], - "recipient_address": lock_event[5], - "value": lock_event[6], - "data": lock_event[7], - "block_timestamp": block_timestamp_utc.astimezone(local_tz).isoformat() - }) + resp_data.append( + { + "category": lock_event[0], + "transaction_hash": lock_event[1], + "issuer_address": _token.issuer_address, + "token_address": lock_event[2], + "token_type": _token.type, + "token_name": token_name, + "lock_address": lock_event[3], + "account_address": lock_event[4], + "recipient_address": lock_event[5], + "value": lock_event[6], + "data": lock_event[7], + "block_timestamp": block_timestamp_utc.astimezone(local_tz).isoformat(), + } + ) data = { "result_set": { "count": count, "offset": offset, "limit": limit, - "total": total + "total": total, }, - "events": resp_data + "events": resp_data, } return json_response(data) @@ -1942,21 +2128,30 @@ def list_all_lock_events_by_share( @router.post( "/transfers", response_model=None, - responses=get_routers_responses(422, 401, 404, AuthorizationError, InvalidParameterError, SendTransactionError, ContractRevertError) + responses=get_routers_responses( + 422, + 401, + 404, + AuthorizationError, + InvalidParameterError, + SendTransactionError, + ContractRevertError, + ), ) def transfer_ownership( - request: Request, - token: IbetShareTransfer, - issuer_address: str = Header(...), - eoa_password: Optional[str] = Header(None), - auth_token: Optional[str] = Header(None), - db: Session = Depends(db_session)): + request: Request, + token: IbetShareTransfer, + issuer_address: str = Header(...), + eoa_password: Optional[str] = Header(None), + auth_token: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Transfer token ownership""" # Validate Headers validate_headers( issuer_address=(issuer_address, address_is_valid_address), - eoa_password=(eoa_password, eoa_password_is_encrypted_value) + eoa_password=(eoa_password, eoa_password_is_encrypted_value), ) # Authentication @@ -1965,23 +2160,24 @@ def transfer_ownership( db=db, issuer_address=issuer_address, eoa_password=eoa_password, - auth_token=auth_token + auth_token=auth_token, ) # Get private key keyfile_json = _account.keyfile private_key = decode_keyfile_json( - raw_keyfile_json=keyfile_json, - password=decrypt_password.encode("utf-8") + raw_keyfile_json=keyfile_json, password=decrypt_password.encode("utf-8") ) # Check that it is a token that has been issued. - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_SHARE). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_address == token.token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_SHARE) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_address == token.token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: @@ -1991,7 +2187,7 @@ def transfer_ownership( IbetShareContract(token.token_address).transfer( data=TransferParams(**token.dict()), tx_from=issuer_address, - private_key=private_key + private_key=private_key, ) except SendTransactionError: raise SendTransactionError("failed to send transaction") @@ -2003,34 +2199,37 @@ def transfer_ownership( @router.get( "/transfers/{token_address}", response_model=TransferHistoryResponse, - responses=get_routers_responses(422, 404, InvalidParameterError) + responses=get_routers_responses(422, 404, InvalidParameterError), ) def list_transfer_history( token_address: str, request_query: ListTransferHistoryQuery = Depends(), - db: Session = Depends(db_session) + db: Session = Depends(db_session), ): """List token transfer history""" # Get token - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_SHARE). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_SHARE) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: raise InvalidParameterError("this token is temporarily unavailable") # Get transfer history - query = db.query(IDXTransfer). \ - filter(IDXTransfer.token_address == token_address) + query = db.query(IDXTransfer).filter(IDXTransfer.token_address == token_address) total = query.count() if request_query.source_event is not None: query = query.filter(IDXTransfer.source_event == request_query.source_event) if request_query.data is not None: - query = query.filter(cast(IDXTransfer.data, String).like("%" + request_query.data + "%")) + query = query.filter( + cast(IDXTransfer.data, String).like("%" + request_query.data + "%") + ) count = query.count() # Sort @@ -2053,39 +2252,43 @@ def list_transfer_history( transfer_history = [] for _transfer in _transfers: block_timestamp_utc = timezone("UTC").localize(_transfer.block_timestamp) - transfer_history.append({ - "transaction_hash": _transfer.transaction_hash, - "token_address": token_address, - "from_address": _transfer.from_address, - "to_address": _transfer.to_address, - "amount": _transfer.amount, - "source_event": _transfer.source_event, - "data": _transfer.data, - "block_timestamp": block_timestamp_utc.astimezone(local_tz).isoformat() - }) - - return json_response({ - "result_set": { - "count": count, - "offset": request_query.offset, - "limit": request_query.limit, - "total": total - }, - "transfer_history": transfer_history - }) + transfer_history.append( + { + "transaction_hash": _transfer.transaction_hash, + "token_address": token_address, + "from_address": _transfer.from_address, + "to_address": _transfer.to_address, + "amount": _transfer.amount, + "source_event": _transfer.source_event, + "data": _transfer.data, + "block_timestamp": block_timestamp_utc.astimezone(local_tz).isoformat(), + } + ) + + return json_response( + { + "result_set": { + "count": count, + "offset": request_query.offset, + "limit": request_query.limit, + "total": total, + }, + "transfer_history": transfer_history, + } + ) # GET: /share/transfer_approvals @router.get( "/transfer_approvals", response_model=TransferApprovalsResponse, - responses=get_routers_responses(422) + responses=get_routers_responses(422), ) def list_transfer_approval_history( issuer_address: Optional[str] = Header(None), offset: Optional[int] = Query(None), limit: Optional[int] = Query(None), - db: Session = Depends(db_session) + db: Session = Depends(db_session), ): """List transfer approval history""" # Create a subquery for 'status' added IDXTransferApproval @@ -2096,54 +2299,71 @@ def list_transfer_approval_history( TransferApprovalHistory, case( ( - and_(IDXTransferApproval.escrow_finished == True, - IDXTransferApproval.transfer_approved == None, - TransferApprovalHistory.operation_type == None), - 1 + and_( + IDXTransferApproval.escrow_finished == True, + IDXTransferApproval.transfer_approved == None, + TransferApprovalHistory.operation_type == None, + ), + 1, ), # EscrowFinish(escrow_finished) ( - and_(IDXTransferApproval.transfer_approved == None, - TransferApprovalHistory.operation_type == TransferApprovalOperationType.APPROVE.value), - 2 + and_( + IDXTransferApproval.transfer_approved == None, + TransferApprovalHistory.operation_type + == TransferApprovalOperationType.APPROVE.value, + ), + 2, ), # Approve(operation completed, event synchronizing) ( IDXTransferApproval.transfer_approved == True, - 2 + 2, ), # Approve(transferred) ( - and_(IDXTransferApproval.cancelled == None, - TransferApprovalHistory.operation_type == TransferApprovalOperationType.CANCEL.value), - 3 + and_( + IDXTransferApproval.cancelled == None, + TransferApprovalHistory.operation_type + == TransferApprovalOperationType.CANCEL.value, + ), + 3, ), # Cancel(operation completed, event synchronizing) - ( - IDXTransferApproval.cancelled == True, - 3 - ), # Cancel(canceled) - else_=0 # ApplyFor(unapproved) - ).label("status") - ).outerjoin( + (IDXTransferApproval.cancelled == True, 3), # Cancel(canceled) + else_=0, # ApplyFor(unapproved) + ).label("status"), + ) + .outerjoin( TransferApprovalHistory, - and_(IDXTransferApproval.token_address == TransferApprovalHistory.token_address, - IDXTransferApproval.exchange_address == TransferApprovalHistory.exchange_address, - IDXTransferApproval.application_id == TransferApprovalHistory.application_id) - ).subquery() + and_( + IDXTransferApproval.token_address + == TransferApprovalHistory.token_address, + IDXTransferApproval.exchange_address + == TransferApprovalHistory.exchange_address, + IDXTransferApproval.application_id + == TransferApprovalHistory.application_id, + ), + ) + .subquery(), ) # Get transfer approval history - query = db.query(Token.issuer_address, - subquery.token_address, - func.count(subquery.id), - func.count(or_(literal_column("status") == 0, None)), - func.count(or_(literal_column("status") == 1, None)), - func.count(or_(literal_column("status") == 2, None)), - func.count(or_(literal_column("status") == 3, None))). \ - join(Token, subquery.token_address == Token.token_address). \ - filter(Token.type == TokenType.IBET_SHARE). \ - filter(Token.token_status != 2) + query = ( + db.query( + Token.issuer_address, + subquery.token_address, + func.count(subquery.id), + func.count(or_(literal_column("status") == 0, None)), + func.count(or_(literal_column("status") == 1, None)), + func.count(or_(literal_column("status") == 2, None)), + func.count(or_(literal_column("status") == 3, None)), + ) + .join(Token, subquery.token_address == Token.token_address) + .filter(Token.type == TokenType.IBET_SHARE) + .filter(Token.token_status != 2) + ) if issuer_address is not None: query = query.filter(Token.issuer_address == issuer_address) - query = query.group_by(Token.issuer_address, subquery.token_address). \ - order_by(Token.issuer_address, subquery.token_address) + query = query.group_by(Token.issuer_address, subquery.token_address).order_by( + Token.issuer_address, subquery.token_address + ) total = query.count() # NOTE: Because no filtering is performed, `total` and `count` have the same value. @@ -2157,59 +2377,73 @@ def list_transfer_approval_history( _transfer_approvals = query.all() transfer_approvals = [] - for issuer_address, token_address, application_count, \ - unapproved_count, escrow_finished_count, transferred_count, canceled_count \ - in _transfer_approvals: - transfer_approvals.append({ - "issuer_address": issuer_address, - "token_address": token_address, - "application_count": application_count, - "unapproved_count": unapproved_count, - "escrow_finished_count": escrow_finished_count, - "transferred_count": transferred_count, - "canceled_count": canceled_count, - }) - - return json_response({ - "result_set": { - "count": count, - "offset": offset, - "limit": limit, - "total": total - }, - "transfer_approvals": transfer_approvals - }) + for ( + issuer_address, + token_address, + application_count, + unapproved_count, + escrow_finished_count, + transferred_count, + canceled_count, + ) in _transfer_approvals: + transfer_approvals.append( + { + "issuer_address": issuer_address, + "token_address": token_address, + "application_count": application_count, + "unapproved_count": unapproved_count, + "escrow_finished_count": escrow_finished_count, + "transferred_count": transferred_count, + "canceled_count": canceled_count, + } + ) + + return json_response( + { + "result_set": { + "count": count, + "offset": offset, + "limit": limit, + "total": total, + }, + "transfer_approvals": transfer_approvals, + } + ) # GET: /share/transfer_approvals/{token_address} @router.get( "/transfer_approvals/{token_address}", response_model=TransferApprovalHistoryResponse, - responses=get_routers_responses(422, 404, InvalidParameterError) + responses=get_routers_responses(422, 404, InvalidParameterError), ) def list_token_transfer_approval_history( - token_address: str, - from_address: Optional[str] = Query(None), - to_address: Optional[str] = Query(None), - status: Optional[List[int]] = Query( - None, - ge=0, - le=3, - description="0:unapproved, 1:escrow_finished, 2:transferred, 3:canceled" - ), - sort_item: Optional[IDXTransferApprovalsSortItem] = Query(IDXTransferApprovalsSortItem.ID), - sort_order: Optional[int] = Query(1, ge=0, le=1, description="0:asc, 1:desc"), - offset: Optional[int] = Query(None), - limit: Optional[int] = Query(None), - db: Session = Depends(db_session) + token_address: str, + from_address: Optional[str] = Query(None), + to_address: Optional[str] = Query(None), + status: Optional[List[int]] = Query( + None, + ge=0, + le=3, + description="0:unapproved, 1:escrow_finished, 2:transferred, 3:canceled", + ), + sort_item: Optional[IDXTransferApprovalsSortItem] = Query( + IDXTransferApprovalsSortItem.ID + ), + sort_order: Optional[int] = Query(1, ge=0, le=1, description="0:asc, 1:desc"), + offset: Optional[int] = Query(None), + limit: Optional[int] = Query(None), + db: Session = Depends(db_session), ): """List token transfer approval history""" # Get token - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_SHARE). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_SHARE) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: @@ -2223,42 +2457,55 @@ def list_token_transfer_approval_history( TransferApprovalHistory, case( ( - and_(IDXTransferApproval.escrow_finished == True, - IDXTransferApproval.transfer_approved == None, - TransferApprovalHistory.operation_type == None), - 1 + and_( + IDXTransferApproval.escrow_finished == True, + IDXTransferApproval.transfer_approved == None, + TransferApprovalHistory.operation_type == None, + ), + 1, ), # EscrowFinish(escrow_finished) ( - and_(IDXTransferApproval.transfer_approved == None, - TransferApprovalHistory.operation_type == TransferApprovalOperationType.APPROVE.value), - 2 + and_( + IDXTransferApproval.transfer_approved == None, + TransferApprovalHistory.operation_type + == TransferApprovalOperationType.APPROVE.value, + ), + 2, ), # Approve(operation completed, event synchronizing) ( IDXTransferApproval.transfer_approved == True, - 2 + 2, ), # Approve(transferred) ( - and_(IDXTransferApproval.cancelled == None, - TransferApprovalHistory.operation_type == TransferApprovalOperationType.CANCEL.value), - 3 + and_( + IDXTransferApproval.cancelled == None, + TransferApprovalHistory.operation_type + == TransferApprovalOperationType.CANCEL.value, + ), + 3, ), # Cancel(operation completed, event synchronizing) - ( - IDXTransferApproval.cancelled == True, - 3 - ), # Cancel(canceled) - else_=0 # ApplyFor(unapproved) - ).label("status") - ).outerjoin( + (IDXTransferApproval.cancelled == True, 3), # Cancel(canceled) + else_=0, # ApplyFor(unapproved) + ).label("status"), + ) + .outerjoin( TransferApprovalHistory, - and_(IDXTransferApproval.token_address == TransferApprovalHistory.token_address, - IDXTransferApproval.exchange_address == TransferApprovalHistory.exchange_address, - IDXTransferApproval.application_id == TransferApprovalHistory.application_id) - ).subquery() + and_( + IDXTransferApproval.token_address + == TransferApprovalHistory.token_address, + IDXTransferApproval.exchange_address + == TransferApprovalHistory.exchange_address, + IDXTransferApproval.application_id + == TransferApprovalHistory.application_id, + ), + ) + .subquery(), ) # Get transfer approval history - query = db.query(subquery, literal_column("status")). \ - filter(subquery.token_address == token_address) + query = db.query(subquery, literal_column("status")).filter( + subquery.token_address == token_address + ) total = query.count() # Search Filter @@ -2312,75 +2559,99 @@ def list_token_transfer_approval_history( else: issuer_cancelable = True - application_datetime_utc = timezone("UTC").localize(_transfer_approval.application_datetime) + application_datetime_utc = timezone("UTC").localize( + _transfer_approval.application_datetime + ) application_datetime = application_datetime_utc.astimezone(local_tz).isoformat() - application_blocktimestamp_utc = timezone("UTC").localize(_transfer_approval.application_blocktimestamp) - application_blocktimestamp = application_blocktimestamp_utc.astimezone(local_tz).isoformat() + application_blocktimestamp_utc = timezone("UTC").localize( + _transfer_approval.application_blocktimestamp + ) + application_blocktimestamp = application_blocktimestamp_utc.astimezone( + local_tz + ).isoformat() if _transfer_approval.approval_datetime is not None: - approval_datetime_utc = timezone("UTC").localize(_transfer_approval.approval_datetime) + approval_datetime_utc = timezone("UTC").localize( + _transfer_approval.approval_datetime + ) approval_datetime = approval_datetime_utc.astimezone(local_tz).isoformat() else: approval_datetime = None if _transfer_approval.approval_blocktimestamp is not None: - approval_blocktimestamp_utc = timezone("UTC").localize(_transfer_approval.approval_blocktimestamp) - approval_blocktimestamp = approval_blocktimestamp_utc.astimezone(local_tz).isoformat() + approval_blocktimestamp_utc = timezone("UTC").localize( + _transfer_approval.approval_blocktimestamp + ) + approval_blocktimestamp = approval_blocktimestamp_utc.astimezone( + local_tz + ).isoformat() else: approval_blocktimestamp = None - transfer_approval_history.append({ - "id": _transfer_approval.id, - "token_address": token_address, - "exchange_address": _transfer_approval.exchange_address, - "application_id": _transfer_approval.application_id, - "from_address": _transfer_approval.from_address, - "to_address": _transfer_approval.to_address, - "amount": _transfer_approval.amount, - "application_datetime": application_datetime, - "application_blocktimestamp": application_blocktimestamp, - "approval_datetime": approval_datetime, - "approval_blocktimestamp": approval_blocktimestamp, - "cancelled": cancelled, - "escrow_finished": escrow_finished, - "transfer_approved": transfer_approved, - "status": status, - "issuer_cancelable": issuer_cancelable - }) - - return json_response({ - "result_set": { - "count": count, - "offset": offset, - "limit": limit, - "total": total - }, - "transfer_approval_history": transfer_approval_history - }) + transfer_approval_history.append( + { + "id": _transfer_approval.id, + "token_address": token_address, + "exchange_address": _transfer_approval.exchange_address, + "application_id": _transfer_approval.application_id, + "from_address": _transfer_approval.from_address, + "to_address": _transfer_approval.to_address, + "amount": _transfer_approval.amount, + "application_datetime": application_datetime, + "application_blocktimestamp": application_blocktimestamp, + "approval_datetime": approval_datetime, + "approval_blocktimestamp": approval_blocktimestamp, + "cancelled": cancelled, + "escrow_finished": escrow_finished, + "transfer_approved": transfer_approved, + "status": status, + "issuer_cancelable": issuer_cancelable, + } + ) + + return json_response( + { + "result_set": { + "count": count, + "offset": offset, + "limit": limit, + "total": total, + }, + "transfer_approval_history": transfer_approval_history, + } + ) # POST: /share/transfer_approvals/{token_address}/{id} @router.post( "/transfer_approvals/{token_address}/{id}", - responses=get_routers_responses(422, 401, 404, AuthorizationError, InvalidParameterError, SendTransactionError, ContractRevertError) + responses=get_routers_responses( + 422, + 401, + 404, + AuthorizationError, + InvalidParameterError, + SendTransactionError, + ContractRevertError, + ), ) def update_transfer_approval( - request: Request, - token_address: str, - id: int, - data: UpdateTransferApprovalRequest, - issuer_address: str = Header(...), - eoa_password: Optional[str] = Header(None), - auth_token: Optional[str] = Header(None), - db: Session = Depends(db_session) + request: Request, + token_address: str, + id: int, + data: UpdateTransferApprovalRequest, + issuer_address: str = Header(...), + eoa_password: Optional[str] = Header(None), + auth_token: Optional[str] = Header(None), + db: Session = Depends(db_session), ): """Update on the status of a share transfer approval""" # Validate Headers validate_headers( issuer_address=(issuer_address, address_is_valid_address), - eoa_password=(eoa_password, eoa_password_is_encrypted_value) + eoa_password=(eoa_password, eoa_password_is_encrypted_value), ) # Authentication @@ -2389,32 +2660,35 @@ def update_transfer_approval( db=db, issuer_address=issuer_address, eoa_password=eoa_password, - auth_token=auth_token + auth_token=auth_token, ) # Get private key keyfile_json = _account.keyfile private_key = decode_keyfile_json( - raw_keyfile_json=keyfile_json, - password=decrypt_password.encode("utf-8") + raw_keyfile_json=keyfile_json, password=decrypt_password.encode("utf-8") ) # Get token - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_SHARE). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_SHARE) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: raise InvalidParameterError("this token is temporarily unavailable") # Get transfer approval history - _transfer_approval: IDXTransferApproval | None = db.query(IDXTransferApproval). \ - filter(IDXTransferApproval.id == id). \ - filter(IDXTransferApproval.token_address == token_address). \ - first() + _transfer_approval: IDXTransferApproval | None = ( + db.query(IDXTransferApproval) + .filter(IDXTransferApproval.id == id) + .filter(IDXTransferApproval.token_address == token_address) + .first() + ) if _transfer_approval is None: raise HTTPException(status_code=404, detail="transfer approval not found") @@ -2422,20 +2696,33 @@ def update_transfer_approval( raise InvalidParameterError("already approved") if _transfer_approval.cancelled is True: raise InvalidParameterError("canceled application") - if _transfer_approval.exchange_address != config.ZERO_ADDRESS and \ - _transfer_approval.escrow_finished is not True: + if ( + _transfer_approval.exchange_address != config.ZERO_ADDRESS + and _transfer_approval.escrow_finished is not True + ): raise InvalidParameterError("escrow has not been finished yet") - if data.operation_type == UpdateTransferApprovalOperationType.CANCEL and \ - _transfer_approval.exchange_address != config.ZERO_ADDRESS: + if ( + data.operation_type == UpdateTransferApprovalOperationType.CANCEL + and _transfer_approval.exchange_address != config.ZERO_ADDRESS + ): # Cancellation is possible only against approval of the transfer of a token contract. raise InvalidParameterError("application that cannot be canceled") - transfer_approval_op: TransferApprovalHistory | None = db.query(TransferApprovalHistory). \ - filter(TransferApprovalHistory.token_address == _transfer_approval.token_address). \ - filter(TransferApprovalHistory.exchange_address == _transfer_approval.exchange_address). \ - filter(TransferApprovalHistory.application_id == _transfer_approval.application_id). \ - filter(TransferApprovalHistory.operation_type == data.operation_type). \ - first() + transfer_approval_op: TransferApprovalHistory | None = ( + db.query(TransferApprovalHistory) + .filter( + TransferApprovalHistory.token_address == _transfer_approval.token_address + ) + .filter( + TransferApprovalHistory.exchange_address + == _transfer_approval.exchange_address + ) + .filter( + TransferApprovalHistory.application_id == _transfer_approval.application_id + ) + .filter(TransferApprovalHistory.operation_type == data.operation_type) + .first() + ) if transfer_approval_op is not None: raise InvalidParameterError("duplicate operation") @@ -2450,7 +2737,7 @@ def update_transfer_approval( if _transfer_approval.exchange_address == config.ZERO_ADDRESS: _data = { "application_id": _transfer_approval.application_id, - "data": now + "data": now, } try: _, tx_receipt = IbetShareContract(token_address).approve_transfer( @@ -2475,10 +2762,7 @@ def update_transfer_approval( # If cancel transfer is successful, approve_transfer error is raised. raise else: - _data = { - "escrow_id": _transfer_approval.application_id, - "data": now - } + _data = {"escrow_id": _transfer_approval.application_id, "data": now} escrow = IbetSecurityTokenEscrow(_transfer_approval.exchange_address) try: _, tx_receipt = escrow.approve_transfer( @@ -2492,10 +2776,7 @@ def update_transfer_approval( except Exception: raise SendTransactionError else: # CANCEL - _data = { - "application_id": _transfer_approval.application_id, - "data": now - } + _data = {"application_id": _transfer_approval.application_id, "data": now} try: _, tx_receipt = IbetShareContract(token_address).cancel_transfer( data=CancelTransferParams(**_data), @@ -2524,53 +2805,72 @@ def update_transfer_approval( @router.get( "/transfer_approvals/{token_address}/{id}", response_model=TransferApprovalTokenResponse, - responses=get_routers_responses(422, 404, InvalidParameterError) + responses=get_routers_responses(422, 404, InvalidParameterError), ) def retrieve_transfer_approval_history( - token_address: str, - id: int, - db: Session = Depends(db_session) + token_address: str, id: int, db: Session = Depends(db_session) ): """Retrieve share token transfer approval history""" # Get token - _token = db.query(Token). \ - filter(Token.type == TokenType.IBET_SHARE). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status != 2). \ - first() + _token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_SHARE) + .filter(Token.token_address == token_address) + .filter(Token.token_status != 2) + .first() + ) if _token is None: raise HTTPException(status_code=404, detail="token not found") if _token.token_status == 0: raise InvalidParameterError("this token is temporarily unavailable") # Get transfer approval history - _transfer_approval: IDXTransferApproval | None = db.query(IDXTransferApproval). \ - filter(IDXTransferApproval.id == id). \ - filter(IDXTransferApproval.token_address == token_address). \ - first() + _transfer_approval: IDXTransferApproval | None = ( + db.query(IDXTransferApproval) + .filter(IDXTransferApproval.id == id) + .filter(IDXTransferApproval.token_address == token_address) + .first() + ) if _transfer_approval is None: raise HTTPException(status_code=404, detail="transfer approval not found") - _transfer_approval_op: TransferApprovalHistory | None = db.query(TransferApprovalHistory). \ - filter(TransferApprovalHistory.token_address == _transfer_approval.token_address). \ - filter(TransferApprovalHistory.exchange_address == _transfer_approval.exchange_address). \ - filter(TransferApprovalHistory.application_id == _transfer_approval.application_id). \ - first() + _transfer_approval_op: TransferApprovalHistory | None = ( + db.query(TransferApprovalHistory) + .filter( + TransferApprovalHistory.token_address == _transfer_approval.token_address + ) + .filter( + TransferApprovalHistory.exchange_address + == _transfer_approval.exchange_address + ) + .filter( + TransferApprovalHistory.application_id == _transfer_approval.application_id + ) + .first() + ) status = 0 - if _transfer_approval.escrow_finished is True and \ - _transfer_approval.transfer_approved is not True and \ - _transfer_approval_op is None: + if ( + _transfer_approval.escrow_finished is True + and _transfer_approval.transfer_approved is not True + and _transfer_approval_op is None + ): status = 1 # EscrowFinish(escrow_finished) - elif _transfer_approval.transfer_approved is not True and \ - _transfer_approval_op is not None and \ - _transfer_approval_op.operation_type == TransferApprovalOperationType.APPROVE.value: + elif ( + _transfer_approval.transfer_approved is not True + and _transfer_approval_op is not None + and _transfer_approval_op.operation_type + == TransferApprovalOperationType.APPROVE.value + ): status = 2 # Approve(operation completed, event synchronizing) elif _transfer_approval.transfer_approved is True: status = 2 # Approve(transferred) - elif _transfer_approval.cancelled is not True and \ - _transfer_approval_op is not None and \ - _transfer_approval_op.operation_type == TransferApprovalOperationType.CANCEL.value: + elif ( + _transfer_approval.cancelled is not True + and _transfer_approval_op is not None + and _transfer_approval_op.operation_type + == TransferApprovalOperationType.CANCEL.value + ): status = 3 # Cancel(operation completed, event synchronizing) elif _transfer_approval.cancelled is True: status = 3 # Cancel(canceled) @@ -2595,21 +2895,33 @@ def retrieve_transfer_approval_history( else: issuer_cancelable = True - application_datetime_utc = timezone("UTC").localize(_transfer_approval.application_datetime) + application_datetime_utc = timezone("UTC").localize( + _transfer_approval.application_datetime + ) application_datetime = application_datetime_utc.astimezone(local_tz).isoformat() - application_blocktimestamp_utc = timezone("UTC").localize(_transfer_approval.application_blocktimestamp) - application_blocktimestamp = application_blocktimestamp_utc.astimezone(local_tz).isoformat() + application_blocktimestamp_utc = timezone("UTC").localize( + _transfer_approval.application_blocktimestamp + ) + application_blocktimestamp = application_blocktimestamp_utc.astimezone( + local_tz + ).isoformat() if _transfer_approval.approval_datetime is not None: - approval_datetime_utc = timezone("UTC").localize(_transfer_approval.approval_datetime) + approval_datetime_utc = timezone("UTC").localize( + _transfer_approval.approval_datetime + ) approval_datetime = approval_datetime_utc.astimezone(local_tz).isoformat() else: approval_datetime = None if _transfer_approval.approval_blocktimestamp is not None: - approval_blocktimestamp_utc = timezone("UTC").localize(_transfer_approval.approval_blocktimestamp) - approval_blocktimestamp = approval_blocktimestamp_utc.astimezone(local_tz).isoformat() + approval_blocktimestamp_utc = timezone("UTC").localize( + _transfer_approval.approval_blocktimestamp + ) + approval_blocktimestamp = approval_blocktimestamp_utc.astimezone( + local_tz + ).isoformat() else: approval_blocktimestamp = None @@ -2629,7 +2941,7 @@ def retrieve_transfer_approval_history( "escrow_finished": escrow_finished, "transfer_approved": transfer_approved, "status": status, - "issuer_cancelable": issuer_cancelable + "issuer_cancelable": issuer_cancelable, } return json_response(history) @@ -2639,21 +2951,24 @@ def retrieve_transfer_approval_history( @router.post( "/bulk_transfer", response_model=BulkTransferUploadIdResponse, - responses=get_routers_responses(422, AuthorizationError, InvalidParameterError, 401) + responses=get_routers_responses( + 422, AuthorizationError, InvalidParameterError, 401 + ), ) def bulk_transfer_ownership( - request: Request, - tokens: List[IbetShareTransfer], - issuer_address: str = Header(...), - eoa_password: Optional[str] = Header(None), - auth_token: Optional[str] = Header(None), - db: Session = Depends(db_session)): + request: Request, + tokens: List[IbetShareTransfer], + issuer_address: str = Header(...), + eoa_password: Optional[str] = Header(None), + auth_token: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Bulk transfer token ownership""" # Validate Headers validate_headers( issuer_address=(issuer_address, address_is_valid_address), - eoa_password=(eoa_password, eoa_password_is_encrypted_value) + eoa_password=(eoa_password, eoa_password_is_encrypted_value), ) if len(tokens) < 1: @@ -2665,21 +2980,25 @@ def bulk_transfer_ownership( db=db, issuer_address=issuer_address, eoa_password=eoa_password, - auth_token=auth_token + auth_token=auth_token, ) # Verify that the tokens are issued by the issuer_address for _token in tokens: - _issued_token = db.query(Token). \ - filter(Token.type == TokenType.IBET_SHARE). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_address == _token.token_address). \ - filter(Token.token_status != 2). \ - first() + _issued_token = ( + db.query(Token) + .filter(Token.type == TokenType.IBET_SHARE) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_address == _token.token_address) + .filter(Token.token_status != 2) + .first() + ) if _issued_token is None: raise InvalidParameterError(f"token not found: {_token.token_address}") if _issued_token.token_status == 0: - raise InvalidParameterError(f"this token is temporarily unavailable: {_token.token_address}") + raise InvalidParameterError( + f"this token is temporarily unavailable: {_token.token_address}" + ) # generate upload_id upload_id = uuid.uuid4() @@ -2707,20 +3026,18 @@ def bulk_transfer_ownership( db.commit() - return json_response({ - "upload_id": str(upload_id) - }) + return json_response({"upload_id": str(upload_id)}) # GET: /share/bulk_transfer @router.get( "/bulk_transfer", response_model=List[BulkTransferUploadResponse], - responses=get_routers_responses(422) + responses=get_routers_responses(422), ) def list_bulk_transfer_upload( - issuer_address: Optional[str] = Header(None), - db: Session = Depends(db_session)): + issuer_address: Optional[str] = Header(None), db: Session = Depends(db_session) +): """List bulk transfer uploads""" # Validate Headers @@ -2728,26 +3045,32 @@ def list_bulk_transfer_upload( # Get bulk transfer upload list if issuer_address is None: - _uploads = db.query(BulkTransferUpload). \ - filter(BulkTransferUpload.token_type == TokenType.IBET_SHARE). \ - order_by(BulkTransferUpload.issuer_address). \ - all() + _uploads = ( + db.query(BulkTransferUpload) + .filter(BulkTransferUpload.token_type == TokenType.IBET_SHARE) + .order_by(BulkTransferUpload.issuer_address) + .all() + ) else: - _uploads = db.query(BulkTransferUpload). \ - filter(BulkTransferUpload.issuer_address == issuer_address). \ - filter(BulkTransferUpload.token_type == TokenType.IBET_SHARE). \ - all() + _uploads = ( + db.query(BulkTransferUpload) + .filter(BulkTransferUpload.issuer_address == issuer_address) + .filter(BulkTransferUpload.token_type == TokenType.IBET_SHARE) + .all() + ) uploads = [] for _upload in _uploads: created_utc = timezone("UTC").localize(_upload.created) - uploads.append({ - "issuer_address": _upload.issuer_address, - "token_type": _upload.token_type, - "upload_id": _upload.upload_id, - "status": _upload.status, - "created": created_utc.astimezone(local_tz).isoformat() - }) + uploads.append( + { + "issuer_address": _upload.issuer_address, + "token_type": _upload.token_type, + "upload_id": _upload.upload_id, + "status": _upload.status, + "created": created_utc.astimezone(local_tz).isoformat(), + } + ) return json_response(uploads) @@ -2756,12 +3079,13 @@ def list_bulk_transfer_upload( @router.get( "/bulk_transfer/{upload_id}", response_model=List[BulkTransferResponse], - responses=get_routers_responses(422, 404) + responses=get_routers_responses(422, 404), ) def retrieve_bulk_transfer( - upload_id: str, - issuer_address: Optional[str] = Header(None), - db: Session = Depends(db_session)): + upload_id: str, + issuer_address: Optional[str] = Header(None), + db: Session = Depends(db_session), +): """Retrieve a bulk transfer upload""" # Validate Headers @@ -2769,30 +3093,36 @@ def retrieve_bulk_transfer( # Get bulk transfer upload list if issuer_address is None: - _bulk_transfers = db.query(BulkTransfer). \ - filter(BulkTransfer.upload_id == upload_id). \ - filter(BulkTransfer.token_type == TokenType.IBET_SHARE). \ - order_by(BulkTransfer.issuer_address). \ - all() + _bulk_transfers = ( + db.query(BulkTransfer) + .filter(BulkTransfer.upload_id == upload_id) + .filter(BulkTransfer.token_type == TokenType.IBET_SHARE) + .order_by(BulkTransfer.issuer_address) + .all() + ) else: - _bulk_transfers = db.query(BulkTransfer). \ - filter(BulkTransfer.issuer_address == issuer_address). \ - filter(BulkTransfer.upload_id == upload_id). \ - filter(BulkTransfer.token_type == TokenType.IBET_SHARE). \ - all() + _bulk_transfers = ( + db.query(BulkTransfer) + .filter(BulkTransfer.issuer_address == issuer_address) + .filter(BulkTransfer.upload_id == upload_id) + .filter(BulkTransfer.token_type == TokenType.IBET_SHARE) + .all() + ) bulk_transfers = [] for _bulk_transfer in _bulk_transfers: - bulk_transfers.append({ - "issuer_address": _bulk_transfer.issuer_address, - "token_type": _bulk_transfer.token_type, - "upload_id": _bulk_transfer.upload_id, - "token_address": _bulk_transfer.token_address, - "from_address": _bulk_transfer.from_address, - "to_address": _bulk_transfer.to_address, - "amount": _bulk_transfer.amount, - "status": _bulk_transfer.status - }) + bulk_transfers.append( + { + "issuer_address": _bulk_transfer.issuer_address, + "token_type": _bulk_transfer.token_type, + "upload_id": _bulk_transfer.upload_id, + "token_address": _bulk_transfer.token_address, + "from_address": _bulk_transfer.from_address, + "to_address": _bulk_transfer.to_address, + "amount": _bulk_transfer.amount, + "status": _bulk_transfer.status, + } + ) if len(bulk_transfers) < 1: raise HTTPException(status_code=404, detail="bulk transfer not found") diff --git a/app/routers/token_holders.py b/app/routers/token_holders.py index 78841952..d3dcbeb0 100644 --- a/app/routers/token_holders.py +++ b/app/routers/token_holders.py @@ -19,40 +19,23 @@ import uuid from typing import List, Optional, Type -from fastapi import ( - APIRouter, - Depends, - Header, - Path, - Query -) +from fastapi import APIRouter, Depends, Header, Path, Query from fastapi.exceptions import HTTPException +from sqlalchemy import asc, desc from sqlalchemy.orm import Session -from sqlalchemy import ( - asc, - desc -) from app.database import db_session +from app.exceptions import InvalidParameterError +from app.model.db import Token, TokenHolder, TokenHolderBatchStatus, TokenHoldersList from app.model.schema import ( CreateTokenHoldersListRequest, CreateTokenHoldersListResponse, + ListAllTokenHolderCollectionsResponse, RetrieveTokenHoldersListResponse, - ListAllTokenHolderCollectionsResponse ) -from app.utils.fastapi import json_response +from app.utils.check_utils import address_is_valid_address, validate_headers from app.utils.docs_utils import get_routers_responses -from app.utils.check_utils import ( - validate_headers, - address_is_valid_address -) -from app.model.db import ( - Token, - TokenHoldersList, - TokenHolderBatchStatus, - TokenHolder -) -from app.exceptions import InvalidParameterError +from app.utils.fastapi import json_response from app.utils.web3_utils import Web3Wrapper web3 = Web3Wrapper() @@ -119,10 +102,12 @@ def create_collection( ) if _same_combi_record: - return json_response({ - "status": _same_combi_record.batch_status, - "list_id": _same_combi_record.list_id, - }) + return json_response( + { + "status": _same_combi_record.batch_status, + "list_id": _same_combi_record.list_id, + } + ) _token_holders_list = TokenHoldersList() _token_holders_list.token_address = token_address @@ -133,17 +118,19 @@ def create_collection( db.add(_token_holders_list) db.commit() - return json_response({ - "status": _token_holders_list.batch_status, - "list_id": _token_holders_list.list_id, - }) + return json_response( + { + "status": _token_holders_list.batch_status, + "list_id": _token_holders_list.list_id, + } + ) # GET: /token/holders/{token_address}/collection @router.get( "/holders/{token_address}/collection", response_model=ListAllTokenHolderCollectionsResponse, - responses=get_routers_responses(422, 404, InvalidParameterError) + responses=get_routers_responses(422, 404, InvalidParameterError), ) def list_all_token_holders_collections( token_address: str = Path(...), @@ -152,7 +139,7 @@ def list_all_token_holders_collections( sort_order: int = Query(1, ge=0, le=1, description="0:asc, 1:desc (created)"), offset: Optional[int] = Query(None), limit: Optional[int] = Query(None), - db: Session = Depends(db_session) + db: Session = Depends(db_session), ): # Validate Headers validate_headers(issuer_address=(issuer_address, address_is_valid_address)) @@ -173,7 +160,9 @@ def list_all_token_holders_collections( if _token.token_status == 0: raise InvalidParameterError("this token is temporarily unavailable") - query = db.query(TokenHoldersList).filter(TokenHoldersList.token_address == token_address) + query = db.query(TokenHoldersList).filter( + TokenHoldersList.token_address == token_address + ) # Total total = query.count() @@ -205,7 +194,7 @@ def list_all_token_holders_collections( "token_address": _collection.token_address, "block_number": _collection.block_number, "list_id": _collection.list_id, - "status": _collection.batch_status + "status": _collection.batch_status, } ) @@ -214,9 +203,9 @@ def list_all_token_holders_collections( "count": count, "offset": offset, "limit": limit, - "total": total + "total": total, }, - "collections": token_holders_collections + "collections": token_holders_collections, } return json_response(resp) @@ -285,7 +274,9 @@ def retrieve_token_holders_list( ) token_holders = [_token_holder.json() for _token_holder in _token_holders] - return json_response({ - "status": _same_list_id_record.batch_status, - "holders": token_holders, - }) + return json_response( + { + "status": _same_list_id_record.batch_status, + "holders": token_holders, + } + ) diff --git a/app/utils/cache_utils.py b/app/utils/cache_utils.py index 97e4e6aa..52c73b79 100644 --- a/app/utils/cache_utils.py +++ b/app/utils/cache_utils.py @@ -16,20 +16,13 @@ SPDX-License-Identifier: Apache-2.0 """ +import inspect import os +import pickle import sys -import inspect -from typing import ( - Optional, - Any, - KeysView, - ValuesView, - ItemsView, - Iterator -) import threading -import pickle from multiprocessing.shared_memory import SharedMemory +from typing import Any, ItemsView, Iterator, KeysView, Optional, ValuesView from shared_memory_dict import SharedMemoryDict from shared_memory_dict.lock import lock @@ -60,13 +53,14 @@ class DictCache: @staticmethod def initialize(): - if "pytest" in sys.modules or \ - inspect.getfile(inspect.stack()[-1][0]).startswith("batch/") or \ - os.environ.get("SHARED_MEMORY_USE_LOCK") != "1": + if ( + "pytest" in sys.modules + or inspect.getfile(inspect.stack()[-1][0]).startswith("batch/") + or os.environ.get("SHARED_MEMORY_USE_LOCK") != "1" + ): DictCache.MEMORY_CACHE = True if DictCache.MEMORY_CACHE is False: - # NOTE: Create an SharedMemoryDict to share the current cache size between processes. DictCache.cache_sizes = SharedMemoryDict(name="cache_sizes", size=4096) @@ -80,21 +74,17 @@ def initialize(): DictCache.cache_sizes[k] = v["default_size"] shm_dict = SharedMemoryDict(name=k, size=v["default_size"]) else: - shm_dict = SharedMemoryDict(name=k, size=DictCache.cache_sizes[k]) + shm_dict = SharedMemoryDict( + name=k, size=DictCache.cache_sizes[k] + ) else: shm_dict = SharedMemoryDict(name=k, size=v["default_size"]) if is_first_init is True: shm_dict.clear() - DictCache.caches[k] = { - "data": shm_dict, - "lock": None - } + DictCache.caches[k] = {"data": shm_dict, "lock": None} else: for k in DictCache.USE_CACHE.keys(): - DictCache.caches[k] = { - "data": {}, - "lock": threading.Lock() - } + DictCache.caches[k] = {"data": {}, "lock": threading.Lock()} def __init__(self, name: str): _ = DictCache.USE_CACHE[name] # check name @@ -102,7 +92,10 @@ def __init__(self, name: str): self.cache = DictCache.caches[name] def get(self, key: str, default: Optional[Any] = None) -> Optional[Any]: - if DictCache.MEMORY_CACHE is False and DictCache.USE_CACHE[self.name]["is_extend_size"] is True: + if ( + DictCache.MEMORY_CACHE is False + and DictCache.USE_CACHE[self.name]["is_extend_size"] is True + ): self._extend_size_and_write() if key in self.cache["data"]: return self.cache["data"][key] @@ -110,17 +103,26 @@ def get(self, key: str, default: Optional[Any] = None) -> Optional[Any]: return default def keys(self) -> KeysView[Any]: - if DictCache.MEMORY_CACHE is False and DictCache.USE_CACHE[self.name]["is_extend_size"] is True: + if ( + DictCache.MEMORY_CACHE is False + and DictCache.USE_CACHE[self.name]["is_extend_size"] is True + ): self._extend_size_and_write() return self.cache["data"].keys() def values(self) -> ValuesView[Any]: - if DictCache.MEMORY_CACHE is False and DictCache.USE_CACHE[self.name]["is_extend_size"] is True: + if ( + DictCache.MEMORY_CACHE is False + and DictCache.USE_CACHE[self.name]["is_extend_size"] is True + ): self._extend_size_and_write() return self.cache["data"].values() def items(self) -> ItemsView: - if DictCache.MEMORY_CACHE is False and DictCache.USE_CACHE[self.name]["is_extend_size"] is True: + if ( + DictCache.MEMORY_CACHE is False + and DictCache.USE_CACHE[self.name]["is_extend_size"] is True + ): self._extend_size_and_write() return self.cache["data"].items() @@ -130,6 +132,7 @@ def pop(self, key: str, default: Optional[Any] = None) -> Optional[Any]: self._extend_size_and_write() return self.cache["data"].pop(key, default) # Lock with SharedMemoryDict else: + def _func(): return self.cache["data"].pop(key, default) @@ -142,13 +145,17 @@ def update(self, other=(), /, **kwargs) -> None: else: self.cache["data"].update(other, **kwargs) # Lock with SharedMemoryDict else: + def _func(): self.cache["data"].update(other, **kwargs) self._thread_safe(_func) def __getitem__(self, key: str) -> Any: - if DictCache.MEMORY_CACHE is False and DictCache.USE_CACHE[self.name]["is_extend_size"] is True: + if ( + DictCache.MEMORY_CACHE is False + and DictCache.USE_CACHE[self.name]["is_extend_size"] is True + ): self._extend_size_and_write() return self.cache["data"][key] @@ -159,13 +166,17 @@ def __setitem__(self, key: str, value: Any) -> None: else: self.cache["data"][key] = value # Lock with SharedMemoryDict else: + def _func(): self.cache["data"][key] = value self._thread_safe(_func) def __len__(self) -> int: - if DictCache.MEMORY_CACHE is False and DictCache.USE_CACHE[self.name]["is_extend_size"] is True: + if ( + DictCache.MEMORY_CACHE is False + and DictCache.USE_CACHE[self.name]["is_extend_size"] is True + ): self._extend_size_and_write() return len(self.cache["data"]) @@ -175,43 +186,65 @@ def __delitem__(self, key: str) -> None: self._extend_size_and_write() del self.cache["data"][key] # Lock with SharedMemoryDict else: + def _func(): del self.cache["data"][key] return self._thread_safe(_func) def __iter__(self) -> Iterator: - if DictCache.MEMORY_CACHE is False and DictCache.USE_CACHE[self.name]["is_extend_size"] is True: + if ( + DictCache.MEMORY_CACHE is False + and DictCache.USE_CACHE[self.name]["is_extend_size"] is True + ): self._extend_size_and_write() return iter(self.cache["data"]) def __reversed__(self): - if DictCache.MEMORY_CACHE is False and DictCache.USE_CACHE[self.name]["is_extend_size"] is True: + if ( + DictCache.MEMORY_CACHE is False + and DictCache.USE_CACHE[self.name]["is_extend_size"] is True + ): self._extend_size_and_write() return reversed(self.cache["data"]) def __contains__(self, key: str) -> bool: - if DictCache.MEMORY_CACHE is False and DictCache.USE_CACHE[self.name]["is_extend_size"] is True: + if ( + DictCache.MEMORY_CACHE is False + and DictCache.USE_CACHE[self.name]["is_extend_size"] is True + ): self._extend_size_and_write() return key in self.cache["data"] def __eq__(self, other: Any) -> bool: - if DictCache.MEMORY_CACHE is False and DictCache.USE_CACHE[self.name]["is_extend_size"] is True: + if ( + DictCache.MEMORY_CACHE is False + and DictCache.USE_CACHE[self.name]["is_extend_size"] is True + ): self._extend_size_and_write() return self.cache["data"] == other def __ne__(self, other: Any) -> bool: - if DictCache.MEMORY_CACHE is False and DictCache.USE_CACHE[self.name]["is_extend_size"] is True: + if ( + DictCache.MEMORY_CACHE is False + and DictCache.USE_CACHE[self.name]["is_extend_size"] is True + ): self._extend_size_and_write() return self.cache["data"] != other def __str__(self) -> str: - if DictCache.MEMORY_CACHE is False and DictCache.USE_CACHE[self.name]["is_extend_size"] is True: + if ( + DictCache.MEMORY_CACHE is False + and DictCache.USE_CACHE[self.name]["is_extend_size"] is True + ): self._extend_size_and_write() return str(self.cache["data"]) def __repr__(self) -> str: - if DictCache.MEMORY_CACHE is False and DictCache.USE_CACHE[self.name]["is_extend_size"] is True: + if ( + DictCache.MEMORY_CACHE is False + and DictCache.USE_CACHE[self.name]["is_extend_size"] is True + ): self._extend_size_and_write() return repr(self.cache["data"]) @@ -221,7 +254,9 @@ def _thread_safe(self, func): return result @lock - def _extend_size_and_write(self, *, key: str = None, value: Any = None, other=(), **kwargs): + def _extend_size_and_write( + self, *, key: str = None, value: Any = None, other=(), **kwargs + ): """ If the cache size becomes large due to updating by another process, reading or writing may fail, so extends the size when accessing the shared memory. @@ -267,7 +302,9 @@ def _extend_size_and_write(self, *, key: str = None, value: Any = None, other=() # NOTE: Re-create shared memory object. old_shared_memory.close() old_shared_memory.unlink() - new_shared_memory = SharedMemory(name=MEMORY_NAME.format(name=self.name), create=True, size=mod_size) + new_shared_memory = SharedMemory( + name=MEMORY_NAME.format(name=self.name), create=True, size=mod_size + ) self.cache["data"]._memory_block = new_shared_memory # NOTE: Save update data independent of @lock decorator.(Avoid deadlock) self.cache["data"]._save_memory(update_data) diff --git a/app/utils/check_utils.py b/app/utils/check_utils.py index 636f7f58..2bc21abf 100644 --- a/app/utils/check_utils.py +++ b/app/utils/check_utils.py @@ -17,30 +17,21 @@ SPDX-License-Identifier: Apache-2.0 """ import hashlib -from datetime import timedelta, datetime +from datetime import datetime, timedelta from typing import Optional from fastapi import Request from fastapi.exceptions import RequestValidationError -from pydantic.errors import MissingError from pydantic.error_wrappers import ErrorWrapper +from pydantic.errors import MissingError from sqlalchemy.orm import Session from web3 import Web3 -from config import ( - EOA_PASSWORD_CHECK_ENABLED, - E2EE_REQUEST_ENABLED -) from app.exceptions import AuthorizationError -from app.log import ( - auth_info, - auth_error -) +from app.log import auth_error, auth_info +from app.model.db import Account, AuthToken from app.utils.e2ee_utils import E2EEUtils -from app.model.db import ( - Account, - AuthToken -) +from config import E2EE_REQUEST_ENABLED, EOA_PASSWORD_CHECK_ENABLED def validate_headers(**kwargs): @@ -104,22 +95,28 @@ def check_value_is_encrypted(name, value): raise ValueError(f"{name} is not a Base64-encoded encrypted data") -def check_auth(request: Request, - db: Session, - issuer_address: str, - eoa_password: Optional[str] = None, - auth_token: Optional[str] = None): +def check_auth( + request: Request, + db: Session, + issuer_address: str, + eoa_password: Optional[str] = None, + auth_token: Optional[str] = None, +): # Check for existence of issuer account try: account, decrypted_eoa_password = check_account_for_auth(db, issuer_address) except AuthorizationError: auth_error(request, issuer_address, "issuer does not exist") - raise AuthorizationError("issuer does not exist, or password mismatch") from None + raise AuthorizationError( + "issuer does not exist, or password mismatch" + ) from None if EOA_PASSWORD_CHECK_ENABLED: if eoa_password is None and auth_token is None: auth_error(request, issuer_address, "password mismatch") - raise AuthorizationError("issuer does not exist, or password mismatch") from None + raise AuthorizationError( + "issuer does not exist, or password mismatch" + ) from None elif eoa_password is not None: # Check EOA password try: @@ -129,27 +126,27 @@ def check_auth(request: Request, ) except AuthorizationError: auth_error(request, issuer_address, "password mismatch") - raise AuthorizationError("issuer does not exist, or password mismatch") from None + raise AuthorizationError( + "issuer does not exist, or password mismatch" + ) from None elif auth_token is not None: # Check auth token try: check_token_for_auth( - db=db, - issuer_address=issuer_address, - auth_token=auth_token + db=db, issuer_address=issuer_address, auth_token=auth_token ) except AuthorizationError: auth_error(request, issuer_address, "password mismatch") - raise AuthorizationError("issuer does not exist, or password mismatch") from None + raise AuthorizationError( + "issuer does not exist, or password mismatch" + ) from None auth_info(request, issuer_address, "authentication succeed") return account, decrypted_eoa_password def check_account_for_auth(db: Session, issuer_address: str): - account = db.query(Account). \ - filter(Account.issuer_address == issuer_address). \ - first() + account = db.query(Account).filter(Account.issuer_address == issuer_address).first() if account is None: raise AuthorizationError decrypted_eoa_password = E2EEUtils.decrypt(account.eoa_password) @@ -167,15 +164,19 @@ def check_eoa_password_for_auth(checked_pwd: str, correct_pwd: str): def check_token_for_auth(db: Session, issuer_address: str, auth_token: str): - issuer_token: Optional[AuthToken] = db.query(AuthToken). \ - filter(AuthToken.issuer_address == issuer_address). \ - first() + issuer_token: Optional[AuthToken] = ( + db.query(AuthToken).filter(AuthToken.issuer_address == issuer_address).first() + ) if issuer_token is None: raise AuthorizationError else: hashed_token = hashlib.sha256(auth_token.encode()).hexdigest() if issuer_token.auth_token != hashed_token: raise AuthorizationError - elif issuer_token.valid_duration != 0 and \ - issuer_token.usage_start + timedelta(seconds=issuer_token.valid_duration) < datetime.utcnow(): + elif ( + issuer_token.valid_duration != 0 + and issuer_token.usage_start + + timedelta(seconds=issuer_token.valid_duration) + < datetime.utcnow() + ): raise AuthorizationError diff --git a/app/utils/contract_error_code.py b/app/utils/contract_error_code.py index 65365960..600fd6cf 100644 --- a/app/utils/contract_error_code.py +++ b/app/utils/contract_error_code.py @@ -38,7 +38,7 @@ def error_code_msg(code_str: str) -> Tuple[int, str]: 100101: "The address has not been registered.", 100102: "Message sender must be the token owner.", # IbetShare (11XXXX) - 110001: "Lock address is invalid.", # < v22.12 + 110001: "Lock address is invalid.", # < v22.12 110002: "Lock amount is greater than message sender balance.", 110101: "Unlock address is invalid.", # < v22.12 110102: "Unlock amount is greater than locked amount.", @@ -190,4 +190,4 @@ def error_code_msg(code_str: str) -> Tuple[int, str]: 610011: "Message sender is not E2E Message sender.", # FreezeLog (62XXXX) 620001: "Log is frozen.", - }.get(code, "") \ No newline at end of file + }.get(code, "") diff --git a/app/utils/contract_utils.py b/app/utils/contract_utils.py index 4d246f8b..c2bb7a6e 100644 --- a/app/utils/contract_utils.py +++ b/app/utils/contract_utils.py @@ -16,31 +16,27 @@ SPDX-License-Identifier: Apache-2.0 """ -from typing import Tuple, TypeVar, Type import json +from typing import Tuple, Type, TypeVar +from eth_utils import to_checksum_address +from sqlalchemy import create_engine +from sqlalchemy.exc import OperationalError +from sqlalchemy.orm import Session from web3 import contract from web3.contract import Contract from web3.exceptions import ( - TimeExhausted, - BadFunctionCallOutput, - ABIFunctionNotFound, ABIEventFunctionNotFound, - ContractLogicError + ABIFunctionNotFound, + BadFunctionCallOutput, + ContractLogicError, + TimeExhausted, ) -from eth_utils import to_checksum_address -from sqlalchemy import create_engine -from sqlalchemy.exc import OperationalError -from sqlalchemy.orm import Session -from config import ( - CHAIN_ID, - TX_GAS_LIMIT, - DATABASE_URL -) -from app.utils.web3_utils import Web3Wrapper -from app.exceptions import SendTransactionError, ContractRevertError +from app.exceptions import ContractRevertError, SendTransactionError from app.model.db import TransactionLock +from app.utils.web3_utils import Web3Wrapper +from config import CHAIN_ID, DATABASE_URL, TX_GAS_LIMIT web3 = Web3Wrapper() @@ -61,16 +57,15 @@ def get_contract_code(contract_name: str): contract_json["bytecode"] = None contract_json["deployedBytecode"] = None - return contract_json["abi"], \ - contract_json["bytecode"], \ - contract_json["deployedBytecode"] + return ( + contract_json["abi"], + contract_json["bytecode"], + contract_json["deployedBytecode"], + ) @staticmethod def deploy_contract( - contract_name: str, - args: list, - deployer: str, - private_key: str + contract_name: str, args: list, deployer: str, private_key: str ) -> Tuple[str, dict, str]: """Deploy contract @@ -99,13 +94,12 @@ def deploy_contract( "chainId": CHAIN_ID, "from": deployer, "gas": TX_GAS_LIMIT, - "gasPrice": 0 + "gasPrice": 0, } ) # Send transaction tx_hash, tx_receipt = ContractUtils.send_transaction( - transaction=tx, - private_key=private_key + transaction=tx, private_key=private_key ) except TimeExhausted as timeout_error: # NOTE: Time-out occurred because sending transaction stays in pending, etc. @@ -116,10 +110,10 @@ def deploy_contract( contract_address = None if tx_receipt is not None: # Check if contract address is registered from transaction receipt result. - if 'contractAddress' in tx_receipt.keys(): - contract_address = tx_receipt['contractAddress'] + if "contractAddress" in tx_receipt.keys(): + contract_address = tx_receipt["contractAddress"] - return contract_address, contract_json['abi'], tx_hash + return contract_address, contract_json["abi"], tx_hash @classmethod def get_contract(cls, contract_name: str, contract_address: str): @@ -135,17 +129,16 @@ def get_contract(cls, contract_name: str, contract_address: str): contract_file = f"contracts/{contract_name}.json" contract_json = json.load(open(contract_file, "r")) - contract_factory = web3.eth.contract(abi=contract_json['abi']) + contract_factory = web3.eth.contract(abi=contract_json["abi"]) cls.factory_map[contract_name] = contract_factory return contract_factory(address=to_checksum_address(contract_address)) T = TypeVar("T") @staticmethod - def call_function(contract: contract, - function_name: str, - args: tuple, - default_returns: T = None) -> T: + def call_function( + contract: contract, function_name: str, args: tuple, default_returns: T = None + ) -> T: """Call contract function :param contract: Contract @@ -157,7 +150,11 @@ def call_function(contract: contract, try: _function = getattr(contract.functions, function_name) result = _function(*args).call() - except (BadFunctionCallOutput, ABIFunctionNotFound, ContractLogicError) as web3_exception: + except ( + BadFunctionCallOutput, + ABIFunctionNotFound, + ContractLogicError, + ) as web3_exception: if default_returns is not None: return default_returns else: @@ -176,7 +173,7 @@ def send_transaction(transaction: dict, private_key: str): DB_URI, connect_args={"options": "-c lock_timeout=10000"}, echo=False, - pool_pre_ping=True + pool_pre_ping=True, ) local_session = Session(autocommit=False, autoflush=True, bind=db_engine) @@ -184,11 +181,13 @@ def send_transaction(transaction: dict, private_key: str): # 10-sec timeout # Lock record try: - _tm = local_session.query(TransactionLock). \ - filter(TransactionLock.tx_from == _tx_from). \ - populate_existing(). \ - with_for_update(). \ - first() + _tm = ( + local_session.query(TransactionLock) + .filter(TransactionLock.tx_from == _tx_from) + .populate_existing() + .with_for_update() + .first() + ) except OperationalError as op_err: local_session.rollback() local_session.close() @@ -199,14 +198,12 @@ def send_transaction(transaction: dict, private_key: str): nonce = web3.eth.get_transaction_count(_tx_from) transaction["nonce"] = nonce signed_tx = web3.eth.account.sign_transaction( - transaction_dict=transaction, - private_key=private_key + transaction_dict=transaction, private_key=private_key ) # Send Transaction tx_hash = web3.eth.send_raw_transaction(signed_tx.rawTransaction.hex()) tx_receipt = web3.eth.wait_for_transaction_receipt( - transaction_hash=tx_hash, - timeout=10 + transaction_hash=tx_hash, timeout=10 ) if tx_receipt["status"] == 0: # inspect reason of transaction fail @@ -259,11 +256,13 @@ def get_block_by_transaction_hash(tx_hash: str): return block @staticmethod - def get_event_logs(contract: contract, - event: str, - block_from: int = None, - block_to: int = None, - argument_filters: dict = None): + def get_event_logs( + contract: contract, + event: str, + block_from: int = None, + block_to: int = None, + argument_filters: dict = None, + ): """Get contract event logs :param contract: Contract @@ -277,7 +276,7 @@ def get_event_logs(contract: contract, result = _event.getLogs( fromBlock=block_from, toBlock=block_to, - argument_filters=argument_filters + argument_filters=argument_filters, ) except ABIEventFunctionNotFound: return [] diff --git a/app/utils/docs_utils.py b/app/utils/docs_utils.py index 76f6d1ec..e3b3caf8 100644 --- a/app/utils/docs_utils.py +++ b/app/utils/docs_utils.py @@ -16,23 +16,18 @@ SPDX-License-Identifier: Apache-2.0 """ -from typing import ( - List, - Dict, - Union, - Any -) +from typing import Any, Dict, List, Union -from pydantic import BaseModel -from fastapi.openapi.utils import get_openapi from fastapi.exceptions import RequestValidationError +from fastapi.openapi.utils import get_openapi +from pydantic import BaseModel from app.exceptions import ( + AuthorizationError, + ContractRevertError, InvalidParameterError, SendTransactionError, - AuthorizationError, ServiceUnavailableError, - ContractRevertError ) @@ -47,7 +42,11 @@ class Config: def schema_extra(schema: Dict[str, Any], _) -> None: properties = schema["properties"] properties["code"]["examples"] = [0, 1, 2, 100001] - properties["title"]["examples"] = ["InvalidParameterError", "SendTransactionError", "ContractRevertError"] + properties["title"]["examples"] = [ + "InvalidParameterError", + "SendTransactionError", + "ContractRevertError", + ] class Error400Model(BaseModel): @@ -61,7 +60,7 @@ def schema_extra(schema: Dict[str, Any], _) -> None: properties["detail"]["examples"] = [ "this token is temporarily unavailable", "failed to register token address token list", - "The address has already been registered." + "The address has already been registered.", ] @@ -152,28 +151,13 @@ class Error503Model(BaseModel): DEFAULT_RESPONSE = { 400: { "description": "Invalid Parameter Error / Send Transaction Error / Contract Revert Error", - "model": Error400Model - }, - 401: { - "description": "Authorization Error", - "model": Error401Model - }, - 404: { - "description": "Not Found Error", - "model": Error404Model + "model": Error400Model, }, - 405: { - "description": "Method Not Allowed", - "model": Error405Model - }, - 422: { - "description": "Validation Error", - "model": Error422Model - }, - 503: { - "description": "Service Unavailable Error", - "model": Error503Model - } + 401: {"description": "Authorization Error", "model": Error401Model}, + 404: {"description": "Not Found Error", "model": Error404Model}, + 405: {"description": "Method Not Allowed", "model": Error405Model}, + 422: {"description": "Validation Error", "model": Error422Model}, + 503: {"description": "Service Unavailable Error", "model": Error503Model}, } @@ -224,7 +208,6 @@ def _get(src: dict, *keys): if paths is not None: for path_info in paths.values(): for router in path_info.values(): - # Remove Default Validation Error Response Structure # NOTE: # HTTPValidationError is automatically added to APIs docs that have path, header, query, @@ -233,7 +216,9 @@ def _get(src: dict, *keys): # and some APIs do not generate a Validation Error(API with no-required string parameter only, etc). resp_422 = _get(router, "responses", "422") if resp_422 is not None: - ref = _get(resp_422, "content", "application/json", "schema", "$ref") + ref = _get( + resp_422, "content", "application/json", "schema", "$ref" + ) if ref == "#/components/schemas/HTTPValidationError": router["responses"].pop("422") diff --git a/app/utils/e2ee_utils.py b/app/utils/e2ee_utils.py index 2d829932..6c47a714 100644 --- a/app/utils/e2ee_utils.py +++ b/app/utils/e2ee_utils.py @@ -18,22 +18,19 @@ """ import base64 import binascii -from datetime import ( - datetime, - timedelta -) +from datetime import datetime, timedelta import boto3 from Crypto.Cipher import PKCS1_OAEP from Crypto.PublicKey import RSA +from app.utils.cache_utils import DictCache from config import ( - E2EE_RSA_RESOURCE_MODE, - E2EE_RSA_RESOURCE, + AWS_REGION_NAME, E2EE_RSA_PASSPHRASE, - AWS_REGION_NAME + E2EE_RSA_RESOURCE, + E2EE_RSA_RESOURCE_MODE, ) -from app.utils.cache_utils import DictCache class E2EEUtils: @@ -57,7 +54,9 @@ def encrypt(data: str): if crypto_data.get("public_key") is None: return data - rsa_key = RSA.importKey(crypto_data.get("public_key"), passphrase=E2EE_RSA_PASSPHRASE) + rsa_key = RSA.importKey( + crypto_data.get("public_key"), passphrase=E2EE_RSA_PASSPHRASE + ) cipher = PKCS1_OAEP.new(rsa_key) encrypt_data = cipher.encrypt(data.encode("utf-8")) base64_data = base64.encodebytes(encrypt_data) @@ -74,7 +73,9 @@ def decrypt(base64_encrypt_data: str): if crypto_data.get("private_key") is None: return base64_encrypt_data - rsa_key = RSA.importKey(crypto_data.get("private_key"), passphrase=E2EE_RSA_PASSPHRASE) + rsa_key = RSA.importKey( + crypto_data.get("private_key"), passphrase=E2EE_RSA_PASSPHRASE + ) cipher = PKCS1_OAEP.new(rsa_key) try: @@ -105,14 +106,15 @@ def get_key(): @staticmethod def __get_crypto_data() -> DictCache: - if E2EEUtils.cache.get("expiration_datetime") is None: - E2EEUtils.cache.update(**{ - "private_key": None, - "public_key": None, - "encrypted_length": None, - "expiration_datetime": datetime.min - }) + E2EEUtils.cache.update( + **{ + "private_key": None, + "public_key": None, + "encrypted_length": None, + "expiration_datetime": datetime.min, + } + ) # Use Cache if E2EEUtils.cache.get("expiration_datetime") > datetime.utcnow(): @@ -125,8 +127,7 @@ def __get_crypto_data() -> DictCache: private_key = f.read() elif E2EE_RSA_RESOURCE_MODE == 1: secrets_manager = boto3.client( - service_name="secretsmanager", - region_name=AWS_REGION_NAME + service_name="secretsmanager", region_name=AWS_REGION_NAME ) result = secrets_manager.get_secret_value(SecretId=E2EE_RSA_RESOURCE) private_key = result.get("SecretString") @@ -138,14 +139,16 @@ def __get_crypto_data() -> DictCache: # Calculate Encrypted Length cipher = PKCS1_OAEP.new(rsa_key) - encrypted_length = len(cipher.encrypt(b'')) + encrypted_length = len(cipher.encrypt(b"")) # Update Cache(expiration for 1 hour) - E2EEUtils.cache.update(**{ - "private_key": private_key, - "public_key": public_key, - "encrypted_length": encrypted_length, - "expiration_datetime": datetime.utcnow() + timedelta(hours=1) - }) + E2EEUtils.cache.update( + **{ + "private_key": private_key, + "public_key": public_key, + "encrypted_length": encrypted_length, + "expiration_datetime": datetime.utcnow() + timedelta(hours=1), + } + ) return E2EEUtils.cache diff --git a/app/utils/fastapi.py b/app/utils/fastapi.py index abbac12b..c022f261 100644 --- a/app/utils/fastapi.py +++ b/app/utils/fastapi.py @@ -11,10 +11,11 @@ limitations under the License. SPDX-License-Identifier: Apache-2.0 """ -from fastapi.responses import ORJSONResponse -from typing import Any import decimal +from typing import Any + import orjson +from fastapi.responses import ORJSONResponse from config import RESPONSE_VALIDATION_MODE @@ -24,12 +25,15 @@ def decimal_default(obj): return float(obj) raise TypeError + class CustomORJSONResponse(ORJSONResponse): media_type = "application/json" def render(self, content: Any) -> bytes: return orjson.dumps( - content, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SERIALIZE_NUMPY, default=decimal_default + content, + option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SERIALIZE_NUMPY, + default=decimal_default, ) diff --git a/app/utils/ledger_utils.py b/app/utils/ledger_utils.py index d111ef2d..fcf4f1c9 100644 --- a/app/utils/ledger_utils.py +++ b/app/utils/ledger_utils.py @@ -22,55 +22,65 @@ import pytz from sqlalchemy.orm import Session -from config import TZ from app.model.blockchain import ( IbetShareContract, IbetStraightBondContract, - PersonalInfoContract + PersonalInfoContract, ) from app.model.db import ( - Token, - TokenType, UTXO, IDXPersonalInfo, Ledger, LedgerDetailsData, - LedgerTemplate, - LedgerDetailsTemplate, LedgerDetailsDataType, + LedgerDetailsTemplate, + LedgerTemplate, Notification, - NotificationType + NotificationType, + Token, + TokenType, ) +from config import TZ local_tz = pytz.timezone(TZ) utc_tz = pytz.timezone("UTC") def create_ledger(token_address: str, db: Session): - _token = db.query(Token). \ - filter(Token.token_address == token_address). \ - filter(Token.token_status == 1). \ - first() - if _token.type != TokenType.IBET_SHARE.value and _token.type != TokenType.IBET_STRAIGHT_BOND.value: + _token = ( + db.query(Token) + .filter(Token.token_address == token_address) + .filter(Token.token_status == 1) + .first() + ) + if ( + _token.type != TokenType.IBET_SHARE.value + and _token.type != TokenType.IBET_STRAIGHT_BOND.value + ): return - _template = db.query(LedgerTemplate). \ - filter(LedgerTemplate.token_address == token_address). \ - first() + _template = ( + db.query(LedgerTemplate) + .filter(LedgerTemplate.token_address == token_address) + .first() + ) if _template is None: return # Get ledger details - _details_list = db.query(LedgerDetailsTemplate). \ - filter(LedgerDetailsTemplate.token_address == token_address). \ - order_by(LedgerDetailsTemplate.id). \ - all() + _details_list = ( + db.query(LedgerDetailsTemplate) + .filter(LedgerDetailsTemplate.token_address == token_address) + .order_by(LedgerDetailsTemplate.id) + .all() + ) ledger_details = [] for _details in _details_list: # Get ledger details data - data_list = __get_details_data_list(token_address, _token.type, _details.data_type, - _details.data_source, db) + data_list = __get_details_data_list( + token_address, _token.type, _details.data_type, _details.data_source, db + ) # NOTE: Merge with template with ledger GET API details = { @@ -81,7 +91,9 @@ def create_ledger(token_address: str, db: Session): } ledger_details.append(details) - created_ymd = utc_tz.localize(datetime.utcnow()).astimezone(local_tz).strftime("%Y/%m/%d") + created_ymd = ( + utc_tz.localize(datetime.utcnow()).astimezone(local_tz).strftime("%Y/%m/%d") + ) # NOTE: Merge with template with ledger GET API ledger = { "created": created_ymd, @@ -102,7 +114,7 @@ def create_ledger(token_address: str, db: Session): # Although autoflush is enabled, there is no operation invoking flush. # Execute flush here to get ledger id which is auto incremented. db.flush() - + # Register Notification to the DB # NOTE: DB commit is executed by the caller _notification = Notification() @@ -114,38 +126,46 @@ def create_ledger(token_address: str, db: Session): _notification.metainfo = { "token_address": token_address, "token_type": _token.type, - "ledger_id": _ledger.id + "ledger_id": _ledger.id, } db.add(_notification) -def __get_details_data_list(token_address: str, token_type: str, data_type: str, data_source: str, db: Session): +def __get_details_data_list( + token_address: str, token_type: str, data_type: str, data_source: str, db: Session +): data_list = [] if data_type == LedgerDetailsDataType.DB.value: data_list = [] # Get Ledger Details Data from DB - _details_data_list = db.query(LedgerDetailsData). \ - filter(LedgerDetailsData.token_address == token_address). \ - filter(LedgerDetailsData.data_id == data_source). \ - order_by(LedgerDetailsData.id). \ - all() + _details_data_list = ( + db.query(LedgerDetailsData) + .filter(LedgerDetailsData.token_address == token_address) + .filter(LedgerDetailsData.data_id == data_source) + .order_by(LedgerDetailsData.id) + .all() + ) for _details_data in _details_data_list: - data_list.append({ - "account_address": None, - "name": _details_data.name, - "address": _details_data.address, - "amount": _details_data.amount, - "price": _details_data.price, - "balance": _details_data.balance, - "acquisition_date": _details_data.acquisition_date, - }) + data_list.append( + { + "account_address": None, + "name": _details_data.name, + "address": _details_data.address, + "amount": _details_data.amount, + "price": _details_data.price, + "balance": _details_data.balance, + "acquisition_date": _details_data.acquisition_date, + } + ) elif data_type == LedgerDetailsDataType.IBET_FIN.value: data_list = __get_details_data_list_from_ibetfin(token_address, token_type, db) return data_list -def __get_details_data_list_from_ibetfin(token_address: str, token_type: str, db: Session): +def __get_details_data_list_from_ibetfin( + token_address: str, token_type: str, db: Session +): if token_type == TokenType.IBET_SHARE.value: token_contract = IbetShareContract(token_address).get() price = token_contract.principal_value @@ -157,15 +177,17 @@ def __get_details_data_list_from_ibetfin(token_address: str, token_type: str, db personal_info_contract = PersonalInfoContract( db, issuer_address, - contract_address=token_contract.personal_info_contract_address + contract_address=token_contract.personal_info_contract_address, ) # Get token holders from UTXO - _utxo_list = db.query(UTXO). \ - filter(UTXO.token_address == token_contract.token_address). \ - filter(UTXO.amount > 0). \ - order_by(UTXO.account_address, UTXO.block_timestamp). \ - all() + _utxo_list = ( + db.query(UTXO) + .filter(UTXO.token_address == token_contract.token_address) + .filter(UTXO.amount > 0) + .order_by(UTXO.account_address, UTXO.block_timestamp) + .all() + ) # NOTE: UTXO grouping # account_address @@ -173,11 +195,13 @@ def __get_details_data_list_from_ibetfin(token_address: str, token_type: str, db # - sum(amount) utxo_grouped = {} for _utxo in _utxo_list: - date_ymd = utc_tz.localize(_utxo.block_timestamp).astimezone(local_tz).strftime("%Y/%m/%d") + date_ymd = ( + utc_tz.localize(_utxo.block_timestamp) + .astimezone(local_tz) + .strftime("%Y/%m/%d") + ) if _utxo.account_address not in utxo_grouped: - utxo_grouped[_utxo.account_address] = { - date_ymd: _utxo.amount - } + utxo_grouped[_utxo.account_address] = {date_ymd: _utxo.amount} else: if date_ymd not in utxo_grouped[_utxo.account_address]: utxo_grouped[_utxo.account_address][date_ymd] = _utxo.amount @@ -198,7 +222,9 @@ def __get_details_data_list_from_ibetfin(token_address: str, token_type: str, db } # Update PersonalInfo - personal_info = __get_personal_info(account_address, issuer_address, personal_info_contract, db) + personal_info = __get_personal_info( + account_address, issuer_address, personal_info_contract, db + ) details_data["name"] = personal_info.get("name", None) details_data["address"] = personal_info.get("address", None) @@ -207,15 +233,23 @@ def __get_details_data_list_from_ibetfin(token_address: str, token_type: str, db return data_list -def __get_personal_info(account_address: str, issuer_address: str, personal_info_contract: PersonalInfoContract, - db: Session): - _idx_personal_info = db.query(IDXPersonalInfo). \ - filter(IDXPersonalInfo.account_address == account_address). \ - filter(IDXPersonalInfo.issuer_address == issuer_address). \ - first() +def __get_personal_info( + account_address: str, + issuer_address: str, + personal_info_contract: PersonalInfoContract, + db: Session, +): + _idx_personal_info = ( + db.query(IDXPersonalInfo) + .filter(IDXPersonalInfo.account_address == account_address) + .filter(IDXPersonalInfo.issuer_address == issuer_address) + .first() + ) if _idx_personal_info is None: # Get PersonalInfo to Contract - personal_info = personal_info_contract.get_info(account_address, default_value=None) + personal_info = personal_info_contract.get_info( + account_address, default_value=None + ) else: personal_info = _idx_personal_info.personal_info diff --git a/app/utils/web3_utils.py b/app/utils/web3_utils.py index 3f541a56..dbbc5a9e 100644 --- a/app/utils/web3_utils.py +++ b/app/utils/web3_utils.py @@ -18,40 +18,33 @@ """ import sys import threading -from typing import Any import time from json.decoder import JSONDecodeError +from typing import Any +from eth_typing import URI +from requests.exceptions import ConnectionError, HTTPError from sqlalchemy import create_engine from sqlalchemy.orm import Session from web3 import Web3 from web3.middleware import geth_poa_middleware -from web3.types import ( - RPCEndpoint, - RPCResponse -) -from eth_typing import URI -from requests.exceptions import ( - ConnectionError, - HTTPError -) +from web3.types import RPCEndpoint, RPCResponse +from app.exceptions import ServiceUnavailableError +from app.model.db import Node from config import ( - WEB3_HTTP_PROVIDER, DATABASE_URL, DB_ECHO, + WEB3_HTTP_PROVIDER, WEB3_REQUEST_RETRY_COUNT, - WEB3_REQUEST_WAIT_TIME + WEB3_REQUEST_WAIT_TIME, ) -from app.model.db import Node -from app.exceptions import ServiceUnavailableError engine = create_engine(DATABASE_URL, echo=DB_ECHO, pool_pre_ping=True) thread_local = threading.local() class Web3Wrapper: - def __init__(self): if "pytest" not in sys.modules: FailOverHTTPProvider.set_fail_over_mode(True) @@ -90,7 +83,6 @@ def _get_web3() -> Web3: class FailOverHTTPProvider(Web3.HTTPProvider): - fail_over_mode = False # If False, use only the default(primary) provider def __init__(self, *args, **kwargs): @@ -110,17 +102,21 @@ def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse: counter = 0 while counter <= WEB3_REQUEST_RETRY_COUNT: # Switch alive node - _node = db_session.query(Node). \ - filter(Node.is_synced == True). \ - order_by(Node.priority). \ - order_by(Node.id). \ - first() + _node = ( + db_session.query(Node) + .filter(Node.is_synced == True) + .order_by(Node.priority) + .order_by(Node.id) + .first() + ) if _node is None: counter += 1 if counter <= WEB3_REQUEST_RETRY_COUNT: time.sleep(WEB3_REQUEST_WAIT_TIME) continue - raise ServiceUnavailableError("Block synchronization is down") + raise ServiceUnavailableError( + "Block synchronization is down" + ) self.endpoint_uri = URI(_node.endpoint_uri) try: return super().make_request(method, params) @@ -132,7 +128,9 @@ def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse: if counter <= WEB3_REQUEST_RETRY_COUNT: time.sleep(WEB3_REQUEST_WAIT_TIME) continue - raise ServiceUnavailableError("Block synchronization is down") + raise ServiceUnavailableError( + "Block synchronization is down" + ) else: # Use default provider self.endpoint_uri = URI(WEB3_HTTP_PROVIDER) return super().make_request(method, params) diff --git a/batch/batch_log.py b/batch/batch_log.py index 9441a6b8..afd8fb54 100644 --- a/batch/batch_log.py +++ b/batch/batch_log.py @@ -17,15 +17,17 @@ SPDX-License-Identifier: Apache-2.0 """ -import sys import logging +import sys def get_logger(process_name: str = None): LOG = logging.getLogger("background") LOG.propagate = False - LOG_FORMAT = f"[%(asctime)s] [{process_name}] [%(process)d] [%(levelname)s] %(message)s" + LOG_FORMAT = ( + f"[%(asctime)s] [{process_name}] [%(process)d] [%(levelname)s] %(message)s" + ) TIMESTAMP_FORMAT = "%Y-%m-%d %H:%M:%S %z" stream_handler = logging.StreamHandler(sys.stdout) diff --git a/batch/indexer_block_tx_data.py b/batch/indexer_block_tx_data.py index 46effed4..3a2cf326 100644 --- a/batch/indexer_block_tx_data.py +++ b/batch/indexer_block_tx_data.py @@ -25,26 +25,17 @@ from sqlalchemy import create_engine from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.orm import Session -from web3.types import ( - BlockData, - TxData -) +from web3.types import BlockData, TxData path = os.path.join(os.path.dirname(__file__), "../") sys.path.append(path) -from config import ( - DATABASE_URL, - CHAIN_ID -) +import batch_log + from app.exceptions import ServiceUnavailableError -from app.model.db import ( - IDXBlockData, - IDXBlockDataBlockNumber, - IDXTxData -) +from app.model.db import IDXBlockData, IDXBlockDataBlockNumber, IDXTxData from app.utils.web3_utils import Web3Wrapper -import batch_log +from config import CHAIN_ID, DATABASE_URL process_name = "INDEXER-BLOCK_TX_DATA" LOG = batch_log.get_logger(process_name=process_name) @@ -72,7 +63,9 @@ def process(self): LOG.info("syncing from={}, to={}".format(from_block, latest_block)) for block_number in range(from_block, latest_block + 1): - block_data: BlockData = web3.eth.get_block(block_number, full_transactions=True) + block_data: BlockData = web3.eth.get_block( + block_number, full_transactions=True + ) # Synchronize block data block_model = IDXBlockData() @@ -88,7 +81,9 @@ def process(self): block_model.gas_limit = block_data.get("gasLimit") block_model.gas_used = block_data.get("gasUsed") block_model.timestamp = block_data.get("timestamp") - block_model.proof_of_authority_data = block_data.get("proofOfAuthorityData").hex() + block_model.proof_of_authority_data = block_data.get( + "proofOfAuthorityData" + ).hex() block_model.mix_hash = block_data.get("mixHash").hex() block_model.nonce = block_data.get("nonce").hex() block_model.hash = block_data.get("hash").hex() @@ -104,7 +99,11 @@ def process(self): tx_model.block_number = transaction.get("blockNumber") tx_model.transaction_index = transaction.get("transactionIndex") tx_model.from_address = to_checksum_address(transaction.get("from")) - tx_model.to_address = to_checksum_address(transaction.get("to")) if transaction.get("to") else None + tx_model.to_address = ( + to_checksum_address(transaction.get("to")) + if transaction.get("to") + else None + ) tx_model.input = transaction.get("input") tx_model.gas = transaction.get("gas") tx_model.gas_price = transaction.get("gasPrice") @@ -130,9 +129,9 @@ def process(self): @staticmethod def __get_indexed_block_number(db_session: Session): indexed_block_number = ( - db_session.query(IDXBlockDataBlockNumber). - filter(IDXBlockDataBlockNumber.chain_id == str(CHAIN_ID)). - first() + db_session.query(IDXBlockDataBlockNumber) + .filter(IDXBlockDataBlockNumber.chain_id == str(CHAIN_ID)) + .first() ) if indexed_block_number is None: return -1 diff --git a/batch/indexer_e2e_messaging.py b/batch/indexer_e2e_messaging.py index 7b27966a..e6b18079 100644 --- a/batch/indexer_e2e_messaging.py +++ b/batch/indexer_e2e_messaging.py @@ -23,39 +23,34 @@ import time from datetime import datetime -from Crypto.Cipher import ( - AES, - PKCS1_OAEP -) +from Crypto.Cipher import AES, PKCS1_OAEP from Crypto.PublicKey import RSA from Crypto.Util.Padding import unpad -from sqlalchemy import ( - create_engine, - desc -) -from sqlalchemy.orm import Session +from sqlalchemy import create_engine, desc from sqlalchemy.exc import SQLAlchemyError +from sqlalchemy.orm import Session path = os.path.join(os.path.dirname(__file__), "../") sys.path.append(path) -from config import ( - INDEXER_SYNC_INTERVAL, - DATABASE_URL, - E2E_MESSAGING_CONTRACT_ADDRESS, - INDEXER_BLOCK_LOT_MAX_SIZE -) +import batch_log + +from app.exceptions import ServiceUnavailableError from app.model.db import ( + E2EMessagingAccount, + E2EMessagingAccountRsaKey, IDXE2EMessaging, IDXE2EMessagingBlockNumber, - E2EMessagingAccount, - E2EMessagingAccountRsaKey ) from app.utils.contract_utils import ContractUtils from app.utils.e2ee_utils import E2EEUtils from app.utils.web3_utils import Web3Wrapper -from app.exceptions import ServiceUnavailableError -import batch_log +from config import ( + DATABASE_URL, + E2E_MESSAGING_CONTRACT_ADDRESS, + INDEXER_BLOCK_LOT_MAX_SIZE, + INDEXER_SYNC_INTERVAL, +) process_name = "INDEXER-E2E-Messaging" LOG = batch_log.get_logger(process_name=process_name) @@ -84,7 +79,7 @@ class Processor: def __init__(self): self.e2e_messaging_contract = ContractUtils.get_contract( contract_name="E2EMessaging", - contract_address=E2E_MESSAGING_CONTRACT_ADDRESS + contract_address=E2E_MESSAGING_CONTRACT_ADDRESS, ) def process(self): @@ -92,7 +87,9 @@ def process(self): try: # Get from_block_number and to_block_number for contract event filter latest_block = web3.eth.block_number - _from_block = self.__get_idx_e2e_messaging_block_number(db_session=db_session) + _from_block = self.__get_idx_e2e_messaging_block_number( + db_session=db_session + ) _to_block = _from_block + INDEXER_BLOCK_LOT_MAX_SIZE # Skip processing if the latest block is not counted up @@ -114,18 +111,17 @@ def process(self): self.__sync_all( db_session=db_session, block_from=_from_block + 1, - block_to=latest_block + block_to=latest_block, ) else: self.__sync_all( db_session=db_session, block_from=_from_block + 1, - block_to=latest_block + block_to=latest_block, ) self.__set_idx_e2e_messaging_block_number( - db_session=db_session, - block_number=latest_block + db_session=db_session, block_number=latest_block ) db_session.commit() finally: @@ -133,16 +129,20 @@ def process(self): LOG.info("Sync job has been completed") def __get_idx_e2e_messaging_block_number(self, db_session: Session): - _idx_e2e_messaging_block_number = db_session.query(IDXE2EMessagingBlockNumber). \ - first() + _idx_e2e_messaging_block_number = db_session.query( + IDXE2EMessagingBlockNumber + ).first() if _idx_e2e_messaging_block_number is None: return 0 else: return _idx_e2e_messaging_block_number.latest_block_number - def __set_idx_e2e_messaging_block_number(self, db_session: Session, block_number: int): - _idx_e2e_messaging_block_number = db_session.query(IDXE2EMessagingBlockNumber). \ - first() + def __set_idx_e2e_messaging_block_number( + self, db_session: Session, block_number: int + ): + _idx_e2e_messaging_block_number = db_session.query( + IDXE2EMessagingBlockNumber + ).first() if _idx_e2e_messaging_block_number is None: _idx_e2e_messaging_block_number = IDXE2EMessagingBlockNumber() @@ -166,11 +166,13 @@ def __sync_message(self, db_session: Session, block_from: int, block_to: int): contract=self.e2e_messaging_contract, event="Message", block_from=block_from, - block_to=block_to + block_to=block_to, ) for event in events: transaction_hash = event["transactionHash"].hex() - block_timestamp = datetime.utcfromtimestamp(web3.eth.get_block(event["blockNumber"])["timestamp"]) + block_timestamp = datetime.utcfromtimestamp( + web3.eth.get_block(event["blockNumber"])["timestamp"] + ) args = event["args"] from_address = args["sender"] to_address = args["receiver"] @@ -179,8 +181,7 @@ def __sync_message(self, db_session: Session, block_from: int, block_to: int): # Check if the message receiver is own accounts _e2e_messaging_account = self.__get_e2e_messaging_account( - db_session=db_session, - to_address=to_address + db_session=db_session, to_address=to_address ) if _e2e_messaging_account is None: continue @@ -190,7 +191,7 @@ def __sync_message(self, db_session: Session, block_from: int, block_to: int): db_session=db_session, to_address=to_address, text=text, - block_timestamp=block_timestamp + block_timestamp=block_timestamp, ) if message_type is None: continue @@ -204,22 +205,24 @@ def __sync_message(self, db_session: Session, block_from: int, block_to: int): send_timestamp=send_timestamp, _type=_type, message=message, - block_timestamp=block_timestamp + block_timestamp=block_timestamp, ) except Exception as e: LOG.error(e) def __get_e2e_messaging_account(self, db_session: Session, to_address: str): - # NOTE: Self sending data is registered at the time of sending. - _e2e_messaging_account = db_session.query(E2EMessagingAccount). \ - filter(E2EMessagingAccount.account_address == to_address). \ - filter(E2EMessagingAccount.is_deleted == False). \ - first() + _e2e_messaging_account = ( + db_session.query(E2EMessagingAccount) + .filter(E2EMessagingAccount.account_address == to_address) + .filter(E2EMessagingAccount.is_deleted == False) + .first() + ) return _e2e_messaging_account - def __get_message(self, db_session: Session, to_address: str, text: str, block_timestamp: datetime): - + def __get_message( + self, db_session: Session, to_address: str, text: str, block_timestamp: datetime + ): # Check message format try: text_dict = json.loads(text) @@ -237,11 +240,13 @@ def __get_message(self, db_session: Session, to_address: str, text: str, block_t return None # Get RSA key - account_rsa_key = db_session.query(E2EMessagingAccountRsaKey). \ - filter(E2EMessagingAccountRsaKey.account_address == to_address). \ - filter(E2EMessagingAccountRsaKey.block_timestamp <= block_timestamp). \ - order_by(desc(E2EMessagingAccountRsaKey.block_timestamp)). \ - first() + account_rsa_key = ( + db_session.query(E2EMessagingAccountRsaKey) + .filter(E2EMessagingAccountRsaKey.account_address == to_address) + .filter(E2EMessagingAccountRsaKey.block_timestamp <= block_timestamp) + .order_by(desc(E2EMessagingAccountRsaKey.block_timestamp)) + .first() + ) if account_rsa_key is None: LOG.warning(f"RSA key does not exist: account_address={to_address}") return None @@ -260,9 +265,9 @@ def __get_message(self, db_session: Session, to_address: str, text: str, block_t # Decrypt message try: message_org = base64.b64decode(message) - aes_iv = message_org[:AES.block_size] + aes_iv = message_org[: AES.block_size] aes_cipher = AES.new(aes_key, AES.MODE_CBC, aes_iv) - pad_message = aes_cipher.decrypt(message_org[AES.block_size:]) + pad_message = aes_cipher.decrypt(message_org[AES.block_size :]) decrypt_message = unpad(pad_message, AES.block_size).decode() except Exception as e: LOG.warning(f"Message could not be decoded: text={text}", exc_info=e) @@ -275,14 +280,16 @@ def __get_message(self, db_session: Session, to_address: str, text: str, block_t return decrypt_message, _type @staticmethod - def __sink_on_e2e_messaging(db_session: Session, - transaction_hash: str, - from_address: str, - to_address: str, - _type: str, - message: str, - send_timestamp: datetime, - block_timestamp: datetime): + def __sink_on_e2e_messaging( + db_session: Session, + transaction_hash: str, + from_address: str, + to_address: str, + _type: str, + message: str, + send_timestamp: datetime, + block_timestamp: datetime, + ): _idx_e2e_messaging = IDXE2EMessaging() _idx_e2e_messaging.transaction_hash = transaction_hash _idx_e2e_messaging.from_address = from_address diff --git a/batch/indexer_issue_redeem.py b/batch/indexer_issue_redeem.py index 1299e684..af4877be 100644 --- a/batch/indexer_issue_redeem.py +++ b/batch/indexer_issue_redeem.py @@ -24,28 +24,25 @@ from eth_utils import to_checksum_address from sqlalchemy import create_engine -from sqlalchemy.orm import Session from sqlalchemy.exc import SQLAlchemyError +from sqlalchemy.orm import Session from web3.eth import Contract path = os.path.join(os.path.dirname(__file__), "../") sys.path.append(path) -from config import ( - INDEXER_SYNC_INTERVAL, - DATABASE_URL, - INDEXER_BLOCK_LOT_MAX_SIZE -) +import batch_log + +from app.exceptions import ServiceUnavailableError from app.model.db import ( - Token, IDXIssueRedeem, + IDXIssueRedeemBlockNumber, IDXIssueRedeemEventType, - IDXIssueRedeemBlockNumber + Token, ) from app.utils.contract_utils import ContractUtils from app.utils.web3_utils import Web3Wrapper -from app.exceptions import ServiceUnavailableError -import batch_log +from config import DATABASE_URL, INDEXER_BLOCK_LOT_MAX_SIZE, INDEXER_SYNC_INTERVAL process_name = "INDEXER-Issue-Redeem" LOG = batch_log.get_logger(process_name=process_name) @@ -66,7 +63,9 @@ def sync_new_logs(self): # Get from_block_number and to_block_number for contract event filter latest_block = web3.eth.block_number - _from_block = self.__get_idx_issue_redeem_block_number(db_session=db_session) + _from_block = self.__get_idx_issue_redeem_block_number( + db_session=db_session + ) _to_block = _from_block + INDEXER_BLOCK_LOT_MAX_SIZE # Skip processing if the latest block is not counted up @@ -88,18 +87,17 @@ def sync_new_logs(self): self.__sync_all( db_session=db_session, block_from=_from_block + 1, - block_to=latest_block + block_to=latest_block, ) else: self.__sync_all( db_session=db_session, block_from=_from_block + 1, - block_to=latest_block + block_to=latest_block, ) self.__set_idx_transfer_block_number( - db_session=db_session, - block_number=latest_block + db_session=db_session, block_number=latest_block ) db_session.commit() finally: @@ -109,41 +107,44 @@ def sync_new_logs(self): def __get_token_list(self, db_session: Session): issued_token_address_list: tuple[str, ...] = tuple( [ - record[0] for record in ( - db_session.query(Token.token_address).filter(Token.token_status == 1).all() + record[0] + for record in ( + db_session.query(Token.token_address) + .filter(Token.token_status == 1) + .all() ) ] ) loaded_token_address_list: tuple[str, ...] = tuple(self.token_list.keys()) - load_required_address_list = list(set(issued_token_address_list) ^ set(loaded_token_address_list)) + load_required_address_list = list( + set(issued_token_address_list) ^ set(loaded_token_address_list) + ) if not load_required_address_list: # If there are no tokens to load newly, skip process return load_required_token_list: list[Type[Token]] = ( - db_session.query(Token). - filter(Token.token_status == 1). - filter(Token.token_address.in_(load_required_address_list)).all() + db_session.query(Token) + .filter(Token.token_status == 1) + .filter(Token.token_address.in_(load_required_address_list)) + .all() ) for load_required_token in load_required_token_list: token_contract = web3.eth.contract( - address=load_required_token.token_address, - abi=load_required_token.abi + address=load_required_token.token_address, abi=load_required_token.abi ) self.token_list[load_required_token.token_address] = token_contract def __get_idx_issue_redeem_block_number(self, db_session: Session): - _idx_transfer_block_number = db_session.query(IDXIssueRedeemBlockNumber). \ - first() + _idx_transfer_block_number = db_session.query(IDXIssueRedeemBlockNumber).first() if _idx_transfer_block_number is None: return 0 else: return _idx_transfer_block_number.latest_block_number def __set_idx_transfer_block_number(self, db_session: Session, block_number: int): - _idx_transfer_block_number = db_session.query(IDXIssueRedeemBlockNumber). \ - first() + _idx_transfer_block_number = db_session.query(IDXIssueRedeemBlockNumber).first() if _idx_transfer_block_number is None: _idx_transfer_block_number = IDXIssueRedeemBlockNumber() @@ -169,12 +170,14 @@ def __sync_issue(self, db_session: Session, block_from: int, block_to: int): contract=token, event="Issue", block_from=block_from, - block_to=block_to + block_to=block_to, ) for event in events: args = event["args"] transaction_hash = event["transactionHash"].hex() - block_timestamp = datetime.utcfromtimestamp(web3.eth.get_block(event["blockNumber"])["timestamp"]) + block_timestamp = datetime.utcfromtimestamp( + web3.eth.get_block(event["blockNumber"])["timestamp"] + ) if args["amount"] > sys.maxsize: pass else: @@ -186,7 +189,7 @@ def __sync_issue(self, db_session: Session, block_from: int, block_to: int): locked_address=args["lockAddress"], target_address=args["targetAddress"], amount=args["amount"], - block_timestamp=block_timestamp + block_timestamp=block_timestamp, ) except Exception: LOG.exception("An exception occurred during event synchronization") @@ -205,12 +208,14 @@ def __sync_redeem(self, db_session: Session, block_from: int, block_to: int): contract=token, event="Redeem", block_from=block_from, - block_to=block_to + block_to=block_to, ) for event in events: args = event["args"] transaction_hash = event["transactionHash"].hex() - block_timestamp = datetime.utcfromtimestamp(web3.eth.get_block(event["blockNumber"])["timestamp"]) + block_timestamp = datetime.utcfromtimestamp( + web3.eth.get_block(event["blockNumber"])["timestamp"] + ) if args["amount"] > sys.maxsize: pass else: @@ -222,20 +227,22 @@ def __sync_redeem(self, db_session: Session, block_from: int, block_to: int): locked_address=args["lockAddress"], target_address=args["targetAddress"], amount=args["amount"], - block_timestamp=block_timestamp + block_timestamp=block_timestamp, ) except Exception: LOG.exception("An exception occurred during event synchronization") @staticmethod - def __insert_index(db_session: Session, - event_type: str, - transaction_hash: str, - token_address: str, - locked_address: str, - target_address: str, - amount: int, - block_timestamp: datetime): + def __insert_index( + db_session: Session, + event_type: str, + transaction_hash: str, + token_address: str, + locked_address: str, + target_address: str, + amount: int, + block_timestamp: datetime, + ): _record = IDXIssueRedeem() _record.event_type = event_type _record.transaction_hash = transaction_hash diff --git a/batch/indexer_personal_info.py b/batch/indexer_personal_info.py index d0c67ebf..d7624764 100644 --- a/batch/indexer_personal_info.py +++ b/batch/indexer_personal_info.py @@ -21,30 +21,28 @@ import sys import time from datetime import datetime + +from eth_utils import to_checksum_address from sqlalchemy import create_engine from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.orm import Session -from eth_utils import to_checksum_address -path = os.path.join(os.path.dirname(__file__), '../') +path = os.path.join(os.path.dirname(__file__), "../") sys.path.append(path) +import batch_log + +from app.exceptions import ServiceUnavailableError +from app.model.blockchain import PersonalInfoContract +from app.model.db import IDXPersonalInfo, IDXPersonalInfoBlockNumber, Token +from app.utils.contract_utils import ContractUtils +from app.utils.web3_utils import Web3Wrapper from config import ( DATABASE_URL, - ZERO_ADDRESS, + INDEXER_BLOCK_LOT_MAX_SIZE, INDEXER_SYNC_INTERVAL, - INDEXER_BLOCK_LOT_MAX_SIZE -) -from app.model.db import ( - Token, - IDXPersonalInfo, - IDXPersonalInfoBlockNumber + ZERO_ADDRESS, ) -from app.model.blockchain import PersonalInfoContract -from app.utils.contract_utils import ContractUtils -from app.utils.web3_utils import Web3Wrapper -from app.exceptions import ServiceUnavailableError -import batch_log process_name = "INDEXER-Personal-Info" LOG = batch_log.get_logger(process_name=process_name) @@ -86,19 +84,16 @@ def process(self): self.__sync_all( db_session=db_session, block_from=_from_block + 1, - block_to=latest_block + block_to=latest_block, ) else: self.__sync_all( db_session=db_session, block_from=_from_block + 1, - block_to=latest_block + block_to=latest_block, ) - self.__set_block_number( - db_session=db_session, - block_number=latest_block - ) + self.__set_block_number(db_session=db_session, block_number=latest_block) db_session.commit() finally: db_session.close() @@ -110,21 +105,20 @@ def __refresh_personal_info_list(self, db_session: Session): tmp_list = [] for _token in _tokens: abi = _token.abi - token_contract = web3.eth.contract( - address=_token.token_address, - abi=abi - ) + token_contract = web3.eth.contract(address=_token.token_address, abi=abi) personal_info_address = ContractUtils.call_function( contract=token_contract, function_name="personalInfoAddress", args=(), - default_returns=ZERO_ADDRESS + default_returns=ZERO_ADDRESS, ) if personal_info_address != ZERO_ADDRESS: - tmp_list.append({ - "issuer_address": _token.issuer_address, - "personal_info_address": personal_info_address - }) + tmp_list.append( + { + "issuer_address": _token.issuer_address, + "personal_info_address": personal_info_address, + } + ) # Remove duplicates from the list unique_list = list(map(json.loads, set(map(json.dumps, tmp_list)))) @@ -133,7 +127,7 @@ def __refresh_personal_info_list(self, db_session: Session): personal_info_contract = PersonalInfoContract( db_session, issuer_address=item["issuer_address"], - contract_address=item["personal_info_address"] + contract_address=item["personal_info_address"], ) self.personal_info_contract_list.append(personal_info_contract) @@ -158,19 +152,18 @@ def __set_block_number(self, db_session: Session, block_number: int): def __sync_all(self, db_session: Session, block_from: int, block_to: int): LOG.info(f"Syncing from={block_from}, to={block_to}") self.__sync_personal_info_register( - db_session=db_session, - block_from=block_from, - block_to=block_to) + db_session=db_session, block_from=block_from, block_to=block_to + ) self.__sync_personal_info_modify( - db_session=db_session, - block_from=block_from, - block_to=block_to + db_session=db_session, block_from=block_from, block_to=block_to ) def __sync_personal_info_register(self, db_session: Session, block_from, block_to): for _personal_info_contract in self.personal_info_contract_list: try: - register_event_list = _personal_info_contract.get_register_event(block_from, block_to) + register_event_list = _personal_info_contract.get_register_event( + block_from, block_to + ) for event in register_event_list: args = event["args"] account_address = args.get("account_address", ZERO_ADDRESS) @@ -179,15 +172,14 @@ def __sync_personal_info_register(self, db_session: Session, block_from, block_t block = web3.eth.get_block(event["blockNumber"]) timestamp = datetime.utcfromtimestamp(block["timestamp"]) decrypted_personal_info = _personal_info_contract.get_info( - account_address=account_address, - default_value=None + account_address=account_address, default_value=None ) self.__sink_on_personal_info( db_session=db_session, account_address=account_address, issuer_address=link_address, personal_info=decrypted_personal_info, - timestamp=timestamp + timestamp=timestamp, ) db_session.commit() except Exception: @@ -196,7 +188,9 @@ def __sync_personal_info_register(self, db_session: Session, block_from, block_t def __sync_personal_info_modify(self, db_session: Session, block_from, block_to): for _personal_info_contract in self.personal_info_contract_list: try: - register_event_list = _personal_info_contract.get_modify_event(block_from, block_to) + register_event_list = _personal_info_contract.get_modify_event( + block_from, block_to + ) for event in register_event_list: args = event["args"] account_address = args.get("account_address", ZERO_ADDRESS) @@ -205,35 +199,44 @@ def __sync_personal_info_modify(self, db_session: Session, block_from, block_to) block = web3.eth.get_block(event["blockNumber"]) timestamp = datetime.utcfromtimestamp(block["timestamp"]) decrypted_personal_info = _personal_info_contract.get_info( - account_address=account_address, - default_value=None + account_address=account_address, default_value=None ) self.__sink_on_personal_info( db_session=db_session, account_address=account_address, issuer_address=link_address, personal_info=decrypted_personal_info, - timestamp=timestamp + timestamp=timestamp, ) db_session.commit() except Exception: LOG.exception("An exception occurred during event synchronization") @staticmethod - def __sink_on_personal_info(db_session: Session, - account_address: str, - issuer_address: str, - personal_info: dict, - timestamp: datetime): - _personal_info = db_session.query(IDXPersonalInfo). \ - filter(IDXPersonalInfo.account_address == to_checksum_address(account_address)). \ - filter(IDXPersonalInfo.issuer_address == to_checksum_address(issuer_address)). \ - first() + def __sink_on_personal_info( + db_session: Session, + account_address: str, + issuer_address: str, + personal_info: dict, + timestamp: datetime, + ): + _personal_info = ( + db_session.query(IDXPersonalInfo) + .filter( + IDXPersonalInfo.account_address == to_checksum_address(account_address) + ) + .filter( + IDXPersonalInfo.issuer_address == to_checksum_address(issuer_address) + ) + .first() + ) if _personal_info is not None: _personal_info.personal_info = personal_info _personal_info.modified = timestamp db_session.merge(_personal_info) - LOG.debug(f"Modify: account_address={account_address}, issuer_address={issuer_address}") + LOG.debug( + f"Modify: account_address={account_address}, issuer_address={issuer_address}" + ) else: _personal_info = IDXPersonalInfo() _personal_info.account_address = account_address @@ -242,7 +245,9 @@ def __sink_on_personal_info(db_session: Session, _personal_info.created = timestamp _personal_info.modified = timestamp db_session.add(_personal_info) - LOG.debug(f"Register: account_address={account_address}, issuer_address={issuer_address}") + LOG.debug( + f"Register: account_address={account_address}, issuer_address={issuer_address}" + ) def main(): @@ -263,4 +268,4 @@ def main(): if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/batch/indexer_position_bond.py b/batch/indexer_position_bond.py index 9bc3a268..f35c140f 100644 --- a/batch/indexer_position_bond.py +++ b/batch/indexer_position_bond.py @@ -21,47 +21,41 @@ import sys import time import uuid -from datetime import ( - datetime, - timezone, - timedelta -) -from typing import ( - Optional, - Type -) +from datetime import datetime, timedelta, timezone from itertools import groupby +from typing import Optional, Type from eth_utils import to_checksum_address from sqlalchemy import create_engine -from sqlalchemy.orm import Session from sqlalchemy.exc import SQLAlchemyError +from sqlalchemy.orm import Session from web3.eth import Contract path = os.path.join(os.path.dirname(__file__), "../") sys.path.append(path) +import batch_log + +from app.exceptions import ServiceUnavailableError from app.model.blockchain import IbetExchangeInterface from app.model.db import ( - Token, - TokenType, + IDXLock, + IDXLockedPosition, IDXPosition, IDXPositionBondBlockNumber, - IDXLockedPosition, - IDXLock, IDXUnlock, Notification, - NotificationType + NotificationType, + Token, + TokenType, ) from app.utils.contract_utils import ContractUtils from app.utils.web3_utils import Web3Wrapper -from app.exceptions import ServiceUnavailableError -import batch_log from config import ( DATABASE_URL, - ZERO_ADDRESS, + INDEXER_BLOCK_LOT_MAX_SIZE, INDEXER_SYNC_INTERVAL, - INDEXER_BLOCK_LOT_MAX_SIZE + ZERO_ADDRESS, ) process_name = "INDEXER-Position-Bond" @@ -108,18 +102,17 @@ def sync_new_logs(self): self.__sync_all( db_session=db_session, block_from=_from_block + 1, - block_to=latest_block + block_to=latest_block, ) else: self.__sync_all( db_session=db_session, block_from=_from_block + 1, - block_to=latest_block + block_to=latest_block, ) self.__set_idx_position_block_number( - db_session=db_session, - block_number=latest_block + db_session=db_session, block_number=latest_block ) db_session.commit() except Exception as e: @@ -134,28 +127,31 @@ def __get_contract_list(self, db_session: Session): issued_token_address_list: tuple[str, ...] = tuple( [ - record[0] for record in ( - db_session.query(Token.token_address). - filter(Token.type == TokenType.IBET_STRAIGHT_BOND). - filter(Token.token_status == 1).all() + record[0] + for record in ( + db_session.query(Token.token_address) + .filter(Token.type == TokenType.IBET_STRAIGHT_BOND) + .filter(Token.token_status == 1) + .all() ) ] ) loaded_token_address_list: tuple[str, ...] = tuple(self.token_list.keys()) - load_required_address_list = list(set(issued_token_address_list) ^ set(loaded_token_address_list)) + load_required_address_list = list( + set(issued_token_address_list) ^ set(loaded_token_address_list) + ) load_required_token_list: list[Type[Token]] = ( - db_session.query(Token). - filter(Token.type == TokenType.IBET_STRAIGHT_BOND). - filter(Token.token_status == 1). - filter(Token.token_address.in_(load_required_address_list)). - all() + db_session.query(Token) + .filter(Token.type == TokenType.IBET_STRAIGHT_BOND) + .filter(Token.token_status == 1) + .filter(Token.token_address.in_(load_required_address_list)) + .all() ) for load_required_token in load_required_token_list: token_contract = web3.eth.contract( - address=load_required_token.token_address, - abi=load_required_token.abi + address=load_required_token.token_address, abi=load_required_token.abi ) self.token_list[load_required_token.token_address] = token_contract @@ -165,7 +161,7 @@ def __get_contract_list(self, db_session: Session): contract=token_contract, function_name="tradableExchange", args=(), - default_returns=ZERO_ADDRESS + default_returns=ZERO_ADDRESS, ) if tradable_exchange_address != ZERO_ADDRESS: _exchange_list_tmp.append(tradable_exchange_address) @@ -174,16 +170,18 @@ def __get_contract_list(self, db_session: Session): self.exchange_address_list = list(set(_exchange_list_tmp)) def __get_idx_position_block_number(self, db_session: Session): - _idx_position_block_number = db_session.query(IDXPositionBondBlockNumber). \ - first() + _idx_position_block_number = db_session.query( + IDXPositionBondBlockNumber + ).first() if _idx_position_block_number is None: return 0 else: return _idx_position_block_number.latest_block_number def __set_idx_position_block_number(self, db_session: Session, block_number: int): - _idx_position_block_number = db_session.query(IDXPositionBondBlockNumber). \ - first() + _idx_position_block_number = db_session.query( + IDXPositionBondBlockNumber + ).first() if _idx_position_block_number is None: _idx_position_block_number = IDXPositionBondBlockNumber() @@ -212,15 +210,17 @@ def __sync_issuer(self, db_session: Session): contract=token, function_name="owner", args=(), - default_returns=ZERO_ADDRESS + default_returns=ZERO_ADDRESS, + ) + balance, pending_transfer = self.__get_account_balance_token( + token, issuer_address ) - balance, pending_transfer = self.__get_account_balance_token(token, issuer_address) self.__sink_on_position( db_session=db_session, token_address=to_checksum_address(token.address), account_address=issuer_address, balance=balance, - pending_transfer=pending_transfer + pending_transfer=pending_transfer, ) except Exception as e: raise e @@ -239,18 +239,20 @@ def __sync_issue(self, db_session: Session, block_from: int, block_to: int): contract=token, event="Issue", block_from=block_from, - block_to=block_to + block_to=block_to, ) for event in events: - args = event['args'] + args = event["args"] account = args.get("targetAddress", ZERO_ADDRESS) - balance, pending_transfer = self.__get_account_balance_token(token, account) + balance, pending_transfer = self.__get_account_balance_token( + token, account + ) self.__sink_on_position( db_session=db_session, token_address=to_checksum_address(token.address), account_address=account, balance=balance, - pending_transfer=pending_transfer + pending_transfer=pending_transfer, ) except Exception as e: raise e @@ -270,14 +272,21 @@ def __sync_transfer(self, db_session: Session, block_from: int, block_to: int): contract=token, event="Transfer", block_from=block_from, - block_to=block_to + block_to=block_to, ) for event in events: args = event["args"] - for account in [args.get("from", ZERO_ADDRESS), args.get("to", ZERO_ADDRESS)]: + for account in [ + args.get("from", ZERO_ADDRESS), + args.get("to", ZERO_ADDRESS), + ]: if web3.eth.get_code(account).hex() == "0x": - balance, pending_transfer, exchange_balance, exchange_commitment = \ - self.__get_account_balance_all(token, account) + ( + balance, + pending_transfer, + exchange_balance, + exchange_commitment, + ) = self.__get_account_balance_all(token, account) self.__sink_on_position( db_session=db_session, token_address=to_checksum_address(token.address), @@ -285,7 +294,7 @@ def __sync_transfer(self, db_session: Session, block_from: int, block_to: int): balance=balance, exchange_balance=exchange_balance, exchange_commitment=exchange_commitment, - pending_transfer=pending_transfer + pending_transfer=pending_transfer, ) except Exception as e: raise e @@ -304,7 +313,7 @@ def __sync_lock(self, db_session: Session, block_from: int, block_to: int): contract=token, event="Lock", block_from=block_from, - block_to=block_to + block_to=block_to, ) # Update locked positions @@ -328,7 +337,7 @@ def __sync_lock(self, db_session: Session, block_from: int, block_to: int): account_address=account_address, value=value, data_str=data, - block_timestamp=event_created + block_timestamp=event_created, ) if lock_address not in lock_map: @@ -340,29 +349,31 @@ def __sync_lock(self, db_session: Session, block_from: int, block_to: int): value = self.__get_account_locked_token( token_contract=token, lock_address=lock_address, - account_address=account_address + account_address=account_address, ) self.__sink_on_locked_position( db_session=db_session, token_address=to_checksum_address(token.address), lock_address=lock_address, account_address=account_address, - value=value + value=value, ) except Exception: pass # Update positions for event in events: - args = event['args'] + args = event["args"] account = args.get("accountAddress", ZERO_ADDRESS) - balance, pending_transfer = self.__get_account_balance_token(token, account) + balance, pending_transfer = self.__get_account_balance_token( + token, account + ) self.__sink_on_position( db_session=db_session, token_address=to_checksum_address(token.address), account_address=account, balance=balance, - pending_transfer=pending_transfer + pending_transfer=pending_transfer, ) # Insert Notification @@ -371,7 +382,7 @@ def __sync_lock(self, db_session: Session, block_from: int, block_to: int): contract=token, function_name="owner", args=(), - default_returns=ZERO_ADDRESS + default_returns=ZERO_ADDRESS, ) for event in events: args = event["args"] @@ -387,7 +398,7 @@ def __sync_lock(self, db_session: Session, block_from: int, block_to: int): account_address=account_address, lock_address=lock_address, value=value, - data_str=data + data_str=data, ) except Exception as e: @@ -407,7 +418,7 @@ def __sync_unlock(self, db_session: Session, block_from: int, block_to: int): contract=token, event="Unlock", block_from=block_from, - block_to=block_to + block_to=block_to, ) # Update locked positions @@ -433,7 +444,7 @@ def __sync_unlock(self, db_session: Session, block_from: int, block_to: int): recipient_address=recipient_address, value=value, data_str=data, - block_timestamp=event_created + block_timestamp=event_created, ) if lock_address not in lock_map: @@ -445,29 +456,31 @@ def __sync_unlock(self, db_session: Session, block_from: int, block_to: int): value = self.__get_account_locked_token( token_contract=token, lock_address=lock_address, - account_address=account_address + account_address=account_address, ) self.__sink_on_locked_position( db_session=db_session, token_address=to_checksum_address(token.address), lock_address=lock_address, account_address=account_address, - value=value + value=value, ) except Exception: pass # Update positions for event in events: - args = event['args'] + args = event["args"] account = args.get("recipientAddress", ZERO_ADDRESS) - balance, pending_transfer = self.__get_account_balance_token(token, account) + balance, pending_transfer = self.__get_account_balance_token( + token, account + ) self.__sink_on_position( db_session=db_session, token_address=to_checksum_address(token.address), account_address=account, balance=balance, - pending_transfer=pending_transfer + pending_transfer=pending_transfer, ) # Insert Notification @@ -476,7 +489,7 @@ def __sync_unlock(self, db_session: Session, block_from: int, block_to: int): contract=token, function_name="owner", args=(), - default_returns=ZERO_ADDRESS + default_returns=ZERO_ADDRESS, ) for event in events: args = event["args"] @@ -494,7 +507,7 @@ def __sync_unlock(self, db_session: Session, block_from: int, block_to: int): lock_address=lock_address, recipient_address=recipient_address, value=value, - data_str=data + data_str=data, ) except Exception as e: @@ -514,23 +527,27 @@ def __sync_redeem(self, db_session: Session, block_from: int, block_to: int): contract=token, event="Redeem", block_from=block_from, - block_to=block_to + block_to=block_to, ) for event in events: args = event["args"] account = args.get("targetAddress", ZERO_ADDRESS) - balance, pending_transfer = self.__get_account_balance_token(token, account) + balance, pending_transfer = self.__get_account_balance_token( + token, account + ) self.__sink_on_position( db_session=db_session, token_address=to_checksum_address(token.address), account_address=account, balance=balance, - pending_transfer=pending_transfer + pending_transfer=pending_transfer, ) except Exception as e: raise e - def __sync_apply_for_transfer(self, db_session: Session, block_from: int, block_to: int): + def __sync_apply_for_transfer( + self, db_session: Session, block_from: int, block_to: int + ): """Sync ApplyForTransfer Events :param db_session: database session @@ -544,23 +561,27 @@ def __sync_apply_for_transfer(self, db_session: Session, block_from: int, block_ contract=token, event="ApplyForTransfer", block_from=block_from, - block_to=block_to + block_to=block_to, ) for event in events: args = event["args"] account = args.get("from", ZERO_ADDRESS) - balance, pending_transfer = self.__get_account_balance_token(token, account) + balance, pending_transfer = self.__get_account_balance_token( + token, account + ) self.__sink_on_position( db_session=db_session, token_address=to_checksum_address(token.address), account_address=account, balance=balance, - pending_transfer=pending_transfer + pending_transfer=pending_transfer, ) except Exception as e: raise e - def __sync_cancel_transfer(self, db_session: Session, block_from: int, block_to: int): + def __sync_cancel_transfer( + self, db_session: Session, block_from: int, block_to: int + ): """Sync CancelTransfer Events :param db_session: database session @@ -574,23 +595,27 @@ def __sync_cancel_transfer(self, db_session: Session, block_from: int, block_to: contract=token, event="CancelTransfer", block_from=block_from, - block_to=block_to + block_to=block_to, ) for event in events: args = event["args"] account = args.get("from", ZERO_ADDRESS) - balance, pending_transfer = self.__get_account_balance_token(token, account) + balance, pending_transfer = self.__get_account_balance_token( + token, account + ) self.__sink_on_position( db_session=db_session, token_address=to_checksum_address(token.address), account_address=account, balance=balance, - pending_transfer=pending_transfer + pending_transfer=pending_transfer, ) except Exception as e: raise e - def __sync_approve_transfer(self, db_session: Session, block_from: int, block_to: int): + def __sync_approve_transfer( + self, db_session: Session, block_from: int, block_to: int + ): """Sync ApproveTransfer Events :param db_session: database session @@ -604,18 +629,23 @@ def __sync_approve_transfer(self, db_session: Session, block_from: int, block_to contract=token, event="ApproveTransfer", block_from=block_from, - block_to=block_to + block_to=block_to, ) for event in events: args = event["args"] - for account in [args.get("from", ZERO_ADDRESS), args.get("to", ZERO_ADDRESS)]: - balance, pending_transfer = self.__get_account_balance_token(token, account) + for account in [ + args.get("from", ZERO_ADDRESS), + args.get("to", ZERO_ADDRESS), + ]: + balance, pending_transfer = self.__get_account_balance_token( + token, account + ) self.__sink_on_position( db_session=db_session, token_address=to_checksum_address(token.address), account_address=account, balance=balance, - pending_transfer=pending_transfer + pending_transfer=pending_transfer, ) except Exception as e: raise e @@ -639,104 +669,156 @@ def __sync_exchange(self, db_session: Session, block_from: int, block_to: int): contract=exchange, event="NewOrder", block_from=block_from, - block_to=block_to + block_to=block_to, ) for _event in _event_list: - account_list_tmp.append({ - "token_address": _event["args"].get("tokenAddress", ZERO_ADDRESS), - "account_address": _event["args"].get("accountAddress", ZERO_ADDRESS) - }) + account_list_tmp.append( + { + "token_address": _event["args"].get( + "tokenAddress", ZERO_ADDRESS + ), + "account_address": _event["args"].get( + "accountAddress", ZERO_ADDRESS + ), + } + ) # CancelOrder event _event_list = ContractUtils.get_event_logs( contract=exchange, event="CancelOrder", block_from=block_from, - block_to=block_to + block_to=block_to, ) for _event in _event_list: - account_list_tmp.append({ - "token_address": _event["args"].get("tokenAddress", ZERO_ADDRESS), - "account_address": _event["args"].get("accountAddress", ZERO_ADDRESS) - }) + account_list_tmp.append( + { + "token_address": _event["args"].get( + "tokenAddress", ZERO_ADDRESS + ), + "account_address": _event["args"].get( + "accountAddress", ZERO_ADDRESS + ), + } + ) # ForceCancelOrder event _event_list = ContractUtils.get_event_logs( contract=exchange, event="ForceCancelOrder", block_from=block_from, - block_to=block_to + block_to=block_to, ) for _event in _event_list: - account_list_tmp.append({ - "token_address": _event["args"].get("tokenAddress", ZERO_ADDRESS), - "account_address": _event["args"].get("accountAddress", ZERO_ADDRESS) - }) + account_list_tmp.append( + { + "token_address": _event["args"].get( + "tokenAddress", ZERO_ADDRESS + ), + "account_address": _event["args"].get( + "accountAddress", ZERO_ADDRESS + ), + } + ) # Agree event _event_list = ContractUtils.get_event_logs( contract=exchange, event="Agree", block_from=block_from, - block_to=block_to + block_to=block_to, ) for _event in _event_list: - account_list_tmp.append({ - "token_address": _event["args"].get("tokenAddress", ZERO_ADDRESS), - "account_address": _event["args"].get("sellAddress", ZERO_ADDRESS) # only seller has changed - }) + account_list_tmp.append( + { + "token_address": _event["args"].get( + "tokenAddress", ZERO_ADDRESS + ), + "account_address": _event["args"].get( + "sellAddress", ZERO_ADDRESS + ), # only seller has changed + } + ) # SettlementOK event _event_list = ContractUtils.get_event_logs( contract=exchange, event="SettlementOK", block_from=block_from, - block_to=block_to + block_to=block_to, ) for _event in _event_list: - account_list_tmp.append({ - "token_address": _event["args"].get("tokenAddress", ZERO_ADDRESS), - "account_address": _event["args"].get("buyAddress", ZERO_ADDRESS) - }) - account_list_tmp.append({ - "token_address": _event["args"].get("tokenAddress", ZERO_ADDRESS), - "account_address": _event["args"].get("sellAddress", ZERO_ADDRESS) - }) + account_list_tmp.append( + { + "token_address": _event["args"].get( + "tokenAddress", ZERO_ADDRESS + ), + "account_address": _event["args"].get( + "buyAddress", ZERO_ADDRESS + ), + } + ) + account_list_tmp.append( + { + "token_address": _event["args"].get( + "tokenAddress", ZERO_ADDRESS + ), + "account_address": _event["args"].get( + "sellAddress", ZERO_ADDRESS + ), + } + ) # SettlementNG event _event_list = ContractUtils.get_event_logs( contract=exchange, event="SettlementNG", block_from=block_from, - block_to=block_to + block_to=block_to, ) for _event in _event_list: - account_list_tmp.append({ - "token_address": _event["args"].get("tokenAddress", ZERO_ADDRESS), - "account_address": _event["args"].get("sellAddress", ZERO_ADDRESS) # only seller has changed - }) + account_list_tmp.append( + { + "token_address": _event["args"].get( + "tokenAddress", ZERO_ADDRESS + ), + "account_address": _event["args"].get( + "sellAddress", ZERO_ADDRESS + ), # only seller has changed + } + ) # Make temporary list unique - account_list_tmp.sort(key=lambda x: (x["token_address"], x["account_address"])) + account_list_tmp.sort( + key=lambda x: (x["token_address"], x["account_address"]) + ) account_list = [] - for k, g in groupby(account_list_tmp, lambda x: (x["token_address"], x["account_address"])): - account_list.append({"token_address": k[0], "account_address": k[1]}) + for k, g in groupby( + account_list_tmp, + lambda x: (x["token_address"], x["account_address"]), + ): + account_list.append( + {"token_address": k[0], "account_address": k[1]} + ) # Update position for _account in account_list: token_address = _account["token_address"] account_address = _account["account_address"] - exchange_balance, exchange_commitment = self.__get_account_balance_exchange( + ( + exchange_balance, + exchange_commitment, + ) = self.__get_account_balance_exchange( exchange_address=exchange_address, token_address=token_address, - account_address=account_address + account_address=account_address, ) self.__sink_on_position( db_session=db_session, token_address=token_address, account_address=account_address, exchange_balance=exchange_balance, - exchange_commitment=exchange_commitment + exchange_commitment=exchange_commitment, ) except Exception as e: raise e @@ -751,7 +833,9 @@ def __sync_escrow(self, db_session: Session, block_from: int, block_to: int): """ for exchange_address in self.exchange_address_list: try: - escrow = ContractUtils.get_contract("IbetSecurityTokenEscrow", exchange_address) + escrow = ContractUtils.get_contract( + "IbetSecurityTokenEscrow", exchange_address + ) account_list_tmp = [] @@ -760,74 +844,103 @@ def __sync_escrow(self, db_session: Session, block_from: int, block_to: int): contract=escrow, event="EscrowCreated", block_from=block_from, - block_to=block_to + block_to=block_to, ) for _event in _event_list: - account_list_tmp.append({ - "token_address": _event["args"].get("token", ZERO_ADDRESS), - "account_address": _event["args"].get("sender", ZERO_ADDRESS) # only sender has changed - }) + account_list_tmp.append( + { + "token_address": _event["args"].get("token", ZERO_ADDRESS), + "account_address": _event["args"].get( + "sender", ZERO_ADDRESS + ), # only sender has changed + } + ) # EscrowCanceled event _event_list = ContractUtils.get_event_logs( contract=escrow, event="EscrowCanceled", block_from=block_from, - block_to=block_to + block_to=block_to, ) for _event in _event_list: - account_list_tmp.append({ - "token_address": _event["args"].get("token", ZERO_ADDRESS), - "account_address": _event["args"].get("sender", ZERO_ADDRESS) # only sender has changed - }) + account_list_tmp.append( + { + "token_address": _event["args"].get("token", ZERO_ADDRESS), + "account_address": _event["args"].get( + "sender", ZERO_ADDRESS + ), # only sender has changed + } + ) # HolderChanged event _event_list = ContractUtils.get_event_logs( contract=escrow, event="HolderChanged", block_from=block_from, - block_to=block_to + block_to=block_to, ) for _event in _event_list: - account_list_tmp.append({ - "token_address": _event["args"].get("token", ZERO_ADDRESS), - "account_address": _event["args"].get("from", ZERO_ADDRESS) - }) - account_list_tmp.append({ - "token_address": _event["args"].get("token", ZERO_ADDRESS), - "account_address": _event["args"].get("to", ZERO_ADDRESS) - }) + account_list_tmp.append( + { + "token_address": _event["args"].get("token", ZERO_ADDRESS), + "account_address": _event["args"].get("from", ZERO_ADDRESS), + } + ) + account_list_tmp.append( + { + "token_address": _event["args"].get("token", ZERO_ADDRESS), + "account_address": _event["args"].get("to", ZERO_ADDRESS), + } + ) # Make temporary list unique - account_list_tmp.sort(key=lambda x: (x["token_address"], x["account_address"])) + account_list_tmp.sort( + key=lambda x: (x["token_address"], x["account_address"]) + ) account_list = [] - for k, g in groupby(account_list_tmp, lambda x: (x["token_address"], x["account_address"])): - account_list.append({"token_address": k[0], "account_address": k[1]}) + for k, g in groupby( + account_list_tmp, + lambda x: (x["token_address"], x["account_address"]), + ): + account_list.append( + {"token_address": k[0], "account_address": k[1]} + ) # Update position for _account in account_list: token_address = _account["token_address"] account_address = _account["account_address"] - exchange_balance, exchange_commitment = self.__get_account_balance_exchange( + ( + exchange_balance, + exchange_commitment, + ) = self.__get_account_balance_exchange( exchange_address=exchange_address, token_address=token_address, - account_address=account_address + account_address=account_address, ) self.__sink_on_position( db_session=db_session, token_address=token_address, account_address=account_address, exchange_balance=exchange_balance, - exchange_commitment=exchange_commitment + exchange_commitment=exchange_commitment, ) except Exception as e: raise e @staticmethod - def __insert_lock_idx(db_session: Session, - transaction_hash: str, block_number: int, - token_address: str, lock_address: str, account_address: str, - value: int, data_str: str, block_timestamp: datetime): + def __insert_lock_idx( + db_session: Session, + transaction_hash: str, + block_number: int, + token_address: str, + lock_address: str, + account_address: str, + value: int, + data_str: str, + block_timestamp: datetime, + ): """Registry Lock event data in DB :param transaction_hash: transaction hash @@ -856,10 +969,18 @@ def __insert_lock_idx(db_session: Session, db_session.add(lock) @staticmethod - def __insert_unlock_idx(db_session: Session, - transaction_hash: str, block_number: int, - token_address: str, lock_address: str, account_address: str, recipient_address: str, - value: int, data_str: str, block_timestamp: datetime): + def __insert_unlock_idx( + db_session: Session, + transaction_hash: str, + block_number: int, + token_address: str, + lock_address: str, + account_address: str, + recipient_address: str, + value: int, + data_str: str, + block_timestamp: datetime, + ): """Registry Unlock event data in DB :param transaction_hash: transaction hash @@ -890,13 +1011,15 @@ def __insert_unlock_idx(db_session: Session, db_session.add(unlock) @staticmethod - def __sink_on_position(db_session: Session, - token_address: str, - account_address: str, - balance: Optional[int] = None, - exchange_balance: Optional[int] = None, - exchange_commitment: Optional[int] = None, - pending_transfer: Optional[int] = None): + def __sink_on_position( + db_session: Session, + token_address: str, + account_address: str, + balance: Optional[int] = None, + exchange_balance: Optional[int] = None, + exchange_commitment: Optional[int] = None, + pending_transfer: Optional[int] = None, + ): """Update balance data :param db_session: database session @@ -908,10 +1031,12 @@ def __sink_on_position(db_session: Session, :param pending_transfer: pending transfer :return: None """ - position = db_session.query(IDXPosition). \ - filter(IDXPosition.token_address == token_address). \ - filter(IDXPosition.account_address == account_address). \ - first() + position = ( + db_session.query(IDXPosition) + .filter(IDXPosition.token_address == token_address) + .filter(IDXPosition.account_address == account_address) + .first() + ) if position is not None: if balance is not None: position.balance = balance @@ -922,9 +1047,18 @@ def __sink_on_position(db_session: Session, if exchange_commitment is not None: position.exchange_commitment = exchange_commitment db_session.merge(position) - elif any(value is not None and value > 0 - for value in [balance, pending_transfer, exchange_balance, exchange_commitment]): - LOG.debug(f"Position created (Bond): token_address={token_address}, account_address={account_address}") + elif any( + value is not None and value > 0 + for value in [ + balance, + pending_transfer, + exchange_balance, + exchange_commitment, + ] + ): + LOG.debug( + f"Position created (Bond): token_address={token_address}, account_address={account_address}" + ) position = IDXPosition() position.token_address = token_address position.account_address = account_address @@ -935,11 +1069,13 @@ def __sink_on_position(db_session: Session, db_session.add(position) @staticmethod - def __sink_on_locked_position(db_session: Session, - token_address: str, - lock_address: str, - account_address: str, - value: int): + def __sink_on_locked_position( + db_session: Session, + token_address: str, + lock_address: str, + account_address: str, + value: int, + ): """Update locked balance data :param db_session: ORM session @@ -949,11 +1085,13 @@ def __sink_on_locked_position(db_session: Session, :param value: updated locked amount :return: None """ - locked = db_session.query(IDXLockedPosition). \ - filter(IDXLockedPosition.token_address == token_address). \ - filter(IDXLockedPosition.lock_address == lock_address). \ - filter(IDXLockedPosition.account_address == account_address). \ - first() + locked = ( + db_session.query(IDXLockedPosition) + .filter(IDXLockedPosition.token_address == token_address) + .filter(IDXLockedPosition.lock_address == lock_address) + .filter(IDXLockedPosition.account_address == account_address) + .first() + ) if locked is not None: locked.value = value db_session.merge(locked) @@ -966,14 +1104,16 @@ def __sink_on_locked_position(db_session: Session, db_session.add(locked) @staticmethod - def __sink_on_lock_info_notification(db_session: Session, - issuer_address: str, - token_address: str, - token_type: str, - account_address: str, - lock_address: str, - value: int, - data_str: str): + def __sink_on_lock_info_notification( + db_session: Session, + issuer_address: str, + token_address: str, + token_type: str, + account_address: str, + lock_address: str, + value: int, + data_str: str, + ): try: data = json.loads(data_str) except Exception: @@ -991,20 +1131,22 @@ def __sink_on_lock_info_notification(db_session: Session, "account_address": account_address, "lock_address": lock_address, "value": value, - "data": data + "data": data, } db_session.add(notification) @staticmethod - def __sink_on_unlock_info_notification(db_session: Session, - issuer_address: str, - token_address: str, - token_type: str, - account_address: str, - lock_address: str, - recipient_address: str, - value: int, - data_str: str): + def __sink_on_unlock_info_notification( + db_session: Session, + issuer_address: str, + token_address: str, + token_type: str, + account_address: str, + lock_address: str, + recipient_address: str, + value: int, + data_str: str, + ): try: data = json.loads(data_str) except Exception: @@ -1023,7 +1165,7 @@ def __sink_on_unlock_info_notification(db_session: Session, "lock_address": lock_address, "recipient_address": recipient_address, "value": value, - "data": data + "data": data, } db_session.add(notification) @@ -1035,13 +1177,13 @@ def __get_account_balance_all(token_contract, account_address: str): contract=token_contract, function_name="balanceOf", args=(account_address,), - default_returns=0 + default_returns=0, ) pending_transfer = ContractUtils.call_function( contract=token_contract, function_name="pendingTransfer", args=(account_address,), - default_returns=0 + default_returns=0, ) exchange_balance = 0 exchange_commitment = 0 @@ -1049,13 +1191,12 @@ def __get_account_balance_all(token_contract, account_address: str): contract=token_contract, function_name="tradableExchange", args=(), - default_returns=ZERO_ADDRESS + default_returns=ZERO_ADDRESS, ) if tradable_exchange_address != ZERO_ADDRESS: exchange_contract = IbetExchangeInterface(tradable_exchange_address) exchange_contract_balance = exchange_contract.get_account_balance( - account_address=account_address, - token_address=token_contract.address + account_address=account_address, token_address=token_contract.address ) exchange_balance = exchange_contract_balance["balance"] exchange_commitment = exchange_contract_balance["commitment"] @@ -1070,45 +1211,54 @@ def __get_account_balance_token(token_contract, account_address: str): contract=token_contract, function_name="balanceOf", args=(account_address,), - default_returns=0 + default_returns=0, ) pending_transfer = ContractUtils.call_function( contract=token_contract, function_name="pendingTransfer", args=(account_address,), - default_returns=0 + default_returns=0, ) return balance, pending_transfer @staticmethod - def __get_account_locked_token(token_contract, lock_address: str, account_address: str): + def __get_account_locked_token( + token_contract, lock_address: str, account_address: str + ): """Get locked balance on token""" value = ContractUtils.call_function( contract=token_contract, function_name="lockedOf", - args=(lock_address, account_address,), - default_returns=0 + args=( + lock_address, + account_address, + ), + default_returns=0, ) return value @staticmethod - def __get_account_balance_exchange(exchange_address: str, token_address: str, account_address: str): + def __get_account_balance_exchange( + exchange_address: str, token_address: str, account_address: str + ): """Get balance on exchange""" exchange_contract = IbetExchangeInterface(exchange_address) exchange_contract_balance = exchange_contract.get_account_balance( - account_address=account_address, - token_address=token_address + account_address=account_address, token_address=token_address + ) + return ( + exchange_contract_balance["balance"], + exchange_contract_balance["commitment"], ) - return exchange_contract_balance["balance"], exchange_contract_balance["commitment"] @staticmethod def __gen_block_timestamp(event): return datetime.fromtimestamp( - web3.eth.get_block(event["blockNumber"])["timestamp"], - UTC + web3.eth.get_block(event["blockNumber"])["timestamp"], UTC ) + def main(): LOG.info("Service started successfully") processor = Processor() diff --git a/batch/indexer_position_share.py b/batch/indexer_position_share.py index d317dbe3..856e9ea7 100644 --- a/batch/indexer_position_share.py +++ b/batch/indexer_position_share.py @@ -21,47 +21,41 @@ import sys import time import uuid -from datetime import ( - datetime, - timezone, - timedelta -) -from typing import ( - Optional, - Type -) +from datetime import datetime, timedelta, timezone from itertools import groupby +from typing import Optional, Type from eth_utils import to_checksum_address from sqlalchemy import create_engine -from sqlalchemy.orm import Session from sqlalchemy.exc import SQLAlchemyError +from sqlalchemy.orm import Session from web3.eth import Contract path = os.path.join(os.path.dirname(__file__), "../") sys.path.append(path) +import batch_log + +from app.exceptions import ServiceUnavailableError from app.model.blockchain import IbetExchangeInterface from app.model.db import ( - Token, - TokenType, + IDXLock, + IDXLockedPosition, IDXPosition, IDXPositionShareBlockNumber, - IDXLockedPosition, - IDXLock, IDXUnlock, Notification, - NotificationType + NotificationType, + Token, + TokenType, ) from app.utils.contract_utils import ContractUtils from app.utils.web3_utils import Web3Wrapper -from app.exceptions import ServiceUnavailableError -import batch_log from config import ( DATABASE_URL, - ZERO_ADDRESS, + INDEXER_BLOCK_LOT_MAX_SIZE, INDEXER_SYNC_INTERVAL, - INDEXER_BLOCK_LOT_MAX_SIZE + ZERO_ADDRESS, ) process_name = "INDEXER-Position-Share" @@ -108,18 +102,17 @@ def sync_new_logs(self): self.__sync_all( db_session=db_session, block_from=_from_block + 1, - block_to=latest_block + block_to=latest_block, ) else: self.__sync_all( db_session=db_session, block_from=_from_block + 1, - block_to=latest_block + block_to=latest_block, ) self.__set_idx_position_block_number( - db_session=db_session, - block_number=latest_block + db_session=db_session, block_number=latest_block ) db_session.commit() except Exception as e: @@ -134,28 +127,31 @@ def __get_contract_list(self, db_session: Session): issued_token_address_list: tuple[str, ...] = tuple( [ - record[0] for record in ( - db_session.query(Token.token_address). - filter(Token.type == TokenType.IBET_SHARE). - filter(Token.token_status == 1).all() + record[0] + for record in ( + db_session.query(Token.token_address) + .filter(Token.type == TokenType.IBET_SHARE) + .filter(Token.token_status == 1) + .all() ) ] ) loaded_token_address_list: tuple[str, ...] = tuple(self.token_list.keys()) - load_required_address_list = list(set(issued_token_address_list) ^ set(loaded_token_address_list)) + load_required_address_list = list( + set(issued_token_address_list) ^ set(loaded_token_address_list) + ) load_required_token_list: list[Type[Token]] = ( - db_session.query(Token). - filter(Token.type == TokenType.IBET_SHARE). - filter(Token.token_status == 1). - filter(Token.token_address.in_(load_required_address_list)). - all() + db_session.query(Token) + .filter(Token.type == TokenType.IBET_SHARE) + .filter(Token.token_status == 1) + .filter(Token.token_address.in_(load_required_address_list)) + .all() ) for load_required_token in load_required_token_list: token_contract = web3.eth.contract( - address=load_required_token.token_address, - abi=load_required_token.abi + address=load_required_token.token_address, abi=load_required_token.abi ) self.token_list[load_required_token.token_address] = token_contract @@ -165,7 +161,7 @@ def __get_contract_list(self, db_session: Session): contract=token_contract, function_name="tradableExchange", args=(), - default_returns=ZERO_ADDRESS + default_returns=ZERO_ADDRESS, ) if tradable_exchange_address != ZERO_ADDRESS: _exchange_list_tmp.append(tradable_exchange_address) @@ -174,16 +170,18 @@ def __get_contract_list(self, db_session: Session): self.exchange_address_list = list(set(_exchange_list_tmp)) def __get_idx_position_block_number(self, db_session: Session): - _idx_position_block_number = db_session.query(IDXPositionShareBlockNumber). \ - first() + _idx_position_block_number = db_session.query( + IDXPositionShareBlockNumber + ).first() if _idx_position_block_number is None: return 0 else: return _idx_position_block_number.latest_block_number def __set_idx_position_block_number(self, db_session: Session, block_number: int): - _idx_position_block_number = db_session.query(IDXPositionShareBlockNumber). \ - first() + _idx_position_block_number = db_session.query( + IDXPositionShareBlockNumber + ).first() if _idx_position_block_number is None: _idx_position_block_number = IDXPositionShareBlockNumber() @@ -212,15 +210,17 @@ def __sync_issuer(self, db_session: Session): contract=token, function_name="owner", args=(), - default_returns=ZERO_ADDRESS + default_returns=ZERO_ADDRESS, + ) + balance, pending_transfer = self.__get_account_balance_token( + token, issuer_address ) - balance, pending_transfer = self.__get_account_balance_token(token, issuer_address) self.__sink_on_position( db_session=db_session, token_address=to_checksum_address(token.address), account_address=issuer_address, balance=balance, - pending_transfer=pending_transfer + pending_transfer=pending_transfer, ) except Exception as e: raise e @@ -239,18 +239,20 @@ def __sync_issue(self, db_session: Session, block_from: int, block_to: int): contract=token, event="Issue", block_from=block_from, - block_to=block_to + block_to=block_to, ) for event in events: - args = event['args'] + args = event["args"] account = args.get("targetAddress", ZERO_ADDRESS) - balance, pending_transfer = self.__get_account_balance_token(token, account) + balance, pending_transfer = self.__get_account_balance_token( + token, account + ) self.__sink_on_position( db_session=db_session, token_address=to_checksum_address(token.address), account_address=account, balance=balance, - pending_transfer=pending_transfer + pending_transfer=pending_transfer, ) except Exception as e: raise e @@ -270,14 +272,21 @@ def __sync_transfer(self, db_session: Session, block_from: int, block_to: int): contract=token, event="Transfer", block_from=block_from, - block_to=block_to + block_to=block_to, ) for event in events: args = event["args"] - for account in [args.get("from", ZERO_ADDRESS), args.get("to", ZERO_ADDRESS)]: + for account in [ + args.get("from", ZERO_ADDRESS), + args.get("to", ZERO_ADDRESS), + ]: if web3.eth.get_code(account).hex() == "0x": - balance, pending_transfer, exchange_balance, exchange_commitment = \ - self.__get_account_balance_all(token, account) + ( + balance, + pending_transfer, + exchange_balance, + exchange_commitment, + ) = self.__get_account_balance_all(token, account) self.__sink_on_position( db_session=db_session, token_address=to_checksum_address(token.address), @@ -285,7 +294,7 @@ def __sync_transfer(self, db_session: Session, block_from: int, block_to: int): balance=balance, exchange_balance=exchange_balance, exchange_commitment=exchange_commitment, - pending_transfer=pending_transfer + pending_transfer=pending_transfer, ) except Exception as e: raise e @@ -304,7 +313,7 @@ def __sync_lock(self, db_session: Session, block_from: int, block_to: int): contract=token, event="Lock", block_from=block_from, - block_to=block_to + block_to=block_to, ) # Update locked positions @@ -328,7 +337,7 @@ def __sync_lock(self, db_session: Session, block_from: int, block_to: int): account_address=account_address, value=value, data_str=data, - block_timestamp=event_created + block_timestamp=event_created, ) if lock_address not in lock_map: @@ -340,29 +349,31 @@ def __sync_lock(self, db_session: Session, block_from: int, block_to: int): value = self.__get_account_locked_token( token_contract=token, lock_address=lock_address, - account_address=account_address + account_address=account_address, ) self.__sink_on_locked_position( db_session=db_session, token_address=to_checksum_address(token.address), lock_address=lock_address, account_address=account_address, - value=value + value=value, ) except Exception: pass # Update positions for event in events: - args = event['args'] + args = event["args"] account = args.get("accountAddress", ZERO_ADDRESS) - balance, pending_transfer = self.__get_account_balance_token(token, account) + balance, pending_transfer = self.__get_account_balance_token( + token, account + ) self.__sink_on_position( db_session=db_session, token_address=to_checksum_address(token.address), account_address=account, balance=balance, - pending_transfer=pending_transfer + pending_transfer=pending_transfer, ) # Insert Notification @@ -371,7 +382,7 @@ def __sync_lock(self, db_session: Session, block_from: int, block_to: int): contract=token, function_name="owner", args=(), - default_returns=ZERO_ADDRESS + default_returns=ZERO_ADDRESS, ) for event in events: args = event["args"] @@ -387,7 +398,7 @@ def __sync_lock(self, db_session: Session, block_from: int, block_to: int): account_address=account_address, lock_address=lock_address, value=value, - data_str=data + data_str=data, ) except Exception as e: @@ -407,7 +418,7 @@ def __sync_unlock(self, db_session: Session, block_from: int, block_to: int): contract=token, event="Unlock", block_from=block_from, - block_to=block_to + block_to=block_to, ) # Update locked positions @@ -433,7 +444,7 @@ def __sync_unlock(self, db_session: Session, block_from: int, block_to: int): recipient_address=recipient_address, value=value, data_str=data, - block_timestamp=event_created + block_timestamp=event_created, ) if lock_address not in lock_map: @@ -445,29 +456,31 @@ def __sync_unlock(self, db_session: Session, block_from: int, block_to: int): value = self.__get_account_locked_token( token_contract=token, lock_address=lock_address, - account_address=account_address + account_address=account_address, ) self.__sink_on_locked_position( db_session=db_session, token_address=to_checksum_address(token.address), lock_address=lock_address, account_address=account_address, - value=value + value=value, ) except Exception: pass # Update positions for event in events: - args = event['args'] + args = event["args"] account = args.get("recipientAddress", ZERO_ADDRESS) - balance, pending_transfer = self.__get_account_balance_token(token, account) + balance, pending_transfer = self.__get_account_balance_token( + token, account + ) self.__sink_on_position( db_session=db_session, token_address=to_checksum_address(token.address), account_address=account, balance=balance, - pending_transfer=pending_transfer + pending_transfer=pending_transfer, ) # Insert Notification @@ -476,7 +489,7 @@ def __sync_unlock(self, db_session: Session, block_from: int, block_to: int): contract=token, function_name="owner", args=(), - default_returns=ZERO_ADDRESS + default_returns=ZERO_ADDRESS, ) for event in events: args = event["args"] @@ -494,7 +507,7 @@ def __sync_unlock(self, db_session: Session, block_from: int, block_to: int): lock_address=lock_address, recipient_address=recipient_address, value=value, - data_str=data + data_str=data, ) except Exception as e: @@ -514,23 +527,27 @@ def __sync_redeem(self, db_session: Session, block_from: int, block_to: int): contract=token, event="Redeem", block_from=block_from, - block_to=block_to + block_to=block_to, ) for event in events: args = event["args"] account = args.get("targetAddress", ZERO_ADDRESS) - balance, pending_transfer = self.__get_account_balance_token(token, account) + balance, pending_transfer = self.__get_account_balance_token( + token, account + ) self.__sink_on_position( db_session=db_session, token_address=to_checksum_address(token.address), account_address=account, balance=balance, - pending_transfer=pending_transfer + pending_transfer=pending_transfer, ) except Exception as e: raise e - def __sync_apply_for_transfer(self, db_session: Session, block_from: int, block_to: int): + def __sync_apply_for_transfer( + self, db_session: Session, block_from: int, block_to: int + ): """Sync ApplyForTransfer Events :param db_session: database session @@ -544,23 +561,27 @@ def __sync_apply_for_transfer(self, db_session: Session, block_from: int, block_ contract=token, event="ApplyForTransfer", block_from=block_from, - block_to=block_to + block_to=block_to, ) for event in events: args = event["args"] account = args.get("from", ZERO_ADDRESS) - balance, pending_transfer = self.__get_account_balance_token(token, account) + balance, pending_transfer = self.__get_account_balance_token( + token, account + ) self.__sink_on_position( db_session=db_session, token_address=to_checksum_address(token.address), account_address=account, balance=balance, - pending_transfer=pending_transfer + pending_transfer=pending_transfer, ) except Exception as e: raise e - def __sync_cancel_transfer(self, db_session: Session, block_from: int, block_to: int): + def __sync_cancel_transfer( + self, db_session: Session, block_from: int, block_to: int + ): """Sync CancelTransfer Events :param db_session: database session @@ -574,23 +595,27 @@ def __sync_cancel_transfer(self, db_session: Session, block_from: int, block_to: contract=token, event="CancelTransfer", block_from=block_from, - block_to=block_to + block_to=block_to, ) for event in events: args = event["args"] account = args.get("from", ZERO_ADDRESS) - balance, pending_transfer = self.__get_account_balance_token(token, account) + balance, pending_transfer = self.__get_account_balance_token( + token, account + ) self.__sink_on_position( db_session=db_session, token_address=to_checksum_address(token.address), account_address=account, balance=balance, - pending_transfer=pending_transfer + pending_transfer=pending_transfer, ) except Exception as e: raise e - def __sync_approve_transfer(self, db_session: Session, block_from: int, block_to: int): + def __sync_approve_transfer( + self, db_session: Session, block_from: int, block_to: int + ): """Sync ApproveTransfer Events :param db_session: database session @@ -604,18 +629,23 @@ def __sync_approve_transfer(self, db_session: Session, block_from: int, block_to contract=token, event="ApproveTransfer", block_from=block_from, - block_to=block_to + block_to=block_to, ) for event in events: args = event["args"] - for account in [args.get("from", ZERO_ADDRESS), args.get("to", ZERO_ADDRESS)]: - balance, pending_transfer = self.__get_account_balance_token(token, account) + for account in [ + args.get("from", ZERO_ADDRESS), + args.get("to", ZERO_ADDRESS), + ]: + balance, pending_transfer = self.__get_account_balance_token( + token, account + ) self.__sink_on_position( db_session=db_session, token_address=to_checksum_address(token.address), account_address=account, balance=balance, - pending_transfer=pending_transfer + pending_transfer=pending_transfer, ) except Exception as e: raise e @@ -639,104 +669,156 @@ def __sync_exchange(self, db_session: Session, block_from: int, block_to: int): contract=exchange, event="NewOrder", block_from=block_from, - block_to=block_to + block_to=block_to, ) for _event in _event_list: - account_list_tmp.append({ - "token_address": _event["args"].get("tokenAddress", ZERO_ADDRESS), - "account_address": _event["args"].get("accountAddress", ZERO_ADDRESS) - }) + account_list_tmp.append( + { + "token_address": _event["args"].get( + "tokenAddress", ZERO_ADDRESS + ), + "account_address": _event["args"].get( + "accountAddress", ZERO_ADDRESS + ), + } + ) # CancelOrder event _event_list = ContractUtils.get_event_logs( contract=exchange, event="CancelOrder", block_from=block_from, - block_to=block_to + block_to=block_to, ) for _event in _event_list: - account_list_tmp.append({ - "token_address": _event["args"].get("tokenAddress", ZERO_ADDRESS), - "account_address": _event["args"].get("accountAddress", ZERO_ADDRESS) - }) + account_list_tmp.append( + { + "token_address": _event["args"].get( + "tokenAddress", ZERO_ADDRESS + ), + "account_address": _event["args"].get( + "accountAddress", ZERO_ADDRESS + ), + } + ) # ForceCancelOrder event _event_list = ContractUtils.get_event_logs( contract=exchange, event="ForceCancelOrder", block_from=block_from, - block_to=block_to + block_to=block_to, ) for _event in _event_list: - account_list_tmp.append({ - "token_address": _event["args"].get("tokenAddress", ZERO_ADDRESS), - "account_address": _event["args"].get("accountAddress", ZERO_ADDRESS) - }) + account_list_tmp.append( + { + "token_address": _event["args"].get( + "tokenAddress", ZERO_ADDRESS + ), + "account_address": _event["args"].get( + "accountAddress", ZERO_ADDRESS + ), + } + ) # Agree event _event_list = ContractUtils.get_event_logs( contract=exchange, event="Agree", block_from=block_from, - block_to=block_to + block_to=block_to, ) for _event in _event_list: - account_list_tmp.append({ - "token_address": _event["args"].get("tokenAddress", ZERO_ADDRESS), - "account_address": _event["args"].get("sellAddress", ZERO_ADDRESS) # only seller has changed - }) + account_list_tmp.append( + { + "token_address": _event["args"].get( + "tokenAddress", ZERO_ADDRESS + ), + "account_address": _event["args"].get( + "sellAddress", ZERO_ADDRESS + ), # only seller has changed + } + ) # SettlementOK event _event_list = ContractUtils.get_event_logs( contract=exchange, event="SettlementOK", block_from=block_from, - block_to=block_to + block_to=block_to, ) for _event in _event_list: - account_list_tmp.append({ - "token_address": _event["args"].get("tokenAddress", ZERO_ADDRESS), - "account_address": _event["args"].get("buyAddress", ZERO_ADDRESS) - }) - account_list_tmp.append({ - "token_address": _event["args"].get("tokenAddress", ZERO_ADDRESS), - "account_address": _event["args"].get("sellAddress", ZERO_ADDRESS) - }) + account_list_tmp.append( + { + "token_address": _event["args"].get( + "tokenAddress", ZERO_ADDRESS + ), + "account_address": _event["args"].get( + "buyAddress", ZERO_ADDRESS + ), + } + ) + account_list_tmp.append( + { + "token_address": _event["args"].get( + "tokenAddress", ZERO_ADDRESS + ), + "account_address": _event["args"].get( + "sellAddress", ZERO_ADDRESS + ), + } + ) # SettlementNG event _event_list = ContractUtils.get_event_logs( contract=exchange, event="SettlementNG", block_from=block_from, - block_to=block_to + block_to=block_to, ) for _event in _event_list: - account_list_tmp.append({ - "token_address": _event["args"].get("tokenAddress", ZERO_ADDRESS), - "account_address": _event["args"].get("sellAddress", ZERO_ADDRESS) # only seller has changed - }) + account_list_tmp.append( + { + "token_address": _event["args"].get( + "tokenAddress", ZERO_ADDRESS + ), + "account_address": _event["args"].get( + "sellAddress", ZERO_ADDRESS + ), # only seller has changed + } + ) # Make temporary list unique - account_list_tmp.sort(key=lambda x: (x["token_address"], x["account_address"])) + account_list_tmp.sort( + key=lambda x: (x["token_address"], x["account_address"]) + ) account_list = [] - for k, g in groupby(account_list_tmp, lambda x: (x["token_address"], x["account_address"])): - account_list.append({"token_address": k[0], "account_address": k[1]}) + for k, g in groupby( + account_list_tmp, + lambda x: (x["token_address"], x["account_address"]), + ): + account_list.append( + {"token_address": k[0], "account_address": k[1]} + ) # Update position for _account in account_list: token_address = _account["token_address"] account_address = _account["account_address"] - exchange_balance, exchange_commitment = self.__get_account_balance_exchange( + ( + exchange_balance, + exchange_commitment, + ) = self.__get_account_balance_exchange( exchange_address=exchange_address, token_address=token_address, - account_address=account_address + account_address=account_address, ) self.__sink_on_position( db_session=db_session, token_address=token_address, account_address=account_address, exchange_balance=exchange_balance, - exchange_commitment=exchange_commitment + exchange_commitment=exchange_commitment, ) except Exception as e: raise e @@ -751,7 +833,9 @@ def __sync_escrow(self, db_session: Session, block_from: int, block_to: int): """ for exchange_address in self.exchange_address_list: try: - escrow = ContractUtils.get_contract("IbetSecurityTokenEscrow", exchange_address) + escrow = ContractUtils.get_contract( + "IbetSecurityTokenEscrow", exchange_address + ) account_list_tmp = [] @@ -760,74 +844,103 @@ def __sync_escrow(self, db_session: Session, block_from: int, block_to: int): contract=escrow, event="EscrowCreated", block_from=block_from, - block_to=block_to + block_to=block_to, ) for _event in _event_list: - account_list_tmp.append({ - "token_address": _event["args"].get("token", ZERO_ADDRESS), - "account_address": _event["args"].get("sender", ZERO_ADDRESS) # only sender has changed - }) + account_list_tmp.append( + { + "token_address": _event["args"].get("token", ZERO_ADDRESS), + "account_address": _event["args"].get( + "sender", ZERO_ADDRESS + ), # only sender has changed + } + ) # EscrowCanceled event _event_list = ContractUtils.get_event_logs( contract=escrow, event="EscrowCanceled", block_from=block_from, - block_to=block_to + block_to=block_to, ) for _event in _event_list: - account_list_tmp.append({ - "token_address": _event["args"].get("token", ZERO_ADDRESS), - "account_address": _event["args"].get("sender", ZERO_ADDRESS) # only sender has changed - }) + account_list_tmp.append( + { + "token_address": _event["args"].get("token", ZERO_ADDRESS), + "account_address": _event["args"].get( + "sender", ZERO_ADDRESS + ), # only sender has changed + } + ) # HolderChanged event _event_list = ContractUtils.get_event_logs( contract=escrow, event="HolderChanged", block_from=block_from, - block_to=block_to + block_to=block_to, ) for _event in _event_list: - account_list_tmp.append({ - "token_address": _event["args"].get("token", ZERO_ADDRESS), - "account_address": _event["args"].get("from", ZERO_ADDRESS) - }) - account_list_tmp.append({ - "token_address": _event["args"].get("token", ZERO_ADDRESS), - "account_address": _event["args"].get("to", ZERO_ADDRESS) - }) + account_list_tmp.append( + { + "token_address": _event["args"].get("token", ZERO_ADDRESS), + "account_address": _event["args"].get("from", ZERO_ADDRESS), + } + ) + account_list_tmp.append( + { + "token_address": _event["args"].get("token", ZERO_ADDRESS), + "account_address": _event["args"].get("to", ZERO_ADDRESS), + } + ) # Make temporary list unique - account_list_tmp.sort(key=lambda x: (x["token_address"], x["account_address"])) + account_list_tmp.sort( + key=lambda x: (x["token_address"], x["account_address"]) + ) account_list = [] - for k, g in groupby(account_list_tmp, lambda x: (x["token_address"], x["account_address"])): - account_list.append({"token_address": k[0], "account_address": k[1]}) + for k, g in groupby( + account_list_tmp, + lambda x: (x["token_address"], x["account_address"]), + ): + account_list.append( + {"token_address": k[0], "account_address": k[1]} + ) # Update position for _account in account_list: token_address = _account["token_address"] account_address = _account["account_address"] - exchange_balance, exchange_commitment = self.__get_account_balance_exchange( + ( + exchange_balance, + exchange_commitment, + ) = self.__get_account_balance_exchange( exchange_address=exchange_address, token_address=token_address, - account_address=account_address + account_address=account_address, ) self.__sink_on_position( db_session=db_session, token_address=token_address, account_address=account_address, exchange_balance=exchange_balance, - exchange_commitment=exchange_commitment + exchange_commitment=exchange_commitment, ) except Exception as e: raise e @staticmethod - def __insert_lock_idx(db_session: Session, - transaction_hash: str, block_number: int, - token_address: str, lock_address: str, account_address: str, - value: int, data_str: str, block_timestamp: datetime): + def __insert_lock_idx( + db_session: Session, + transaction_hash: str, + block_number: int, + token_address: str, + lock_address: str, + account_address: str, + value: int, + data_str: str, + block_timestamp: datetime, + ): """Registry Lock event data in DB :param transaction_hash: transaction hash @@ -856,10 +969,18 @@ def __insert_lock_idx(db_session: Session, db_session.add(lock) @staticmethod - def __insert_unlock_idx(db_session: Session, - transaction_hash: str, block_number: int, - token_address: str, lock_address: str, account_address: str, recipient_address: str, - value: int, data_str: str, block_timestamp: datetime): + def __insert_unlock_idx( + db_session: Session, + transaction_hash: str, + block_number: int, + token_address: str, + lock_address: str, + account_address: str, + recipient_address: str, + value: int, + data_str: str, + block_timestamp: datetime, + ): """Registry Unlock event data in DB :param transaction_hash: transaction hash @@ -890,13 +1011,15 @@ def __insert_unlock_idx(db_session: Session, db_session.add(unlock) @staticmethod - def __sink_on_position(db_session: Session, - token_address: str, - account_address: str, - balance: Optional[int] = None, - exchange_balance: Optional[int] = None, - exchange_commitment: Optional[int] = None, - pending_transfer: Optional[int] = None): + def __sink_on_position( + db_session: Session, + token_address: str, + account_address: str, + balance: Optional[int] = None, + exchange_balance: Optional[int] = None, + exchange_commitment: Optional[int] = None, + pending_transfer: Optional[int] = None, + ): """Update balance data :param db_session: database session @@ -908,10 +1031,12 @@ def __sink_on_position(db_session: Session, :param pending_transfer: pending transfer :return: None """ - position = db_session.query(IDXPosition). \ - filter(IDXPosition.token_address == token_address). \ - filter(IDXPosition.account_address == account_address). \ - first() + position = ( + db_session.query(IDXPosition) + .filter(IDXPosition.token_address == token_address) + .filter(IDXPosition.account_address == account_address) + .first() + ) if position is not None: if balance is not None: position.balance = balance @@ -922,9 +1047,18 @@ def __sink_on_position(db_session: Session, if exchange_commitment is not None: position.exchange_commitment = exchange_commitment db_session.merge(position) - elif any(value is not None and value > 0 - for value in [balance, pending_transfer, exchange_balance, exchange_commitment]): - LOG.debug(f"Position created (Share): token_address={token_address}, account_address={account_address}") + elif any( + value is not None and value > 0 + for value in [ + balance, + pending_transfer, + exchange_balance, + exchange_commitment, + ] + ): + LOG.debug( + f"Position created (Share): token_address={token_address}, account_address={account_address}" + ) position = IDXPosition() position.token_address = token_address position.account_address = account_address @@ -935,11 +1069,13 @@ def __sink_on_position(db_session: Session, db_session.add(position) @staticmethod - def __sink_on_locked_position(db_session: Session, - token_address: str, - lock_address: str, - account_address: str, - value: int): + def __sink_on_locked_position( + db_session: Session, + token_address: str, + lock_address: str, + account_address: str, + value: int, + ): """Update locked balance data :param db_session: ORM session @@ -949,11 +1085,13 @@ def __sink_on_locked_position(db_session: Session, :param value: updated locked amount :return: None """ - locked = db_session.query(IDXLockedPosition). \ - filter(IDXLockedPosition.token_address == token_address). \ - filter(IDXLockedPosition.lock_address == lock_address). \ - filter(IDXLockedPosition.account_address == account_address). \ - first() + locked = ( + db_session.query(IDXLockedPosition) + .filter(IDXLockedPosition.token_address == token_address) + .filter(IDXLockedPosition.lock_address == lock_address) + .filter(IDXLockedPosition.account_address == account_address) + .first() + ) if locked is not None: locked.value = value db_session.merge(locked) @@ -966,14 +1104,16 @@ def __sink_on_locked_position(db_session: Session, db_session.add(locked) @staticmethod - def __sink_on_lock_info_notification(db_session: Session, - issuer_address: str, - token_address: str, - token_type: str, - account_address: str, - lock_address: str, - value: int, - data_str: str): + def __sink_on_lock_info_notification( + db_session: Session, + issuer_address: str, + token_address: str, + token_type: str, + account_address: str, + lock_address: str, + value: int, + data_str: str, + ): try: data = json.loads(data_str) except Exception: @@ -991,20 +1131,22 @@ def __sink_on_lock_info_notification(db_session: Session, "account_address": account_address, "lock_address": lock_address, "value": value, - "data": data + "data": data, } db_session.add(notification) @staticmethod - def __sink_on_unlock_info_notification(db_session: Session, - issuer_address: str, - token_address: str, - token_type: str, - account_address: str, - lock_address: str, - recipient_address: str, - value: int, - data_str: str): + def __sink_on_unlock_info_notification( + db_session: Session, + issuer_address: str, + token_address: str, + token_type: str, + account_address: str, + lock_address: str, + recipient_address: str, + value: int, + data_str: str, + ): try: data = json.loads(data_str) except Exception: @@ -1023,7 +1165,7 @@ def __sink_on_unlock_info_notification(db_session: Session, "lock_address": lock_address, "recipient_address": recipient_address, "value": value, - "data": data + "data": data, } db_session.add(notification) @@ -1035,13 +1177,13 @@ def __get_account_balance_all(token_contract, account_address: str): contract=token_contract, function_name="balanceOf", args=(account_address,), - default_returns=0 + default_returns=0, ) pending_transfer = ContractUtils.call_function( contract=token_contract, function_name="pendingTransfer", args=(account_address,), - default_returns=0 + default_returns=0, ) exchange_balance = 0 exchange_commitment = 0 @@ -1049,13 +1191,12 @@ def __get_account_balance_all(token_contract, account_address: str): contract=token_contract, function_name="tradableExchange", args=(), - default_returns=ZERO_ADDRESS + default_returns=ZERO_ADDRESS, ) if tradable_exchange_address != ZERO_ADDRESS: exchange_contract = IbetExchangeInterface(tradable_exchange_address) exchange_contract_balance = exchange_contract.get_account_balance( - account_address=account_address, - token_address=token_contract.address + account_address=account_address, token_address=token_contract.address ) exchange_balance = exchange_contract_balance["balance"] exchange_commitment = exchange_contract_balance["commitment"] @@ -1070,45 +1211,54 @@ def __get_account_balance_token(token_contract, account_address: str): contract=token_contract, function_name="balanceOf", args=(account_address,), - default_returns=0 + default_returns=0, ) pending_transfer = ContractUtils.call_function( contract=token_contract, function_name="pendingTransfer", args=(account_address,), - default_returns=0 + default_returns=0, ) return balance, pending_transfer @staticmethod - def __get_account_locked_token(token_contract, lock_address: str, account_address: str): + def __get_account_locked_token( + token_contract, lock_address: str, account_address: str + ): """Get locked balance on token""" value = ContractUtils.call_function( contract=token_contract, function_name="lockedOf", - args=(lock_address, account_address,), - default_returns=0 + args=( + lock_address, + account_address, + ), + default_returns=0, ) return value @staticmethod - def __get_account_balance_exchange(exchange_address: str, token_address: str, account_address: str): + def __get_account_balance_exchange( + exchange_address: str, token_address: str, account_address: str + ): """Get balance on exchange""" exchange_contract = IbetExchangeInterface(exchange_address) exchange_contract_balance = exchange_contract.get_account_balance( - account_address=account_address, - token_address=token_address + account_address=account_address, token_address=token_address + ) + return ( + exchange_contract_balance["balance"], + exchange_contract_balance["commitment"], ) - return exchange_contract_balance["balance"], exchange_contract_balance["commitment"] @staticmethod def __gen_block_timestamp(event): return datetime.fromtimestamp( - web3.eth.get_block(event["blockNumber"])["timestamp"], - UTC + web3.eth.get_block(event["blockNumber"])["timestamp"], UTC ) + def main(): LOG.info("Service started successfully") processor = Processor() diff --git a/batch/indexer_token_holders.py b/batch/indexer_token_holders.py index fb9180bb..5c4b4796 100644 --- a/batch/indexer_token_holders.py +++ b/batch/indexer_token_holders.py @@ -19,33 +19,34 @@ import os import sys import time -from typing import Optional, Dict, List, Type +from typing import Dict, List, Optional, Type from sqlalchemy import create_engine -from sqlalchemy.orm import Session from sqlalchemy.exc import SQLAlchemyError +from sqlalchemy.orm import Session from web3.contract import Contract path = os.path.join(os.path.dirname(__file__), "../") sys.path.append(path) -from config import ( - DATABASE_URL, - ZERO_ADDRESS, - INDEXER_SYNC_INTERVAL, - INDEXER_BLOCK_LOT_MAX_SIZE -) +import batch_log + from app.exceptions import ServiceUnavailableError from app.model.db import ( - TokenType, + Token, TokenHolder, - TokenHoldersList, TokenHolderBatchStatus, - Token + TokenHoldersList, + TokenType, ) from app.utils.contract_utils import ContractUtils from app.utils.web3_utils import Web3Wrapper -import batch_log +from config import ( + DATABASE_URL, + INDEXER_BLOCK_LOT_MAX_SIZE, + INDEXER_SYNC_INTERVAL, + ZERO_ADDRESS, +) process_name = "INDEXER-Token-Holders" LOG = batch_log.get_logger(process_name=process_name) @@ -96,14 +97,19 @@ def __get_db_session() -> Session: def __load_target(self, db_session: Session) -> bool: self.target: TokenHoldersList = ( - db_session.query(TokenHoldersList).filter(TokenHoldersList.batch_status == TokenHolderBatchStatus.PENDING).first() + db_session.query(TokenHoldersList) + .filter(TokenHoldersList.batch_status == TokenHolderBatchStatus.PENDING) + .first() ) return True if self.target else False def __load_token_info(self, db_session: Session) -> bool: # Fetch token list information from DB issued_token: Optional[Token] = ( - db_session.query(Token).filter(Token.token_address == self.target.token_address).filter(Token.token_status == 1).first() + db_session.query(Token) + .filter(Token.token_address == self.target.token_address) + .filter(Token.token_status == 1) + .first() ) if not issued_token: return False @@ -111,9 +117,13 @@ def __load_token_info(self, db_session: Session) -> bool: token_type = issued_token.type # Store token contract. if token_type == TokenType.IBET_STRAIGHT_BOND.value: - self.token_contract = ContractUtils.get_contract("IbetStraightBond", self.target.token_address) + self.token_contract = ContractUtils.get_contract( + "IbetStraightBond", self.target.token_address + ) elif token_type == TokenType.IBET_SHARE.value: - self.token_contract = ContractUtils.get_contract("IbetShare", self.target.token_address) + self.token_contract = ContractUtils.get_contract( + "IbetShare", self.target.token_address + ) else: return False @@ -130,7 +140,9 @@ def __load_token_info(self, db_session: Session) -> bool: ) return True - def __load_checkpoint(self, local_session: Session, target_token_address: str, block_to: int) -> int: + def __load_checkpoint( + self, local_session: Session, target_token_address: str, block_to: int + ) -> int: _checkpoint: Optional[TokenHoldersList] = ( local_session.query(TokenHoldersList) .filter(TokenHoldersList.token_address == target_token_address) @@ -140,9 +152,15 @@ def __load_checkpoint(self, local_session: Session, target_token_address: str, b .first() ) if _checkpoint: - _holders: List[TokenHolder] = local_session.query(TokenHolder).filter(TokenHolder.holder_list_id == _checkpoint.id).all() + _holders: List[TokenHolder] = ( + local_session.query(TokenHolder) + .filter(TokenHolder.holder_list_id == _checkpoint.id) + .all() + ) for holder in _holders: - self.balance_book.store(account_address=holder.account_address, amount=holder.hold_balance) + self.balance_book.store( + account_address=holder.account_address, amount=holder.hold_balance + ) block_from = _checkpoint.block_number + 1 return block_from return 0 @@ -159,7 +177,9 @@ def collect(self): local_session.commit() return _target_block = self.target.block_number - _from_block = self.__load_checkpoint(local_session, self.target.token_address, block_to=_target_block) + _from_block = self.__load_checkpoint( + local_session, self.target.token_address, block_to=_target_block + ) _to_block = INDEXER_BLOCK_LOT_MAX_SIZE - 1 + _from_block if _target_block > _to_block: @@ -167,20 +187,20 @@ def collect(self): self.__process_all( db_session=local_session, block_from=_from_block, - block_to=_to_block + block_to=_to_block, ) _from_block += INDEXER_BLOCK_LOT_MAX_SIZE _to_block += INDEXER_BLOCK_LOT_MAX_SIZE self.__process_all( db_session=local_session, block_from=_from_block, - block_to=_target_block + block_to=_target_block, ) else: self.__process_all( db_session=local_session, block_from=_from_block, - block_to=_target_block + block_to=_target_block, ) self.__update_status(local_session, TokenHolderBatchStatus.DONE) local_session.commit() @@ -197,16 +217,18 @@ def __update_status(self, local_session: Session, status: TokenHolderBatchStatus if status == TokenHolderBatchStatus.DONE: # Not to store non-holders ( - local_session.query(TokenHolder). - filter(TokenHolder.holder_list_id == self.target.id). - filter(TokenHolder.hold_balance == 0). - filter(TokenHolder.locked_balance == 0). - delete() + local_session.query(TokenHolder) + .filter(TokenHolder.holder_list_id == self.target.id) + .filter(TokenHolder.hold_balance == 0) + .filter(TokenHolder.locked_balance == 0) + .delete() ) self.target.batch_status = status.value local_session.merge(self.target) - LOG.info(f"Token holder list({self.target.list_id}) status changes to be {status.value}.") + LOG.info( + f"Token holder list({self.target.list_id}) status changes to be {status.value}." + ) self.target = None self.balance_book = self.BalanceBook() @@ -252,9 +274,7 @@ def __process_transfer(self, block_from: int, block_to: int): event="HolderChanged", block_from=block_from, block_to=block_to, - argument_filters={ - "token": self.token_contract.address - } + argument_filters={"token": self.token_contract.address}, ) for _event in holder_changed_events: if self.token_contract.address == _event["args"]["token"]: @@ -287,7 +307,9 @@ def __process_transfer(self, block_from: int, block_to: int): ) # Marge & Sort: block_number > log_index - events = sorted(tmp_events, key=lambda x: (x["block_number"], x["log_index"])) + events = sorted( + tmp_events, key=lambda x: (x["block_number"], x["log_index"]) + ) for event in events: args = event["args"] @@ -296,12 +318,17 @@ def __process_transfer(self, block_from: int, block_to: int): amount = args.get("value") # Skip sinking in case of deposit to exchange or withdrawal from exchange - if web3.eth.get_code(from_account).hex() != "0x" or web3.eth.get_code(to_account).hex() != "0x": + if ( + web3.eth.get_code(from_account).hex() != "0x" + or web3.eth.get_code(to_account).hex() != "0x" + ): continue if amount is not None and amount <= sys.maxsize: # Update Balance(from account) - self.balance_book.store(account_address=from_account, amount=-amount) + self.balance_book.store( + account_address=from_account, amount=-amount + ) # Update Balance(to account) self.balance_book.store(account_address=to_account, amount=+amount) @@ -325,7 +352,7 @@ def __process_issue(self, block_from: int, block_to: int): contract=self.token_contract, event="Issue", block_from=block_from, - block_to=block_to + block_to=block_to, ) for event in events: args = event["args"] @@ -335,7 +362,9 @@ def __process_issue(self, block_from: int, block_to: int): if lock_address == ZERO_ADDRESS: if amount is not None and amount <= sys.maxsize: # Update Balance - self.balance_book.store(account_address=account_address, amount=+amount) + self.balance_book.store( + account_address=account_address, amount=+amount + ) except Exception: raise @@ -356,7 +385,7 @@ def __process_redeem(self, block_from: int, block_to: int): contract=self.token_contract, event="Redeem", block_from=block_from, - block_to=block_to + block_to=block_to, ) for event in events: @@ -367,7 +396,9 @@ def __process_redeem(self, block_from: int, block_to: int): if lock_address == ZERO_ADDRESS: if amount is not None and amount <= sys.maxsize: # Update Balance - self.balance_book.store(account_address=account_address, amount=-amount) + self.balance_book.store( + account_address=account_address, amount=-amount + ) except Exception: raise @@ -388,14 +419,16 @@ def __process_lock(self, block_from: int, block_to: int): contract=self.token_contract, event="Lock", block_from=block_from, - block_to=block_to + block_to=block_to, ) for event in events: args = event["args"] account_address = args.get("accountAddress", ZERO_ADDRESS) amount = args.get("value") if amount is not None and amount <= sys.maxsize: - self.balance_book.store(account_address=account_address, amount=-amount, locked=+amount) + self.balance_book.store( + account_address=account_address, amount=-amount, locked=+amount + ) except Exception: raise @@ -415,7 +448,7 @@ def __process_unlock(self, block_from: int, block_to: int): contract=self.token_contract, event="Unlock", block_from=block_from, - block_to=block_to + block_to=block_to, ) for event in events: args = event["args"] @@ -423,8 +456,12 @@ def __process_unlock(self, block_from: int, block_to: int): recipient_address = args.get("recipientAddress", ZERO_ADDRESS) amount = args.get("value") if amount is not None and amount <= sys.maxsize: - self.balance_book.store(account_address=account_address, locked=-amount) - self.balance_book.store(account_address=recipient_address, amount=+amount) + self.balance_book.store( + account_address=account_address, locked=-amount + ) + self.balance_book.store( + account_address=recipient_address, amount=+amount + ) except Exception: raise @@ -436,7 +473,9 @@ def __save_holders( token_address: str, token_owner_address: str, ): - for account_address, page in zip(balance_book.pages.keys(), balance_book.pages.values()): + for account_address, page in zip( + balance_book.pages.keys(), balance_book.pages.values() + ): if page.account_address == token_owner_address: # Skip storing data for token owner continue @@ -451,7 +490,9 @@ def __save_holders( token_holder.locked_balance = page.locked_balance db_session.merge(token_holder) elif page.hold_balance > 0 or page.locked_balance > 0: - LOG.debug(f"Collection record created : token_address={token_address}, account_address={account_address}") + LOG.debug( + f"Collection record created : token_address={token_address}, account_address={account_address}" + ) page.holder_list_id = holder_list_id db_session.add(page) diff --git a/batch/indexer_transfer.py b/batch/indexer_transfer.py index 84a495ff..12d20cb3 100644 --- a/batch/indexer_transfer.py +++ b/batch/indexer_transfer.py @@ -25,29 +25,30 @@ from eth_utils import to_checksum_address from sqlalchemy import create_engine -from sqlalchemy.orm import Session from sqlalchemy.exc import SQLAlchemyError +from sqlalchemy.orm import Session from web3.eth import Contract path = os.path.join(os.path.dirname(__file__), "../") sys.path.append(path) -from config import ( - INDEXER_SYNC_INTERVAL, - INDEXER_BLOCK_LOT_MAX_SIZE, - DATABASE_URL, - ZERO_ADDRESS -) +import batch_log + +from app.exceptions import ServiceUnavailableError from app.model.db import ( - Token, IDXTransfer, IDXTransferBlockNumber, - IDXTransferSourceEventType + IDXTransferSourceEventType, + Token, ) from app.utils.contract_utils import ContractUtils from app.utils.web3_utils import Web3Wrapper -from app.exceptions import ServiceUnavailableError -import batch_log +from config import ( + DATABASE_URL, + INDEXER_BLOCK_LOT_MAX_SIZE, + INDEXER_SYNC_INTERVAL, + ZERO_ADDRESS, +) process_name = "INDEXER-Transfer" LOG = batch_log.get_logger(process_name=process_name) @@ -90,18 +91,17 @@ def sync_new_logs(self): self.__sync_all( db_session=db_session, block_from=_from_block + 1, - block_to=latest_block + block_to=latest_block, ) else: self.__sync_all( db_session=db_session, block_from=_from_block + 1, - block_to=latest_block + block_to=latest_block, ) self.__set_idx_transfer_block_number( - db_session=db_session, - block_number=latest_block + db_session=db_session, block_number=latest_block ) db_session.commit() except Exception: @@ -114,41 +114,44 @@ def sync_new_logs(self): def __get_token_list(self, db_session: Session): issued_token_address_list: tuple[str, ...] = tuple( [ - record[0] for record in ( - db_session.query(Token.token_address).filter(Token.token_status == 1).all() + record[0] + for record in ( + db_session.query(Token.token_address) + .filter(Token.token_status == 1) + .all() ) ] ) loaded_token_address_list: tuple[str, ...] = tuple(self.token_list.keys()) - load_required_address_list = list(set(issued_token_address_list) ^ set(loaded_token_address_list)) + load_required_address_list = list( + set(issued_token_address_list) ^ set(loaded_token_address_list) + ) if not load_required_address_list: # If there are no additional tokens to load, skip process return load_required_token_list: list[Type[Token]] = ( - db_session.query(Token). - filter(Token.token_status == 1). - filter(Token.token_address.in_(load_required_address_list)).all() + db_session.query(Token) + .filter(Token.token_status == 1) + .filter(Token.token_address.in_(load_required_address_list)) + .all() ) for load_required_token in load_required_token_list: token_contract = web3.eth.contract( - address=load_required_token.token_address, - abi=load_required_token.abi + address=load_required_token.token_address, abi=load_required_token.abi ) self.token_list[load_required_token.token_address] = token_contract def __get_idx_transfer_block_number(self, db_session: Session): - _idx_transfer_block_number = db_session.query(IDXTransferBlockNumber). \ - first() + _idx_transfer_block_number = db_session.query(IDXTransferBlockNumber).first() if _idx_transfer_block_number is None: return 0 else: return _idx_transfer_block_number.latest_block_number def __set_idx_transfer_block_number(self, db_session: Session, block_number: int): - _idx_transfer_block_number = db_session.query(IDXTransferBlockNumber). \ - first() + _idx_transfer_block_number = db_session.query(IDXTransferBlockNumber).first() if _idx_transfer_block_number is None: _idx_transfer_block_number = IDXTransferBlockNumber() @@ -174,12 +177,14 @@ def __sync_transfer(self, db_session: Session, block_from: int, block_to: int): contract=token, event="Transfer", block_from=block_from, - block_to=block_to + block_to=block_to, ) for event in events: args = event["args"] transaction_hash = event["transactionHash"].hex() - block_timestamp = datetime.utcfromtimestamp(web3.eth.get_block(event["blockNumber"])["timestamp"]) + block_timestamp = datetime.utcfromtimestamp( + web3.eth.get_block(event["blockNumber"])["timestamp"] + ) if args["value"] > sys.maxsize: pass else: @@ -192,7 +197,7 @@ def __sync_transfer(self, db_session: Session, block_from: int, block_to: int): amount=args["value"], source_event=IDXTransferSourceEventType.TRANSFER, data_str=None, - block_timestamp=block_timestamp + block_timestamp=block_timestamp, ) except Exception: raise @@ -211,12 +216,14 @@ def __sync_unlock(self, db_session: Session, block_from: int, block_to: int): contract=token, event="Unlock", block_from=block_from, - block_to=block_to + block_to=block_to, ) for event in events: args = event["args"] transaction_hash = event["transactionHash"].hex() - block_timestamp = datetime.utcfromtimestamp(web3.eth.get_block(event["blockNumber"])["timestamp"]) + block_timestamp = datetime.utcfromtimestamp( + web3.eth.get_block(event["blockNumber"])["timestamp"] + ) if args["value"] > sys.maxsize: pass else: @@ -233,21 +240,23 @@ def __sync_unlock(self, db_session: Session, block_from: int, block_to: int): amount=args["value"], source_event=IDXTransferSourceEventType.UNLOCK, data_str=data_str, - block_timestamp=block_timestamp + block_timestamp=block_timestamp, ) except Exception: raise @staticmethod - def __sink_on_transfer(db_session: Session, - transaction_hash: str, - token_address: str, - from_address: str, - to_address: str, - amount: int, - source_event: IDXTransferSourceEventType, - data_str: str | None, - block_timestamp: datetime): + def __sink_on_transfer( + db_session: Session, + transaction_hash: str, + token_address: str, + from_address: str, + to_address: str, + amount: int, + source_event: IDXTransferSourceEventType, + data_str: str | None, + block_timestamp: datetime, + ): if data_str is not None: try: data = json.loads(data_str) diff --git a/batch/indexer_transfer_approval.py b/batch/indexer_transfer_approval.py index 8ae5b183..a1d4ea34 100644 --- a/batch/indexer_transfer_approval.py +++ b/batch/indexer_transfer_approval.py @@ -20,39 +20,35 @@ import sys import time import uuid -from datetime import ( - datetime, - timezone -) +from datetime import datetime, timezone +from typing import Optional, Type + from sqlalchemy import create_engine -from sqlalchemy.orm import Session from sqlalchemy.exc import SQLAlchemyError -from typing import ( - Optional, - Type -) +from sqlalchemy.orm import Session from web3.eth import Contract path = os.path.join(os.path.dirname(__file__), "../") sys.path.append(path) -from config import ( - INDEXER_SYNC_INTERVAL, - DATABASE_URL, - ZERO_ADDRESS, - INDEXER_BLOCK_LOT_MAX_SIZE -) +import batch_log + +from app.exceptions import ServiceUnavailableError from app.model.db import ( - Token, IDXTransferApproval, IDXTransferApprovalBlockNumber, Notification, - NotificationType + NotificationType, + Token, ) from app.utils.contract_utils import ContractUtils from app.utils.web3_utils import Web3Wrapper -from app.exceptions import ServiceUnavailableError -import batch_log +from config import ( + DATABASE_URL, + INDEXER_BLOCK_LOT_MAX_SIZE, + INDEXER_SYNC_INTERVAL, + ZERO_ADDRESS, +) process_name = "INDEXER-TransferApproval" LOG = batch_log.get_logger(process_name=process_name) @@ -90,7 +86,9 @@ def sync_new_logs(self): # Get from_block_number and to_block_number for contract event filter latest_block = web3.eth.block_number - _from_block = self.__get_idx_transfer_approval_block_number(db_session=db_session) + _from_block = self.__get_idx_transfer_approval_block_number( + db_session=db_session + ) _to_block = _from_block + INDEXER_BLOCK_LOT_MAX_SIZE # Skip processing if the latest block is not counted up @@ -112,18 +110,17 @@ def sync_new_logs(self): self.__sync_all( db_session=db_session, block_from=_from_block + 1, - block_to=latest_block + block_to=latest_block, ) else: self.__sync_all( db_session=db_session, block_from=_from_block + 1, - block_to=latest_block + block_to=latest_block, ) self.__set_idx_transfer_approval_block_number( - db_session=db_session, - block_number=latest_block + db_session=db_session, block_number=latest_block ) db_session.commit() finally: @@ -135,25 +132,28 @@ def __get_contract_list(self, db_session: Session): issued_token_address_list: tuple[str, ...] = tuple( [ - record[0] for record in ( - db_session.query(Token.token_address). - filter(Token.token_status == 1).all() + record[0] + for record in ( + db_session.query(Token.token_address) + .filter(Token.token_status == 1) + .all() ) ] ) loaded_token_address_list: tuple[str, ...] = tuple(self.token_list.keys()) - load_required_address_list = list(set(issued_token_address_list) ^ set(loaded_token_address_list)) + load_required_address_list = list( + set(issued_token_address_list) ^ set(loaded_token_address_list) + ) load_required_token_list: list[Type[Token]] = ( - db_session.query(Token). - filter(Token.token_status == 1). - filter(Token.token_address.in_(load_required_address_list)). - all() + db_session.query(Token) + .filter(Token.token_status == 1) + .filter(Token.token_address.in_(load_required_address_list)) + .all() ) for load_required_token in load_required_token_list: token_contract = web3.eth.contract( - address=load_required_token.token_address, - abi=load_required_token.abi + address=load_required_token.token_address, abi=load_required_token.abi ) self.token_list[load_required_token.token_address] = token_contract @@ -163,7 +163,7 @@ def __get_contract_list(self, db_session: Session): contract=token_contract, function_name="tradableExchange", args=(), - default_returns=ZERO_ADDRESS + default_returns=ZERO_ADDRESS, ) if tradable_exchange_address != ZERO_ADDRESS: _exchange_list_tmp.append(tradable_exchange_address) @@ -172,21 +172,25 @@ def __get_contract_list(self, db_session: Session): for _exchange_address in list(set(_exchange_list_tmp)): exchange_contract = ContractUtils.get_contract( contract_name="IbetSecurityTokenEscrow", - contract_address=_exchange_address + contract_address=_exchange_address, ) self.exchange_list.append(exchange_contract) def __get_idx_transfer_approval_block_number(self, db_session: Session): - _idx_transfer_approval_block_number = db_session.query(IDXTransferApprovalBlockNumber). \ - first() + _idx_transfer_approval_block_number = db_session.query( + IDXTransferApprovalBlockNumber + ).first() if _idx_transfer_approval_block_number is None: return 0 else: return _idx_transfer_approval_block_number.latest_block_number - def __set_idx_transfer_approval_block_number(self, db_session: Session, block_number: int): - _idx_transfer_approval_block_number = db_session.query(IDXTransferApprovalBlockNumber). \ - first() + def __set_idx_transfer_approval_block_number( + self, db_session: Session, block_number: int + ): + _idx_transfer_approval_block_number = db_session.query( + IDXTransferApprovalBlockNumber + ).first() if _idx_transfer_approval_block_number is None: _idx_transfer_approval_block_number = IDXTransferApprovalBlockNumber() @@ -203,7 +207,9 @@ def __sync_all(self, db_session: Session, block_from: int, block_to: int): self.__sync_exchange_escrow_finished(db_session, block_from, block_to) self.__sync_exchange_approve_transfer(db_session, block_from, block_to) - def __sync_token_apply_for_transfer(self, db_session: Session, block_from, block_to): + def __sync_token_apply_for_transfer( + self, db_session: Session, block_from, block_to + ): """Sync ApplyForTransfer Events of Tokens :param db_session: database session @@ -217,7 +223,7 @@ def __sync_token_apply_for_transfer(self, db_session: Session, block_from, block contract=token, event="ApplyForTransfer", block_from=block_from, - block_to=block_to + block_to=block_to, ) for event in events: args = event["args"] @@ -236,7 +242,7 @@ def __sync_token_apply_for_transfer(self, db_session: Session, block_from, block to_address=args.get("to", ZERO_ADDRESS), amount=args.get("value"), optional_data_applicant=args.get("data"), - block_timestamp=block_timestamp + block_timestamp=block_timestamp, ) self.__register_notification( db_session=db_session, @@ -244,7 +250,7 @@ def __sync_token_apply_for_transfer(self, db_session: Session, block_from, block token_address=token.address, exchange_address=ZERO_ADDRESS, application_id=args.get("index"), - notice_code=0 + notice_code=0, ) except Exception: LOG.exception("An exception occurred during event synchronization") @@ -263,7 +269,7 @@ def __sync_token_cancel_transfer(self, db_session: Session, block_from, block_to contract=token, event="CancelTransfer", block_from=block_from, - block_to=block_to + block_to=block_to, ) for event in events: args = event["args"] @@ -282,7 +288,7 @@ def __sync_token_cancel_transfer(self, db_session: Session, block_from, block_to token_address=token.address, exchange_address=ZERO_ADDRESS, application_id=args.get("index"), - notice_code=1 + notice_code=1, ) except Exception: LOG.exception("An exception occurred during event synchronization") @@ -301,7 +307,7 @@ def __sync_token_approve_transfer(self, db_session: Session, block_from, block_t contract=token, event="ApproveTransfer", block_from=block_from, - block_to=block_to + block_to=block_to, ) for event in events: args = event["args"] @@ -315,7 +321,7 @@ def __sync_token_approve_transfer(self, db_session: Session, block_from, block_t from_address=args.get("from", ZERO_ADDRESS), to_address=args.get("to", ZERO_ADDRESS), optional_data_approver=args.get("data"), - block_timestamp=block_timestamp + block_timestamp=block_timestamp, ) self.__register_notification( db_session=db_session, @@ -323,12 +329,14 @@ def __sync_token_approve_transfer(self, db_session: Session, block_from, block_t token_address=token.address, exchange_address=ZERO_ADDRESS, application_id=args.get("index"), - notice_code=2 + notice_code=2, ) except Exception: LOG.exception("An exception occurred during event synchronization") - def __sync_exchange_apply_for_transfer(self, db_session: Session, block_from, block_to): + def __sync_exchange_apply_for_transfer( + self, db_session: Session, block_from, block_to + ): """Sync ApplyForTransfer events of exchanges :param db_session: database session @@ -342,7 +350,7 @@ def __sync_exchange_apply_for_transfer(self, db_session: Session, block_from, bl contract=exchange, event="ApplyForTransfer", block_from=block_from, - block_to=block_to + block_to=block_to, ) for event in events: args = event["args"] @@ -361,7 +369,7 @@ def __sync_exchange_apply_for_transfer(self, db_session: Session, block_from, bl to_address=args.get("to", ZERO_ADDRESS), amount=args.get("value"), optional_data_applicant=args.get("data"), - block_timestamp=block_timestamp + block_timestamp=block_timestamp, ) self.__register_notification( db_session=db_session, @@ -369,12 +377,14 @@ def __sync_exchange_apply_for_transfer(self, db_session: Session, block_from, bl token_address=args.get("token", ZERO_ADDRESS), exchange_address=exchange.address, application_id=args.get("escrowId"), - notice_code=0 + notice_code=0, ) except Exception: LOG.exception("An exception occurred during event synchronization") - def __sync_exchange_cancel_transfer(self, db_session: Session, block_from, block_to): + def __sync_exchange_cancel_transfer( + self, db_session: Session, block_from, block_to + ): """Sync CancelTransfer events of exchanges :param db_session: database session @@ -388,7 +398,7 @@ def __sync_exchange_cancel_transfer(self, db_session: Session, block_from, block contract=exchange, event="CancelTransfer", block_from=block_from, - block_to=block_to + block_to=block_to, ) for event in events: args = event["args"] @@ -407,12 +417,14 @@ def __sync_exchange_cancel_transfer(self, db_session: Session, block_from, block token_address=args.get("token", ZERO_ADDRESS), exchange_address=exchange.address, application_id=args.get("escrowId"), - notice_code=1 + notice_code=1, ) except Exception: LOG.exception("An exception occurred during event synchronization") - def __sync_exchange_escrow_finished(self, db_session: Session, block_from: int, block_to: int): + def __sync_exchange_escrow_finished( + self, db_session: Session, block_from: int, block_to: int + ): """Sync EscrowFinished events of exchanges :param db_session: ORM session @@ -427,7 +439,7 @@ def __sync_exchange_escrow_finished(self, db_session: Session, block_from: int, event="EscrowFinished", block_from=block_from, block_to=block_to, - argument_filters={"transferApprovalRequired": True} + argument_filters={"transferApprovalRequired": True}, ) for event in events: args = event["args"] @@ -438,7 +450,7 @@ def __sync_exchange_escrow_finished(self, db_session: Session, block_from: int, exchange_address=exchange.address, application_id=args.get("escrowId"), from_address=args.get("sender", ZERO_ADDRESS), - to_address=args.get("recipient", ZERO_ADDRESS) + to_address=args.get("recipient", ZERO_ADDRESS), ) self.__register_notification( db_session=db_session, @@ -446,12 +458,14 @@ def __sync_exchange_escrow_finished(self, db_session: Session, block_from: int, token_address=args.get("token", ZERO_ADDRESS), exchange_address=exchange.address, application_id=args.get("escrowId"), - notice_code=3 + notice_code=3, ) except Exception: LOG.exception("An exception occurred during event synchronization") - def __sync_exchange_approve_transfer(self, db_session: Session, block_from: int, block_to: int): + def __sync_exchange_approve_transfer( + self, db_session: Session, block_from: int, block_to: int + ): """Sync ApproveTransfer events of exchanges :param db_session: ORM session @@ -465,7 +479,7 @@ def __sync_exchange_approve_transfer(self, db_session: Session, block_from: int, contract=exchange, event="ApproveTransfer", block_from=block_from, - block_to=block_to + block_to=block_to, ) for event in events: args = event["args"] @@ -477,7 +491,7 @@ def __sync_exchange_approve_transfer(self, db_session: Session, block_from: int, exchange_address=exchange.address, application_id=args.get("escrowId"), optional_data_approver=args.get("data"), - block_timestamp=block_timestamp + block_timestamp=block_timestamp, ) self.__register_notification( db_session=db_session, @@ -485,30 +499,35 @@ def __sync_exchange_approve_transfer(self, db_session: Session, block_from: int, token_address=args.get("token", ZERO_ADDRESS), exchange_address=exchange.address, application_id=args.get("escrowId"), - notice_code=2 + notice_code=2, ) except Exception: LOG.exception("An exception occurred during event synchronization") - def __register_notification(self, - db_session: Session, - transaction_hash, - token_address, - exchange_address, - application_id, - notice_code): - + def __register_notification( + self, + db_session: Session, + transaction_hash, + token_address, + exchange_address, + application_id, + notice_code, + ): # Get IDXTransferApproval's Sequence Id - transfer_approval = db_session.query(IDXTransferApproval). \ - filter(IDXTransferApproval.token_address == token_address). \ - filter(IDXTransferApproval.exchange_address == exchange_address). \ - filter(IDXTransferApproval.application_id == application_id). \ - first() + transfer_approval = ( + db_session.query(IDXTransferApproval) + .filter(IDXTransferApproval.token_address == token_address) + .filter(IDXTransferApproval.exchange_address == exchange_address) + .filter(IDXTransferApproval.application_id == application_id) + .first() + ) if transfer_approval is not None: # Get issuer address - token: Token | None = db_session.query(Token). \ - filter(Token.token_address == token_address). \ - first() + token: Token | None = ( + db_session.query(Token) + .filter(Token.token_address == token_address) + .first() + ) sender = web3.eth.get_transaction(transaction_hash)["from"] if token is not None: if token.issuer_address != sender: # Operate from other than issuer @@ -519,16 +538,18 @@ def __register_notification(self, code=notice_code, token_address=token_address, token_type=token.type, - id=transfer_approval.id + id=transfer_approval.id, ) - elif notice_code == 1 or notice_code == 3: # CancelTransfer or EscrowFinished + elif ( + notice_code == 1 or notice_code == 3 + ): # CancelTransfer or EscrowFinished self.__sink_on_info_notification( db_session=db_session, issuer_address=token.issuer_address, code=notice_code, token_address=token_address, token_type=token.type, - id=transfer_approval.id + id=transfer_approval.id, ) else: # Operate from issuer if notice_code == 2: # ApproveTransfer @@ -538,7 +559,7 @@ def __register_notification(self, code=notice_code, token_address=token_address, token_type=token.type, - id=transfer_approval.id + id=transfer_approval.id, ) @staticmethod @@ -547,17 +568,19 @@ def __get_block_timestamp(event) -> int: return block_timestamp @staticmethod - def __sink_on_transfer_approval(db_session: Session, - event_type: str, - token_address: str, - exchange_address: Optional[str], - application_id: int, - from_address: Optional[str] = None, - to_address: Optional[str] = None, - amount: Optional[int] = None, - optional_data_applicant: Optional[str] = None, - optional_data_approver: Optional[str] = None, - block_timestamp: Optional[int] = None): + def __sink_on_transfer_approval( + db_session: Session, + event_type: str, + token_address: str, + exchange_address: Optional[str], + application_id: int, + from_address: Optional[str] = None, + to_address: Optional[str] = None, + amount: Optional[int] = None, + optional_data_applicant: Optional[str] = None, + optional_data_approver: Optional[str] = None, + block_timestamp: Optional[int] = None, + ): """Update Transfer Approval data in DB :param db_session: database session @@ -573,11 +596,13 @@ def __sink_on_transfer_approval(db_session: Session, :param block_timestamp: block timestamp :return: None """ - transfer_approval = db_session.query(IDXTransferApproval). \ - filter(IDXTransferApproval.token_address == token_address). \ - filter(IDXTransferApproval.exchange_address == exchange_address). \ - filter(IDXTransferApproval.application_id == application_id). \ - first() + transfer_approval = ( + db_session.query(IDXTransferApproval) + .filter(IDXTransferApproval.token_address == token_address) + .filter(IDXTransferApproval.exchange_address == exchange_address) + .filter(IDXTransferApproval.application_id == application_id) + .first() + ) if event_type == "ApplyFor": if transfer_approval is None: transfer_approval = IDXTransferApproval() @@ -589,14 +614,12 @@ def __sink_on_transfer_approval(db_session: Session, transfer_approval.amount = amount try: transfer_approval.application_datetime = datetime.fromtimestamp( - float(optional_data_applicant), - tz=timezone.utc + float(optional_data_applicant), tz=timezone.utc ) except ValueError: transfer_approval.application_datetime = None transfer_approval.application_blocktimestamp = datetime.fromtimestamp( - block_timestamp, - tz=timezone.utc + block_timestamp, tz=timezone.utc ) elif event_type == "Cancel": if transfer_approval is not None: @@ -608,25 +631,25 @@ def __sink_on_transfer_approval(db_session: Session, if transfer_approval is not None: try: transfer_approval.approval_datetime = datetime.fromtimestamp( - float(optional_data_approver), - tz=timezone.utc + float(optional_data_approver), tz=timezone.utc ) except ValueError: transfer_approval.approval_datetime = None transfer_approval.approval_blocktimestamp = datetime.fromtimestamp( - block_timestamp, - tz=timezone.utc + block_timestamp, tz=timezone.utc ) transfer_approval.transfer_approved = True db_session.merge(transfer_approval) @staticmethod - def __sink_on_info_notification(db_session: Session, - issuer_address: str, - code: int, - token_address: str, - token_type: str, - id: int): + def __sink_on_info_notification( + db_session: Session, + issuer_address: str, + code: int, + token_address: str, + token_type: str, + id: int, + ): notification = Notification() notification.notice_id = uuid.uuid4() notification.issuer_address = issuer_address @@ -636,7 +659,7 @@ def __sink_on_info_notification(db_session: Session, notification.metainfo = { "token_address": token_address, "token_type": token_type, - "id": id + "id": id, } db_session.add(notification) diff --git a/batch/processor_batch_issue_redeem.py b/batch/processor_batch_issue_redeem.py index 10daea83..65a5929e 100644 --- a/batch/processor_batch_issue_redeem.py +++ b/batch/processor_batch_issue_redeem.py @@ -20,47 +20,43 @@ import sys import time import uuid -from typing import ( - List, - Type -) +from typing import List, Type from eth_keyfile import decode_keyfile_json from sqlalchemy import create_engine from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.orm import Session -path = os.path.join(os.path.dirname(__file__), '../') +path = os.path.join(os.path.dirname(__file__), "../") sys.path.append(path) -from config import DATABASE_URL -from app.model.blockchain import ( - IbetStraightBondContract, - IbetShareContract -) -from app.model.db import ( - BatchIssueRedeemUpload, - BatchIssueRedeem, - BatchIssueRedeemProcessingCategory, - TokenType, - Account, - Notification, - NotificationType -) +import batch_log + +from app.exceptions import ContractRevertError, SendTransactionError +from app.model.blockchain import IbetShareContract, IbetStraightBondContract from app.model.blockchain.tx_params.ibet_share import ( AdditionalIssueParams as IbetShareAdditionalIssueParams, - RedeemParams as IbetShareRedeemParams +) +from app.model.blockchain.tx_params.ibet_share import ( + RedeemParams as IbetShareRedeemParams, ) from app.model.blockchain.tx_params.ibet_straight_bond import ( AdditionalIssueParams as IbetStraightBondAdditionalIssueParams, - RedeemParams as IbetStraightBondRedeemParams ) -from app.utils.e2ee_utils import E2EEUtils -from app.exceptions import ( - SendTransactionError, - ContractRevertError +from app.model.blockchain.tx_params.ibet_straight_bond import ( + RedeemParams as IbetStraightBondRedeemParams, ) -import batch_log +from app.model.db import ( + Account, + BatchIssueRedeem, + BatchIssueRedeemProcessingCategory, + BatchIssueRedeemUpload, + Notification, + NotificationType, + TokenType, +) +from app.utils.e2ee_utils import E2EEUtils +from config import DATABASE_URL """ [PROCESSOR-Batch-Issue-Redeem] @@ -75,20 +71,23 @@ class Processor: - def process(self): db_session = Session(autocommit=False, autoflush=True, bind=db_engine) try: - upload_list: List[Type[BatchIssueRedeemUpload]] = db_session.query(BatchIssueRedeemUpload). \ - filter(BatchIssueRedeemUpload.processed == False). \ - all() + upload_list: List[Type[BatchIssueRedeemUpload]] = ( + db_session.query(BatchIssueRedeemUpload) + .filter(BatchIssueRedeemUpload.processed == False) + .all() + ) for upload in upload_list: LOG.info(f"Process start: upload_id={upload.upload_id}") # Get issuer's private key - issuer_account = db_session.query(Account). \ - filter(Account.issuer_address == upload.issuer_address). \ - first() + issuer_account = ( + db_session.query(Account) + .filter(Account.issuer_address == upload.issuer_address) + .first() + ) if issuer_account is None: LOG.exception("Issuer account does not exist") self.__sink_on_notification( @@ -99,7 +98,7 @@ def process(self): code=1, upload_category=upload.category, upload_id=upload.upload_id, - error_data_id_list=[] + error_data_id_list=[], ) upload.processed = True db_session.commit() @@ -108,7 +107,9 @@ def process(self): try: issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer_account.keyfile, - password=E2EEUtils.decrypt(issuer_account.eoa_password).encode("utf-8") + password=E2EEUtils.decrypt(issuer_account.eoa_password).encode( + "utf-8" + ), ) except (ValueError, TypeError): LOG.exception("Failed to decode keyfile") @@ -120,62 +121,86 @@ def process(self): code=2, upload_category=upload.category, upload_id=upload.upload_id, - error_data_id_list=[] + error_data_id_list=[], ) upload.processed = True db_session.commit() continue # Batch processing - batch_data_list: List[BatchIssueRedeem] = db_session.query(BatchIssueRedeem). \ - filter(BatchIssueRedeem.upload_id == upload.upload_id). \ - filter(BatchIssueRedeem.status == 0). \ - all() + batch_data_list: List[BatchIssueRedeem] = ( + db_session.query(BatchIssueRedeem) + .filter(BatchIssueRedeem.upload_id == upload.upload_id) + .filter(BatchIssueRedeem.status == 0) + .all() + ) for batch_data in batch_data_list: tx_hash = "-" try: if upload.token_type == TokenType.IBET_STRAIGHT_BOND.value: - if upload.category == BatchIssueRedeemProcessingCategory.ISSUE.value: - tx_hash = IbetStraightBondContract(upload.token_address).additional_issue( + if ( + upload.category + == BatchIssueRedeemProcessingCategory.ISSUE.value + ): + tx_hash = IbetStraightBondContract( + upload.token_address + ).additional_issue( data=IbetStraightBondAdditionalIssueParams( account_address=batch_data.account_address, - amount=batch_data.amount + amount=batch_data.amount, ), tx_from=upload.issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) - elif upload.category == BatchIssueRedeemProcessingCategory.REDEEM.value: - tx_hash = IbetStraightBondContract(upload.token_address).redeem( + elif ( + upload.category + == BatchIssueRedeemProcessingCategory.REDEEM.value + ): + tx_hash = IbetStraightBondContract( + upload.token_address + ).redeem( data=IbetStraightBondRedeemParams( account_address=batch_data.account_address, - amount=batch_data.amount + amount=batch_data.amount, ), tx_from=upload.issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) elif upload.token_type == TokenType.IBET_SHARE.value: - if upload.category == BatchIssueRedeemProcessingCategory.ISSUE.value: - tx_hash = IbetShareContract(upload.token_address).additional_issue( + if ( + upload.category + == BatchIssueRedeemProcessingCategory.ISSUE.value + ): + tx_hash = IbetShareContract( + upload.token_address + ).additional_issue( data=IbetShareAdditionalIssueParams( account_address=batch_data.account_address, - amount=batch_data.amount + amount=batch_data.amount, ), tx_from=upload.issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) - elif upload.category == BatchIssueRedeemProcessingCategory.REDEEM.value: - tx_hash = IbetShareContract(upload.token_address).redeem( + elif ( + upload.category + == BatchIssueRedeemProcessingCategory.REDEEM.value + ): + tx_hash = IbetShareContract( + upload.token_address + ).redeem( data=IbetShareRedeemParams( account_address=batch_data.account_address, - amount=batch_data.amount + amount=batch_data.amount, ), tx_from=upload.issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) LOG.debug(f"Transaction sent successfully: {tx_hash}") batch_data.status = 1 except ContractRevertError as e: - LOG.warning(f"Transaction reverted: upload_id=<{batch_data.upload_id}> error_code:<{e.code}> error_msg:<{e.message}>") + LOG.warning( + f"Transaction reverted: upload_id=<{batch_data.upload_id}> error_code:<{e.code}> error_msg:<{e.message}>" + ) batch_data.status = 2 except SendTransactionError: LOG.warning(f"Failed to send transaction: {tx_hash}") @@ -184,10 +209,12 @@ def process(self): db_session.commit() # commit for each data # Process failed data - failed_batch_data_list: List[BatchIssueRedeem] = db_session.query(BatchIssueRedeem). \ - filter(BatchIssueRedeem.upload_id == upload.upload_id). \ - filter(BatchIssueRedeem.status == 2). \ - all() + failed_batch_data_list: List[BatchIssueRedeem] = ( + db_session.query(BatchIssueRedeem) + .filter(BatchIssueRedeem.upload_id == upload.upload_id) + .filter(BatchIssueRedeem.status == 2) + .all() + ) error_data_id_list = [data.id for data in failed_batch_data_list] # 0: Success, 3: failed @@ -200,7 +227,7 @@ def process(self): code=code, upload_category=upload.category, upload_id=upload.upload_id, - error_data_id_list=error_data_id_list + error_data_id_list=error_data_id_list, ) # Update to processed upload.processed = True @@ -211,14 +238,16 @@ def process(self): db_session.close() @staticmethod - def __sink_on_notification(db_session: Session, - issuer_address: str, - token_address: str, - token_type: str, - upload_category: str, - code: int, - upload_id: str, - error_data_id_list: list[int]): + def __sink_on_notification( + db_session: Session, + issuer_address: str, + token_address: str, + token_type: str, + upload_category: str, + code: int, + upload_id: str, + error_data_id_list: list[int], + ): notification = Notification() notification.notice_id = uuid.uuid4() notification.issuer_address = issuer_address @@ -230,7 +259,7 @@ def __sink_on_notification(db_session: Session, "upload_id": upload_id, "error_data_id": error_data_id_list, "token_address": token_address, - "token_type": token_type + "token_type": token_type, } db_session.add(notification) diff --git a/batch/processor_batch_register_personal_info.py b/batch/processor_batch_register_personal_info.py index 4dfb49be..ed24dad5 100644 --- a/batch/processor_batch_register_personal_info.py +++ b/batch/processor_batch_register_personal_info.py @@ -17,47 +17,50 @@ SPDX-License-Identifier: Apache-2.0 """ from __future__ import annotations + import os import sys +import threading import time import uuid -import threading from sqlalchemy import create_engine -from sqlalchemy.orm import Session from sqlalchemy.exc import SQLAlchemyError +from sqlalchemy.orm import Session path = os.path.join(os.path.dirname(__file__), "../") sys.path.append(path) -from config import ( - DATABASE_URL, - ZERO_ADDRESS, - BATCH_REGISTER_PERSONAL_INFO_WORKER_LOT_SIZE, - BATCH_REGISTER_PERSONAL_INFO_INTERVAL, - BATCH_REGISTER_PERSONAL_INFO_WORKER_COUNT +import batch_log + +from app.exceptions import ( + ContractRevertError, + SendTransactionError, + ServiceUnavailableError, +) +from app.model.blockchain import ( + IbetShareContract, + IbetStraightBondContract, + PersonalInfoContract, ) from app.model.db import ( Account, - Token, - TokenType, + BatchRegisterPersonalInfo, + BatchRegisterPersonalInfoUpload, + BatchRegisterPersonalInfoUploadStatus, Notification, NotificationType, - BatchRegisterPersonalInfoUpload, - BatchRegisterPersonalInfo, - BatchRegisterPersonalInfoUploadStatus -) -from app.model.blockchain import ( - IbetStraightBondContract, - IbetShareContract, PersonalInfoContract + Token, + TokenType, ) from app.utils.web3_utils import Web3Wrapper -from app.exceptions import ( - SendTransactionError, - ServiceUnavailableError, - ContractRevertError +from config import ( + BATCH_REGISTER_PERSONAL_INFO_INTERVAL, + BATCH_REGISTER_PERSONAL_INFO_WORKER_COUNT, + BATCH_REGISTER_PERSONAL_INFO_WORKER_LOT_SIZE, + DATABASE_URL, + ZERO_ADDRESS, ) -import batch_log """ [PROCESSOR-Batch-Register-Personal-Info] @@ -83,31 +86,41 @@ def __init__(self, thread_num): def process(self): db_session = Session(autocommit=False, autoflush=True, bind=db_engine) try: - upload_list: list[BatchRegisterPersonalInfoUpload] = self.__get_uploads(db_session=db_session) + upload_list: list[BatchRegisterPersonalInfoUpload] = self.__get_uploads( + db_session=db_session + ) if len(upload_list) < 1: return for _upload in upload_list: - LOG.info(f"<{self.thread_num}> Process start: upload_id={_upload.upload_id}") + LOG.info( + f"<{self.thread_num}> Process start: upload_id={_upload.upload_id}" + ) # Get issuer's private key - issuer_account: Account | None = db_session.query(Account).\ - filter(Account.issuer_address == _upload.issuer_address).\ - first() - if issuer_account is None: # If issuer does not exist, update the status of the upload to ERROR - LOG.warning(f"Issuer of the upload_id:{_upload.upload_id} does not exist") + issuer_account: Account | None = ( + db_session.query(Account) + .filter(Account.issuer_address == _upload.issuer_address) + .first() + ) + if ( + issuer_account is None + ): # If issuer does not exist, update the status of the upload to ERROR + LOG.warning( + f"Issuer of the upload_id:{_upload.upload_id} does not exist" + ) self.__sink_on_finish_upload_process( db_session=db_session, upload_id=_upload.upload_id, - status=BatchRegisterPersonalInfoUploadStatus.FAILED.value + status=BatchRegisterPersonalInfoUploadStatus.FAILED.value, ) self.__sink_on_error_notification( db_session=db_session, issuer_address=_upload.issuer_address, code=0, upload_id=_upload.upload_id, - error_registration_id=[] + error_registration_id=[], ) db_session.commit() self.__release_processing_issuer(_upload.upload_id) @@ -115,90 +128,91 @@ def process(self): # Load PersonalInfo Contract accessor self.__load_personal_info_contract_accessor( - db_session=db_session, - issuer_address=issuer_account.issuer_address + db_session=db_session, issuer_address=issuer_account.issuer_address ) # Register batch_data_list = self.__get_registration_data( - db_session=db_session, - upload_id=_upload.upload_id, - status=0 + db_session=db_session, upload_id=_upload.upload_id, status=0 ) for batch_data in batch_data_list: try: - personal_info_contract: PersonalInfoContract | None = \ - self.personal_info_contract_accessor_map.get(batch_data.token_address) + personal_info_contract: PersonalInfoContract | None = ( + self.personal_info_contract_accessor_map.get( + batch_data.token_address + ) + ) if personal_info_contract: tx_hash = personal_info_contract.register_info( account_address=batch_data.account_address, - data=batch_data.personal_info + data=batch_data.personal_info, ) LOG.debug(f"Transaction sent successfully: {tx_hash}") self.__sink_on_finish_register_process( - db_session=db_session, - record_id=batch_data.id, - status=1 + db_session=db_session, record_id=batch_data.id, status=1 ) else: - LOG.warning(f"Failed to get personal info contract: id=<{batch_data.id}>") + LOG.warning( + f"Failed to get personal info contract: id=<{batch_data.id}>" + ) self.__sink_on_finish_register_process( - db_session=db_session, - record_id=batch_data.id, - status=2 + db_session=db_session, record_id=batch_data.id, status=2 ) except ContractRevertError as e: - LOG.warning(f"Transaction reverted: id=<{batch_data.id}> error_code:<{e.code}> error_msg:<{e.message}>") + LOG.warning( + f"Transaction reverted: id=<{batch_data.id}> error_code:<{e.code}> error_msg:<{e.message}>" + ) self.__sink_on_finish_register_process( - db_session=db_session, - record_id=batch_data.id, - status=2 + db_session=db_session, record_id=batch_data.id, status=2 ) except SendTransactionError: LOG.warning(f"Failed to send transaction: id=<{batch_data.id}>") self.__sink_on_finish_register_process( - db_session=db_session, - record_id=batch_data.id, - status=2 + db_session=db_session, record_id=batch_data.id, status=2 ) db_session.commit() error_registration_list = self.__get_registration_data( - db_session=db_session, - upload_id=_upload.upload_id, - status=2 + db_session=db_session, upload_id=_upload.upload_id, status=2 ) if len(error_registration_list) == 0: # succeeded self.__sink_on_finish_upload_process( db_session=db_session, upload_id=_upload.upload_id, - status=BatchRegisterPersonalInfoUploadStatus.DONE.value + status=BatchRegisterPersonalInfoUploadStatus.DONE.value, ) else: # failed self.__sink_on_finish_upload_process( db_session=db_session, upload_id=_upload.upload_id, - status=BatchRegisterPersonalInfoUploadStatus.FAILED.value + status=BatchRegisterPersonalInfoUploadStatus.FAILED.value, ) - error_registration_id = [_error_registration.id for _error_registration in error_registration_list] + error_registration_id = [ + _error_registration.id + for _error_registration in error_registration_list + ] self.__sink_on_error_notification( db_session=db_session, issuer_address=_upload.issuer_address, code=2, upload_id=_upload.upload_id, - error_registration_id=error_registration_id + error_registration_id=error_registration_id, ) db_session.commit() self.__release_processing_issuer(_upload.upload_id) - LOG.info(f"<{self.thread_num}> Process end: upload_id={_upload.upload_id}") + LOG.info( + f"<{self.thread_num}> Process end: upload_id={_upload.upload_id}" + ) finally: self.personal_info_contract_accessor_map = {} db_session.close() - def __load_personal_info_contract_accessor(self, db_session: Session, issuer_address: str) -> None: + def __load_personal_info_contract_accessor( + self, db_session: Session, issuer_address: str + ) -> None: """Load PersonalInfo Contracts related to given issuer_address to memory :param db_session: database session @@ -207,10 +221,12 @@ def __load_personal_info_contract_accessor(self, db_session: Session, issuer_add """ self.personal_info_contract_accessor_map = {} - token_list = db_session.query(Token). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_status == 1). \ - all() + token_list = ( + db_session.query(Token) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_status == 1) + .all() + ) for token in token_list: if token.type == TokenType.IBET_SHARE.value: token_contract = IbetShareContract(token.token_address).get() @@ -221,13 +237,17 @@ def __load_personal_info_contract_accessor(self, db_session: Session, issuer_add contract_address = token_contract.personal_info_contract_address if contract_address != ZERO_ADDRESS: - self.personal_info_contract_accessor_map[token.token_address] = PersonalInfoContract( + self.personal_info_contract_accessor_map[ + token.token_address + ] = PersonalInfoContract( db=db_session, issuer_address=issuer_address, - contract_address=contract_address + contract_address=contract_address, ) - def __get_uploads(self, db_session: Session) -> list[BatchRegisterPersonalInfoUpload]: + def __get_uploads( + self, db_session: Session + ) -> list[BatchRegisterPersonalInfoUpload]: # NOTE: # - There is only one Issuer that is processed in the same thread. # - The maximum size to be processed at one time is the size defined @@ -246,19 +266,39 @@ def __get_uploads(self, db_session: Session) -> list[BatchRegisterPersonalInfoUp # Retrieve one target data # NOTE: Priority is given to issuers that are not being processed by other threads. - upload_1 = db_session.query(BatchRegisterPersonalInfoUpload). \ - filter(BatchRegisterPersonalInfoUpload.upload_id.notin_(locked_update_id)). \ - filter(BatchRegisterPersonalInfoUpload.status == BatchRegisterPersonalInfoUploadStatus.PENDING). \ - filter(BatchRegisterPersonalInfoUpload.issuer_address.notin_(exclude_issuer)). \ - order_by(BatchRegisterPersonalInfoUpload.created). \ - first() + upload_1 = ( + db_session.query(BatchRegisterPersonalInfoUpload) + .filter( + BatchRegisterPersonalInfoUpload.upload_id.notin_(locked_update_id) + ) + .filter( + BatchRegisterPersonalInfoUpload.status + == BatchRegisterPersonalInfoUploadStatus.PENDING + ) + .filter( + BatchRegisterPersonalInfoUpload.issuer_address.notin_( + exclude_issuer + ) + ) + .order_by(BatchRegisterPersonalInfoUpload.created) + .first() + ) if upload_1 is None: # Retrieve again for all issuers - upload_1 = db_session.query(BatchRegisterPersonalInfoUpload). \ - filter(BatchRegisterPersonalInfoUpload.upload_id.notin_(locked_update_id)). \ - filter(BatchRegisterPersonalInfoUpload.status == BatchRegisterPersonalInfoUploadStatus.PENDING). \ - order_by(BatchRegisterPersonalInfoUpload.created). \ - first() + upload_1 = ( + db_session.query(BatchRegisterPersonalInfoUpload) + .filter( + BatchRegisterPersonalInfoUpload.upload_id.notin_( + locked_update_id + ) + ) + .filter( + BatchRegisterPersonalInfoUpload.status + == BatchRegisterPersonalInfoUploadStatus.PENDING + ) + .order_by(BatchRegisterPersonalInfoUpload.created) + .first() + ) # Issuer to be processed => upload_1.issuer_address # Retrieve the data of the Issuer to be processed @@ -266,26 +306,43 @@ def __get_uploads(self, db_session: Session) -> list[BatchRegisterPersonalInfoUp if upload_1 is not None: upload_list = [upload_1] if BATCH_REGISTER_PERSONAL_INFO_WORKER_LOT_SIZE > 1: - upload_list = upload_list + db_session.query(BatchRegisterPersonalInfoUpload). \ - filter(BatchRegisterPersonalInfoUpload.upload_id.notin_(locked_update_id)). \ - filter(BatchRegisterPersonalInfoUpload.status == BatchRegisterPersonalInfoUploadStatus.PENDING). \ - filter(BatchRegisterPersonalInfoUpload.issuer_address == upload_1.issuer_address). \ - order_by(BatchRegisterPersonalInfoUpload.created). \ - offset(1). \ - limit(BATCH_REGISTER_PERSONAL_INFO_WORKER_LOT_SIZE - 1). \ - all() + upload_list = ( + upload_list + + db_session.query(BatchRegisterPersonalInfoUpload) + .filter( + BatchRegisterPersonalInfoUpload.upload_id.notin_( + locked_update_id + ) + ) + .filter( + BatchRegisterPersonalInfoUpload.status + == BatchRegisterPersonalInfoUploadStatus.PENDING + ) + .filter( + BatchRegisterPersonalInfoUpload.issuer_address + == upload_1.issuer_address + ) + .order_by(BatchRegisterPersonalInfoUpload.created) + .offset(1) + .limit(BATCH_REGISTER_PERSONAL_INFO_WORKER_LOT_SIZE - 1) + .all() + ) processing_issuer[self.thread_num] = {} for upload in upload_list: - processing_issuer[self.thread_num][upload.upload_id] = upload.issuer_address + processing_issuer[self.thread_num][ + upload.upload_id + ] = upload.issuer_address return upload_list @staticmethod def __get_registration_data(db_session: Session, upload_id: str, status: int): - register_list = db_session.query(BatchRegisterPersonalInfo). \ - filter(BatchRegisterPersonalInfo.upload_id == upload_id). \ - filter(BatchRegisterPersonalInfo.status == status). \ - all() + register_list = ( + db_session.query(BatchRegisterPersonalInfo) + .filter(BatchRegisterPersonalInfo.upload_id == upload_id) + .filter(BatchRegisterPersonalInfo.status == status) + .all() + ) return register_list def __release_processing_issuer(self, upload_id): @@ -293,30 +350,39 @@ def __release_processing_issuer(self, upload_id): processing_issuer[self.thread_num].pop(upload_id, None) @staticmethod - def __sink_on_finish_upload_process(db_session: Session, upload_id: str, status: str): - personal_info_register_upload_record: BatchRegisterPersonalInfoUpload | None = \ - db_session.query(BatchRegisterPersonalInfoUpload). \ - filter(BatchRegisterPersonalInfoUpload.upload_id == upload_id). \ - first() + def __sink_on_finish_upload_process( + db_session: Session, upload_id: str, status: str + ): + personal_info_register_upload_record: BatchRegisterPersonalInfoUpload | None = ( + db_session.query(BatchRegisterPersonalInfoUpload) + .filter(BatchRegisterPersonalInfoUpload.upload_id == upload_id) + .first() + ) if personal_info_register_upload_record is not None: personal_info_register_upload_record.status = status db_session.merge(personal_info_register_upload_record) @staticmethod - def __sink_on_finish_register_process(db_session: Session, record_id: int, status: int): - register_record = db_session.query(BatchRegisterPersonalInfo). \ - filter(BatchRegisterPersonalInfo.id == record_id). \ - first() + def __sink_on_finish_register_process( + db_session: Session, record_id: int, status: int + ): + register_record = ( + db_session.query(BatchRegisterPersonalInfo) + .filter(BatchRegisterPersonalInfo.id == record_id) + .first() + ) if register_record is not None: register_record.status = status db_session.merge(register_record) @staticmethod - def __sink_on_error_notification(db_session: Session, - issuer_address: str, - code: int, - upload_id: str, - error_registration_id: list[int]): + def __sink_on_error_notification( + db_session: Session, + issuer_address: str, + code: int, + upload_id: str, + error_registration_id: list[int], + ): notification = Notification() notification.notice_id = uuid.uuid4() notification.issuer_address = issuer_address @@ -325,7 +391,7 @@ def __sink_on_error_notification(db_session: Session, notification.code = code notification.metainfo = { "upload_id": upload_id, - "error_registration_id": error_registration_id + "error_registration_id": error_registration_id, } db_session.add(notification) @@ -344,20 +410,20 @@ def __sink_on_error_notification(db_session: Session, class Worker: - def __init__(self, thread_num: int): processor = Processor(thread_num=thread_num) self.processor = processor def run(self): - while True: try: self.processor.process() except ServiceUnavailableError: LOG.warning("An external service was unavailable") except SQLAlchemyError as sa_err: - LOG.error(f"A database error has occurred: code={sa_err.code}\n{sa_err}") + LOG.error( + f"A database error has occurred: code={sa_err.code}\n{sa_err}" + ) except Exception as ex: LOG.error(ex) err_bucket.append(ex) diff --git a/batch/processor_bulk_transfer.py b/batch/processor_bulk_transfer.py index b91cab1c..73b346ad 100644 --- a/batch/processor_bulk_transfer.py +++ b/batch/processor_bulk_transfer.py @@ -16,56 +16,51 @@ SPDX-License-Identifier: Apache-2.0 """ -from typing import ( - List, - Type -) import os import sys +import threading import time import uuid -import threading +from typing import List, Type from eth_keyfile import decode_keyfile_json from sqlalchemy import create_engine -from sqlalchemy.orm import Session from sqlalchemy.exc import SQLAlchemyError +from sqlalchemy.orm import Session path = os.path.join(os.path.dirname(__file__), "../") sys.path.append(path) -from config import ( - DATABASE_URL, - BULK_TRANSFER_INTERVAL, - BULK_TRANSFER_WORKER_COUNT, - BULK_TRANSFER_WORKER_LOT_SIZE +import batch_log + +from app.exceptions import ( + ContractRevertError, + SendTransactionError, + ServiceUnavailableError, +) +from app.model.blockchain import IbetShareContract, IbetStraightBondContract +from app.model.blockchain.tx_params.ibet_share import ( + TransferParams as IbetShareTransferParams, +) +from app.model.blockchain.tx_params.ibet_straight_bond import ( + TransferParams as IbetStraightBondTransferParams, ) -from app.utils.e2ee_utils import E2EEUtils from app.model.db import ( Account, - BulkTransferUpload, BulkTransfer, - TokenType, + BulkTransferUpload, Notification, - NotificationType -) -from app.model.blockchain import ( - IbetStraightBondContract, - IbetShareContract -) -from app.model.blockchain.tx_params.ibet_share import ( - TransferParams as IbetShareTransferParams -) -from app.model.blockchain.tx_params.ibet_straight_bond import ( - TransferParams as IbetStraightBondTransferParams + NotificationType, + TokenType, ) +from app.utils.e2ee_utils import E2EEUtils from app.utils.web3_utils import Web3Wrapper -from app.exceptions import ( - SendTransactionError, - ServiceUnavailableError, - ContractRevertError +from config import ( + BULK_TRANSFER_INTERVAL, + BULK_TRANSFER_WORKER_COUNT, + BULK_TRANSFER_WORKER_LOT_SIZE, + DATABASE_URL, ) -import batch_log """ [PROCESSOR-Bulk-Transfer] @@ -92,19 +87,25 @@ def process(self): return for _upload in upload_list: - LOG.info(f"<{self.thread_num}> Process start: upload_id={_upload.upload_id}") + LOG.info( + f"<{self.thread_num}> Process start: upload_id={_upload.upload_id}" + ) # Get issuer's private key try: - _account = db_session.query(Account). \ - filter(Account.issuer_address == _upload.issuer_address). \ - first() - if _account is None: # If issuer does not exist, update the status of the upload to ERROR - LOG.warning(f"Issuer of the upload_id:{_upload.upload_id} does not exist") + _account = ( + db_session.query(Account) + .filter(Account.issuer_address == _upload.issuer_address) + .first() + ) + if ( + _account is None + ): # If issuer does not exist, update the status of the upload to ERROR + LOG.warning( + f"Issuer of the upload_id:{_upload.upload_id} does not exist" + ) self.__sink_on_finish_upload_process( - db_session=db_session, - upload_id=_upload.upload_id, - status=2 + db_session=db_session, upload_id=_upload.upload_id, status=2 ) self.__sink_on_error_notification( db_session=db_session, @@ -112,7 +113,7 @@ def process(self): code=0, upload_id=_upload.upload_id, token_type=_upload.token_type, - error_transfer_id=[] + error_transfer_id=[], ) db_session.commit() self.__release_processing_issuer(_upload.upload_id) @@ -121,16 +122,15 @@ def process(self): decrypt_password = E2EEUtils.decrypt(_account.eoa_password) private_key = decode_keyfile_json( raw_keyfile_json=keyfile_json, - password=decrypt_password.encode("utf-8") + password=decrypt_password.encode("utf-8"), ) except Exception as err: LOG.exception( f"Could not get the private key of the issuer of upload_id:{_upload.upload_id}", - err) + err, + ) self.__sink_on_finish_upload_process( - db_session=db_session, - upload_id=_upload.upload_id, - status=2 + db_session=db_session, upload_id=_upload.upload_id, status=2 ) self.__sink_on_error_notification( db_session=db_session, @@ -138,7 +138,7 @@ def process(self): code=1, upload_id=_upload.upload_id, token_type=_upload.token_type, - error_transfer_id=[] + error_transfer_id=[], ) db_session.commit() self.__release_processing_issuer(_upload.upload_id) @@ -146,16 +146,14 @@ def process(self): # Transfer transfer_list = self.__get_transfer_data( - db_session=db_session, - upload_id=_upload.upload_id, - status=0 + db_session=db_session, upload_id=_upload.upload_id, status=0 ) for _transfer in transfer_list: token = { "token_address": _transfer.token_address, "from_address": _transfer.from_address, "to_address": _transfer.to_address, - "amount": _transfer.amount + "amount": _transfer.amount, } try: if _transfer.token_type == TokenType.IBET_SHARE.value: @@ -163,66 +161,64 @@ def process(self): IbetShareContract(_transfer.token_address).transfer( data=_transfer_data, tx_from=_transfer.issuer_address, - private_key=private_key + private_key=private_key, ) elif _transfer.token_type == TokenType.IBET_STRAIGHT_BOND.value: _transfer_data = IbetStraightBondTransferParams(**token) IbetStraightBondContract(_transfer.token_address).transfer( data=_transfer_data, tx_from=_transfer.issuer_address, - private_key=private_key + private_key=private_key, ) self.__sink_on_finish_transfer_process( - db_session=db_session, - record_id=_transfer.id, - status=1 + db_session=db_session, record_id=_transfer.id, status=1 ) except ContractRevertError as e: - LOG.warning(f"Transaction reverted: id=<{_transfer.id}> error_code:<{e.code}> error_msg:<{e.message}>") + LOG.warning( + f"Transaction reverted: id=<{_transfer.id}> error_code:<{e.code}> error_msg:<{e.message}>" + ) self.__sink_on_finish_transfer_process( - db_session=db_session, - record_id=_transfer.id, - status=2 + db_session=db_session, record_id=_transfer.id, status=2 ) except SendTransactionError: LOG.warning(f"Failed to send transaction: id=<{_transfer.id}>") self.__sink_on_finish_transfer_process( - db_session=db_session, - record_id=_transfer.id, - status=2 + db_session=db_session, record_id=_transfer.id, status=2 ) db_session.commit() error_transfer_list = self.__get_transfer_data( - db_session=db_session, - upload_id=_upload.upload_id, - status=2 + db_session=db_session, upload_id=_upload.upload_id, status=2 ) if len(error_transfer_list) == 0: self.__sink_on_finish_upload_process( db_session=db_session, upload_id=_upload.upload_id, - status=1 # succeeded + status=1, # succeeded ) else: self.__sink_on_finish_upload_process( db_session=db_session, upload_id=_upload.upload_id, - status=2 # error + status=2, # error ) - error_transfer_id = [_error_transfer.id for _error_transfer in error_transfer_list] + error_transfer_id = [ + _error_transfer.id for _error_transfer in error_transfer_list + ] self.__sink_on_error_notification( db_session=db_session, issuer_address=_upload.issuer_address, code=2, upload_id=_upload.upload_id, token_type=_upload.token_type, - error_transfer_id=error_transfer_id + error_transfer_id=error_transfer_id, ) db_session.commit() self.__release_processing_issuer(_upload.upload_id) - LOG.info(f"<{self.thread_num}> Process end: upload_id={_upload.upload_id}") + LOG.info( + f"<{self.thread_num}> Process end: upload_id={_upload.upload_id}" + ) finally: db_session.close() @@ -244,19 +240,23 @@ def __get_uploads(self, db_session: Session) -> List[BulkTransferUpload]: # Retrieve one target data # NOTE: Priority is given to non-issuers that are being processed by other threads. - upload_1 = db_session.query(BulkTransferUpload). \ - filter(BulkTransferUpload.upload_id.notin_(locked_update_id)). \ - filter(BulkTransferUpload.status == 0). \ - filter(BulkTransferUpload.issuer_address.notin_(exclude_issuer)). \ - order_by(BulkTransferUpload.created). \ - first() + upload_1 = ( + db_session.query(BulkTransferUpload) + .filter(BulkTransferUpload.upload_id.notin_(locked_update_id)) + .filter(BulkTransferUpload.status == 0) + .filter(BulkTransferUpload.issuer_address.notin_(exclude_issuer)) + .order_by(BulkTransferUpload.created) + .first() + ) if upload_1 is None: # Retrieve again for all issuers - upload_1 = db_session.query(BulkTransferUpload). \ - filter(BulkTransferUpload.upload_id.notin_(locked_update_id)). \ - filter(BulkTransferUpload.status == 0). \ - order_by(BulkTransferUpload.created). \ - first() + upload_1 = ( + db_session.query(BulkTransferUpload) + .filter(BulkTransferUpload.upload_id.notin_(locked_update_id)) + .filter(BulkTransferUpload.status == 0) + .order_by(BulkTransferUpload.created) + .first() + ) # Issuer to be processed => upload_1.issuer_address # Retrieve the data of the Issuer to be processed @@ -264,25 +264,36 @@ def __get_uploads(self, db_session: Session) -> List[BulkTransferUpload]: if upload_1 is not None: upload_list = [upload_1] if BULK_TRANSFER_WORKER_LOT_SIZE > 1: - upload_list = upload_list + db_session.query(BulkTransferUpload). \ - filter(BulkTransferUpload.upload_id.notin_(locked_update_id)). \ - filter(BulkTransferUpload.status == 0). \ - filter(BulkTransferUpload.issuer_address == upload_1.issuer_address). \ - order_by(BulkTransferUpload.created). \ - offset(1). \ - limit(BULK_TRANSFER_WORKER_LOT_SIZE - 1). \ - all() + upload_list = ( + upload_list + + db_session.query(BulkTransferUpload) + .filter(BulkTransferUpload.upload_id.notin_(locked_update_id)) + .filter(BulkTransferUpload.status == 0) + .filter( + BulkTransferUpload.issuer_address == upload_1.issuer_address + ) + .order_by(BulkTransferUpload.created) + .offset(1) + .limit(BULK_TRANSFER_WORKER_LOT_SIZE - 1) + .all() + ) processing_issuer[self.thread_num] = {} for upload in upload_list: - processing_issuer[self.thread_num][upload.upload_id] = upload.issuer_address + processing_issuer[self.thread_num][ + upload.upload_id + ] = upload.issuer_address return upload_list - def __get_transfer_data(self, db_session: Session, upload_id: str, status: int) -> List[Type[BulkTransfer]]: - transfer_list = db_session.query(BulkTransfer). \ - filter(BulkTransfer.upload_id == upload_id). \ - filter(BulkTransfer.status == status). \ - all() + def __get_transfer_data( + self, db_session: Session, upload_id: str, status: int + ) -> List[Type[BulkTransfer]]: + transfer_list = ( + db_session.query(BulkTransfer) + .filter(BulkTransfer.upload_id == upload_id) + .filter(BulkTransfer.status == status) + .all() + ) return transfer_list def __release_processing_issuer(self, upload_id): @@ -290,30 +301,38 @@ def __release_processing_issuer(self, upload_id): processing_issuer[self.thread_num].pop(upload_id, None) @staticmethod - def __sink_on_finish_upload_process(db_session: Session, upload_id: str, status: int): - transfer_upload_record = db_session.query(BulkTransferUpload). \ - filter(BulkTransferUpload.upload_id == upload_id). \ - first() + def __sink_on_finish_upload_process( + db_session: Session, upload_id: str, status: int + ): + transfer_upload_record = ( + db_session.query(BulkTransferUpload) + .filter(BulkTransferUpload.upload_id == upload_id) + .first() + ) if transfer_upload_record is not None: transfer_upload_record.status = status db_session.merge(transfer_upload_record) @staticmethod - def __sink_on_finish_transfer_process(db_session: Session, record_id: int, status: int): - transfer_record = db_session.query(BulkTransfer). \ - filter(BulkTransfer.id == record_id). \ - first() + def __sink_on_finish_transfer_process( + db_session: Session, record_id: int, status: int + ): + transfer_record = ( + db_session.query(BulkTransfer).filter(BulkTransfer.id == record_id).first() + ) if transfer_record is not None: transfer_record.status = status db_session.merge(transfer_record) @staticmethod - def __sink_on_error_notification(db_session: Session, - issuer_address: str, - code: int, - upload_id: str, - token_type: str, - error_transfer_id: List[int]): + def __sink_on_error_notification( + db_session: Session, + issuer_address: str, + code: int, + upload_id: str, + token_type: str, + error_transfer_id: List[int], + ): notification = Notification() notification.notice_id = uuid.uuid4() notification.issuer_address = issuer_address @@ -323,7 +342,7 @@ def __sink_on_error_notification(db_session: Session, notification.metainfo = { "upload_id": upload_id, "token_type": token_type, - "error_transfer_id": error_transfer_id + "error_transfer_id": error_transfer_id, } db_session.add(notification) @@ -337,20 +356,20 @@ def __sink_on_error_notification(db_session: Session, class Worker: - def __init__(self, thread_num: int): processor = Processor(thread_num=thread_num) self.processor = processor def run(self): - while True: try: self.processor.process() except ServiceUnavailableError: LOG.warning("An external service was unavailable") except SQLAlchemyError as sa_err: - LOG.error(f"A database error has occurred: code={sa_err.code}\n{sa_err}") + LOG.error( + f"A database error has occurred: code={sa_err.code}\n{sa_err}" + ) except Exception as ex: LOG.error(ex) err_bucket.append(ex) diff --git a/batch/processor_create_utxo.py b/batch/processor_create_utxo.py index 4f5669c8..3dd92667 100644 --- a/batch/processor_create_utxo.py +++ b/batch/processor_create_utxo.py @@ -20,30 +20,28 @@ import sys import time from datetime import datetime + from sqlalchemy import create_engine -from sqlalchemy.orm import Session from sqlalchemy.exc import SQLAlchemyError +from sqlalchemy.orm import Session from web3.eth import Contract -path = os.path.join(os.path.dirname(__file__), '../') +path = os.path.join(os.path.dirname(__file__), "../") sys.path.append(path) +import batch_log + +from app.exceptions import ServiceUnavailableError +from app.model.db import UTXO, Token, UTXOBlockNumber +from app.utils.contract_utils import ContractUtils +from app.utils.ledger_utils import create_ledger +from app.utils.web3_utils import Web3Wrapper from config import ( + CREATE_UTXO_BLOCK_LOT_MAX_SIZE, + CREATE_UTXO_INTERVAL, DATABASE_URL, ZERO_ADDRESS, - CREATE_UTXO_INTERVAL, - CREATE_UTXO_BLOCK_LOT_MAX_SIZE -) -from app.model.db import ( - UTXO, - UTXOBlockNumber, - Token ) -from app.utils.ledger_utils import create_ledger -from app.utils.web3_utils import Web3Wrapper -from app.utils.contract_utils import ContractUtils -from app.exceptions import ServiceUnavailableError -import batch_log """ [PROCESSOR-Create-UTXO] @@ -89,26 +87,28 @@ def process(self): db_session=db_session, token_contract=token_contract, block_from=block_from, - block_to=block_to + block_to=block_to, ) event_triggered = event_triggered | self.__process_issue( db_session=db_session, token_contract=token_contract, block_from=block_from, - block_to=block_to + block_to=block_to, ) event_triggered = event_triggered | self.__process_redeem( db_session=db_session, token_contract=token_contract, block_from=block_from, - block_to=block_to + block_to=block_to, ) self.__process_event_triggered( db_session=db_session, token_contract=token_contract, - event_triggered=event_triggered + event_triggered=event_triggered, ) - self.__set_utxo_block_number(db_session=db_session, block_number=block_to) + self.__set_utxo_block_number( + db_session=db_session, block_number=block_to + ) db_session.commit() finally: db_session.close() @@ -120,34 +120,39 @@ def __refresh_token_contract_list(self, db_session: Session): self.token_contract_list = [] # Update token_contract_list to recent - _token_list = db_session.query(Token). \ - filter(Token.token_status == 1). \ - order_by(Token.id). \ - all() + _token_list = ( + db_session.query(Token) + .filter(Token.token_status == 1) + .order_by(Token.id) + .all() + ) for _token in _token_list: token_contract = ContractUtils.get_contract( - contract_name=_token.type, - contract_address=_token.token_address + contract_name=_token.type, contract_address=_token.token_address ) self.token_contract_list.append(token_contract) def __get_utxo_block_number(self, db_session: Session): - _utxo_block_number = db_session.query(UTXOBlockNumber). \ - first() + _utxo_block_number = db_session.query(UTXOBlockNumber).first() if _utxo_block_number is None: return 0 else: return _utxo_block_number.latest_block_number def __set_utxo_block_number(self, db_session: Session, block_number: int): - _utxo_block_number = db_session.query(UTXOBlockNumber). \ - first() + _utxo_block_number = db_session.query(UTXOBlockNumber).first() if _utxo_block_number is None: _utxo_block_number = UTXOBlockNumber() _utxo_block_number.latest_block_number = block_number db_session.merge(_utxo_block_number) - def __process_transfer(self, db_session: Session, token_contract: Contract, block_from: int, block_to: int): + def __process_transfer( + self, + db_session: Session, + token_contract: Contract, + block_from: int, + block_to: int, + ): """Process Transfer Event - The process of updating UTXO data by capturing the following events @@ -166,53 +171,54 @@ def __process_transfer(self, db_session: Session, token_contract: Contract, bloc contract=token_contract, function_name="tradableExchange", args=(), - default_returns=ZERO_ADDRESS + default_returns=ZERO_ADDRESS, ) # Get "HolderChanged" events from exchange contract exchange_contract = ContractUtils.get_contract( contract_name="IbetExchangeInterface", - contract_address=exchange_contract_address + contract_address=exchange_contract_address, ) exchange_contract_events = ContractUtils.get_event_logs( contract=exchange_contract, event="HolderChanged", block_from=block_from, block_to=block_to, - argument_filters={ - "token": token_contract.address - } + argument_filters={"token": token_contract.address}, ) tmp_events = [] for _event in exchange_contract_events: if token_contract.address == _event["args"]["token"]: - tmp_events.append({ - "event": _event["event"], - "args": dict(_event["args"]), - "transaction_hash": _event["transactionHash"].hex(), - "block_number": _event["blockNumber"], - "log_index": _event["logIndex"] - }) + tmp_events.append( + { + "event": _event["event"], + "args": dict(_event["args"]), + "transaction_hash": _event["transactionHash"].hex(), + "block_number": _event["blockNumber"], + "log_index": _event["logIndex"], + } + ) # Get "Transfer" events from token contract token_transfer_events = ContractUtils.get_event_logs( contract=token_contract, event="Transfer", block_from=block_from, - block_to=block_to + block_to=block_to, ) for _event in token_transfer_events: - tmp_events.append({ - "event": _event["event"], - "args": dict(_event["args"]), - "transaction_hash": _event["transactionHash"].hex(), - "block_number": _event["blockNumber"], - "log_index": _event["logIndex"] - }) + tmp_events.append( + { + "event": _event["event"], + "args": dict(_event["args"]), + "transaction_hash": _event["transactionHash"].hex(), + "block_number": _event["blockNumber"], + "log_index": _event["logIndex"], + } + ) # Marge & Sort: block_number > log_index events = sorted( - tmp_events, - key=lambda x: (x["block_number"], x["log_index"]) + tmp_events, key=lambda x: (x["block_number"], x["log_index"]) ) # Sink @@ -224,12 +230,17 @@ def __process_transfer(self, db_session: Session, token_contract: Contract, bloc amount = args.get("value") # Skip sinking in case of deposit to exchange or withdrawal from exchange - if web3.eth.get_code(from_account).hex() != "0x" or web3.eth.get_code(to_account).hex() != "0x": + if ( + web3.eth.get_code(from_account).hex() != "0x" + or web3.eth.get_code(to_account).hex() != "0x" + ): continue transaction_hash = event["transaction_hash"] block_number = event["block_number"] - block_timestamp = datetime.utcfromtimestamp(web3.eth.get_block(block_number)["timestamp"]) # UTC + block_timestamp = datetime.utcfromtimestamp( + web3.eth.get_block(block_number)["timestamp"] + ) # UTC if amount is not None and amount <= sys.maxsize: event_triggered = True @@ -243,7 +254,7 @@ def __process_transfer(self, db_session: Session, token_contract: Contract, bloc account_address=from_account, amount=amount, block_number=block_number, - block_timestamp=block_timestamp + block_timestamp=block_timestamp, ) # Update UTXO(to account) @@ -255,7 +266,7 @@ def __process_transfer(self, db_session: Session, token_contract: Contract, bloc account_address=to_account, amount=amount, block_number=block_number, - block_timestamp=block_timestamp + block_timestamp=block_timestamp, ) return event_triggered @@ -263,7 +274,13 @@ def __process_transfer(self, db_session: Session, token_contract: Contract, bloc LOG.exception(e) return False - def __process_issue(self, db_session: Session, token_contract: Contract, block_from: int, block_to: int): + def __process_issue( + self, + db_session: Session, + token_contract: Contract, + block_from: int, + block_to: int, + ): """Process Issue Event - The process of updating UTXO data by capturing the following events @@ -281,7 +298,7 @@ def __process_issue(self, db_session: Session, token_contract: Contract, block_f contract=token_contract, event="Issue", block_from=block_from, - block_to=block_to + block_to=block_to, ) # Sink @@ -293,7 +310,9 @@ def __process_issue(self, db_session: Session, token_contract: Contract, block_f transaction_hash = event["transactionHash"].hex() block_number = event["blockNumber"] - block_timestamp = datetime.utcfromtimestamp(web3.eth.get_block(block_number)["timestamp"]) # UTC + block_timestamp = datetime.utcfromtimestamp( + web3.eth.get_block(block_number)["timestamp"] + ) # UTC if amount is not None and amount <= sys.maxsize: event_triggered = True @@ -307,7 +326,7 @@ def __process_issue(self, db_session: Session, token_contract: Contract, block_f account_address=account, amount=amount, block_number=block_number, - block_timestamp=block_timestamp + block_timestamp=block_timestamp, ) return event_triggered @@ -315,7 +334,13 @@ def __process_issue(self, db_session: Session, token_contract: Contract, block_f LOG.exception(e) return False - def __process_redeem(self, db_session: Session, token_contract: Contract, block_from: int, block_to: int): + def __process_redeem( + self, + db_session: Session, + token_contract: Contract, + block_from: int, + block_to: int, + ): """Process Redeem Event - The process of updating UTXO data by capturing the following events @@ -333,7 +358,7 @@ def __process_redeem(self, db_session: Session, token_contract: Contract, block_ contract=token_contract, event="Redeem", block_from=block_from, - block_to=block_to + block_to=block_to, ) # Sink @@ -345,7 +370,9 @@ def __process_redeem(self, db_session: Session, token_contract: Contract, block_ transaction_hash = event["transactionHash"].hex() block_number = event["blockNumber"] - block_timestamp = datetime.utcfromtimestamp(web3.eth.get_block(block_number)["timestamp"]) # UTC + block_timestamp = datetime.utcfromtimestamp( + web3.eth.get_block(block_number)["timestamp"] + ) # UTC if amount is not None and amount <= sys.maxsize: event_triggered = True @@ -359,7 +386,7 @@ def __process_redeem(self, db_session: Session, token_contract: Contract, block_ account_address=account, amount=amount, block_number=block_number, - block_timestamp=block_timestamp + block_timestamp=block_timestamp, ) return event_triggered @@ -367,7 +394,9 @@ def __process_redeem(self, db_session: Session, token_contract: Contract, block_ LOG.exception(e) return False - def __process_event_triggered(self, db_session: Session, token_contract: Contract, event_triggered: bool): + def __process_event_triggered( + self, db_session: Session, token_contract: Contract, event_triggered: bool + ): try: if event_triggered is True: # Create Ledger @@ -376,19 +405,23 @@ def __process_event_triggered(self, db_session: Session, token_contract: Contrac LOG.exception(e) @staticmethod - def __sink_on_utxo(db_session: Session, - spent: bool, - transaction_hash: str, - account_address: str, - token_address: str, - amount: int, - block_number: int, - block_timestamp: datetime): + def __sink_on_utxo( + db_session: Session, + spent: bool, + transaction_hash: str, + account_address: str, + token_address: str, + amount: int, + block_number: int, + block_timestamp: datetime, + ): if not spent: - _utxo = db_session.query(UTXO). \ - filter(UTXO.transaction_hash == transaction_hash). \ - filter(UTXO.account_address == account_address). \ - first() + _utxo = ( + db_session.query(UTXO) + .filter(UTXO.transaction_hash == transaction_hash) + .filter(UTXO.account_address == account_address) + .first() + ) if _utxo is None: _utxo = UTXO() _utxo.transaction_hash = transaction_hash @@ -403,12 +436,14 @@ def __sink_on_utxo(db_session: Session, _utxo.amount = utxo_amount + amount db_session.merge(_utxo) else: - _utxo_list = db_session.query(UTXO). \ - filter(UTXO.account_address == account_address). \ - filter(UTXO.token_address == token_address). \ - filter(UTXO.amount > 0). \ - order_by(UTXO.block_timestamp). \ - all() + _utxo_list = ( + db_session.query(UTXO) + .filter(UTXO.account_address == account_address) + .filter(UTXO.token_address == token_address) + .filter(UTXO.amount > 0) + .order_by(UTXO.block_timestamp) + .all() + ) spend_amount = amount for _utxo in _utxo_list: utxo_amount = _utxo.amount diff --git a/batch/processor_generate_rsa_key.py b/batch/processor_generate_rsa_key.py index b2cc07e0..eeb369a4 100644 --- a/batch/processor_generate_rsa_key.py +++ b/batch/processor_generate_rsa_key.py @@ -22,24 +22,19 @@ from Crypto import Random from Crypto.PublicKey import RSA -from sqlalchemy import ( - create_engine, - or_ -) -from sqlalchemy.orm import Session +from sqlalchemy import create_engine, or_ from sqlalchemy.exc import SQLAlchemyError +from sqlalchemy.orm import Session -path = os.path.join(os.path.dirname(__file__), '../') +path = os.path.join(os.path.dirname(__file__), "../") sys.path.append(path) -from config import DATABASE_URL -from app.model.db import ( - Account, - AccountRsaStatus -) -from app.utils.e2ee_utils import E2EEUtils import batch_log +from app.model.db import Account, AccountRsaStatus +from app.utils.e2ee_utils import E2EEUtils +from config import DATABASE_URL + """ [PROCESSOR-Generate-RSA-Key] @@ -53,7 +48,6 @@ class Processor: - def process(self): db_session = Session(autocommit=False, autoflush=True, bind=db_engine) try: @@ -73,7 +67,7 @@ def process(self): db_session=db_session, issuer_address=account.issuer_address, rsa_private_pem=rsa_private_pem, - rsa_public_pem=rsa_public_pem + rsa_public_pem=rsa_public_pem, ) db_session.commit() @@ -83,12 +77,16 @@ def process(self): db_session.close() def __get_account_list(self, db_session: Session): - account_list = db_session.query(Account). \ - filter( - or_( - Account.rsa_status == AccountRsaStatus.CREATING.value, - Account.rsa_status == AccountRsaStatus.CHANGING.value)). \ - all() + account_list = ( + db_session.query(Account) + .filter( + or_( + Account.rsa_status == AccountRsaStatus.CREATING.value, + Account.rsa_status == AccountRsaStatus.CHANGING.value, + ) + ) + .all() + ) return account_list @@ -101,10 +99,17 @@ def __generate_rsa_key(self, passphrase: str): return rsa_private_pem, rsa_public_pem @staticmethod - def __sink_on_account(db_session: Session, issuer_address: str, rsa_private_pem: str, rsa_public_pem: str): - account = db_session.query(Account). \ - filter(Account.issuer_address == issuer_address). \ - first() + def __sink_on_account( + db_session: Session, + issuer_address: str, + rsa_private_pem: str, + rsa_public_pem: str, + ): + account = ( + db_session.query(Account) + .filter(Account.issuer_address == issuer_address) + .first() + ) if account is not None: rsa_status = AccountRsaStatus.SET.value if account.rsa_status == AccountRsaStatus.CHANGING.value: diff --git a/batch/processor_modify_personal_info.py b/batch/processor_modify_personal_info.py index 85669f91..d12c00ee 100644 --- a/batch/processor_modify_personal_info.py +++ b/batch/processor_modify_personal_info.py @@ -19,38 +19,33 @@ import os import sys import time -from typing import ( - List, - Set -) +from typing import List, Set from sqlalchemy import create_engine -from sqlalchemy.orm import Session from sqlalchemy.exc import SQLAlchemyError +from sqlalchemy.orm import Session -path = os.path.join(os.path.dirname(__file__), '../') +path = os.path.join(os.path.dirname(__file__), "../") sys.path.append(path) -from config import ( - DATABASE_URL, - ZERO_ADDRESS +import batch_log + +from app.exceptions import ServiceUnavailableError +from app.model.blockchain import ( + IbetShareContract, + IbetStraightBondContract, + PersonalInfoContract, ) from app.model.db import ( - Token, - TokenType, - IDXPersonalInfo, Account, AccountRsaKeyTemporary, - AccountRsaStatus -) -from app.model.blockchain import ( - PersonalInfoContract, - IbetShareContract, - IbetStraightBondContract + AccountRsaStatus, + IDXPersonalInfo, + Token, + TokenType, ) from app.utils.contract_utils import ContractUtils -from app.exceptions import ServiceUnavailableError -import batch_log +from config import DATABASE_URL, ZERO_ADDRESS """ [PROCESSOR-Modify-Personal-Info] @@ -66,7 +61,6 @@ class Processor: - def process(self): db_session = Session(autocommit=False, autoflush=True, bind=db_engine) try: @@ -74,15 +68,18 @@ def process(self): for temporary in temporary_list: LOG.info(f"Process start: issuer={temporary.issuer_address}") - contract_accessor_list = self.__get_personal_info_contract_accessor_list( - db_session=db_session, - issuer_address=temporary.issuer_address + contract_accessor_list = ( + self.__get_personal_info_contract_accessor_list( + db_session=db_session, issuer_address=temporary.issuer_address + ) ) # Get target PersonalInfo account address - idx_personal_info_list = db_session.query(IDXPersonalInfo).\ - filter(IDXPersonalInfo.issuer_address == temporary.issuer_address).\ - all() + idx_personal_info_list = ( + db_session.query(IDXPersonalInfo) + .filter(IDXPersonalInfo.issuer_address == temporary.issuer_address) + .all() + ) count = len(idx_personal_info_list) completed_count = 0 @@ -92,8 +89,11 @@ def process(self): is_registered = ContractUtils.call_function( contract=contract_accessor.personal_info_contract, function_name="isRegistered", - args=(idx_personal_info.account_address, idx_personal_info.issuer_address,), - default_returns=False + args=( + idx_personal_info.account_address, + idx_personal_info.issuer_address, + ), + default_returns=False, ) if is_registered: target_contract_accessor = contract_accessor @@ -102,7 +102,7 @@ def process(self): is_modify = self.__modify_personal_info( temporary=temporary, idx_personal_info=idx_personal_info, - personal_info_contract_accessor=target_contract_accessor + personal_info_contract_accessor=target_contract_accessor, ) if not is_modify: # Confirm after being reflected in Contract. @@ -113,8 +113,7 @@ def process(self): # update the status of the issuer's RSA key. if count == completed_count: self.__sink_on_account( - db_session=db_session, - issuer_address=temporary.issuer_address + db_session=db_session, issuer_address=temporary.issuer_address ) db_session.commit() @@ -125,20 +124,26 @@ def process(self): def __get_temporary_list(self, db_session: Session) -> List[AccountRsaKeyTemporary]: # NOTE: rsa_private_key in Account DB and AccountRsaKeyTemporary DB is the same when API is executed, # Account DB is changed when RSA generate batch is completed. - temporary_list = db_session.query(AccountRsaKeyTemporary). \ - join(Account, AccountRsaKeyTemporary.issuer_address == Account.issuer_address). \ - filter(AccountRsaKeyTemporary.rsa_private_key != Account.rsa_private_key). \ - all() + temporary_list = ( + db_session.query(AccountRsaKeyTemporary) + .join( + Account, AccountRsaKeyTemporary.issuer_address == Account.issuer_address + ) + .filter(AccountRsaKeyTemporary.rsa_private_key != Account.rsa_private_key) + .all() + ) return temporary_list - def __get_personal_info_contract_accessor_list(self, - db_session: Session, - issuer_address: str) -> Set[PersonalInfoContract]: - token_list = db_session.query(Token). \ - filter(Token.issuer_address == issuer_address). \ - filter(Token.token_status == 1). \ - all() + def __get_personal_info_contract_accessor_list( + self, db_session: Session, issuer_address: str + ) -> Set[PersonalInfoContract]: + token_list = ( + db_session.query(Token) + .filter(Token.issuer_address == issuer_address) + .filter(Token.token_status == 1) + .all() + ) personal_info_contract_list = set() for token in token_list: if token.type == TokenType.IBET_SHARE.value: @@ -154,21 +159,27 @@ def __get_personal_info_contract_accessor_list(self, PersonalInfoContract( db=db_session, issuer_address=issuer_address, - contract_address=contract_address)) + contract_address=contract_address, + ) + ) return personal_info_contract_list - def __modify_personal_info(self, - temporary: AccountRsaKeyTemporary, - idx_personal_info: IDXPersonalInfo, - personal_info_contract_accessor: PersonalInfoContract) -> bool: - + def __modify_personal_info( + self, + temporary: AccountRsaKeyTemporary, + idx_personal_info: IDXPersonalInfo, + personal_info_contract_accessor: PersonalInfoContract, + ) -> bool: # Unset information assumes completed. personal_info_state = ContractUtils.call_function( contract=personal_info_contract_accessor.personal_info_contract, function_name="personal_info", - args=(idx_personal_info.account_address, idx_personal_info.issuer_address,), - default_returns=[ZERO_ADDRESS, ZERO_ADDRESS, ""] + args=( + idx_personal_info.account_address, + idx_personal_info.issuer_address, + ), + default_returns=[ZERO_ADDRESS, ZERO_ADDRESS, ""], ) encrypted_info = personal_info_state[2] if encrypted_info == "": @@ -179,12 +190,13 @@ def __modify_personal_info(self, org_rsa_private_key = personal_info_contract_accessor.issuer.rsa_private_key org_rsa_passphrase = personal_info_contract_accessor.issuer.rsa_passphrase # Replace RSA - personal_info_contract_accessor.issuer.rsa_private_key = temporary.rsa_private_key + personal_info_contract_accessor.issuer.rsa_private_key = ( + temporary.rsa_private_key + ) personal_info_contract_accessor.issuer.rsa_passphrase = temporary.rsa_passphrase # Modify info = personal_info_contract_accessor.get_info( - idx_personal_info.account_address, - default_value=None + idx_personal_info.account_address, default_value=None ) # Back RSA personal_info_contract_accessor.issuer.rsa_private_key = org_rsa_private_key @@ -197,7 +209,7 @@ def __modify_personal_info(self, "email": None, "birth": None, "is_corporate": None, - "tax_category": None + "tax_category": None, } if info == default_info: return False @@ -206,21 +218,25 @@ def __modify_personal_info(self, personal_info_contract_accessor.modify_info( account_address=idx_personal_info.account_address, data=info, - default_value=None + default_value=None, ) return True @staticmethod def __sink_on_account(db_session: Session, issuer_address: str): - account = db_session.query(Account). \ - filter(Account.issuer_address == issuer_address). \ - first() + account = ( + db_session.query(Account) + .filter(Account.issuer_address == issuer_address) + .first() + ) if account is not None: account.rsa_status = AccountRsaStatus.SET.value db_session.merge(account) - temporary = db_session.query(AccountRsaKeyTemporary). \ - filter(Account.issuer_address == issuer_address). \ - first() + temporary = ( + db_session.query(AccountRsaKeyTemporary) + .filter(Account.issuer_address == issuer_address) + .first() + ) if temporary is not None: db_session.delete(temporary) diff --git a/batch/processor_monitor_block_sync.py b/batch/processor_monitor_block_sync.py index c636fc61..8e86e36e 100644 --- a/batch/processor_monitor_block_sync.py +++ b/batch/processor_monitor_block_sync.py @@ -22,30 +22,28 @@ from typing import Any, Callable from sqlalchemy import create_engine -from sqlalchemy.orm import Session from sqlalchemy.exc import SQLAlchemyError +from sqlalchemy.orm import Session from web3 import Web3 from web3.middleware import geth_poa_middleware -from web3.types import ( - RPCEndpoint, - RPCResponse -) +from web3.types import RPCEndpoint, RPCResponse -path = os.path.join(os.path.dirname(__file__), '../') +path = os.path.join(os.path.dirname(__file__), "../") sys.path.append(path) +import batch_log + +from app.exceptions import ServiceUnavailableError +from app.model.db import Node from config import ( + BLOCK_GENERATION_SPEED_THRESHOLD, + BLOCK_SYNC_REMAINING_THRESHOLD, + BLOCK_SYNC_STATUS_CALC_PERIOD, + BLOCK_SYNC_STATUS_SLEEP_INTERVAL, DATABASE_URL, WEB3_HTTP_PROVIDER, WEB3_HTTP_PROVIDER_STANDBY, - BLOCK_SYNC_STATUS_SLEEP_INTERVAL, - BLOCK_SYNC_STATUS_CALC_PERIOD, - BLOCK_SYNC_REMAINING_THRESHOLD, - BLOCK_GENERATION_SPEED_THRESHOLD ) -from app.model.db import Node -from app.exceptions import ServiceUnavailableError -import batch_log """ [PROCESSOR-Monitor-Block-Sync] @@ -64,7 +62,7 @@ class Web3WrapperException(Exception): def web3_exception_handler_middleware( - make_request: Callable[[RPCEndpoint, Any], Any], w3: "Web3" + make_request: Callable[[RPCEndpoint, Any], Any], w3: "Web3" ) -> Callable[[RPCEndpoint, Any], RPCResponse]: METHODS = [ "eth_blockNumber", @@ -108,16 +106,21 @@ def __init__(self): db_session = self.__get_db_session() try: # Delete old node data - valid_endpoint_uri_list = list(WEB3_HTTP_PROVIDER) + WEB3_HTTP_PROVIDER_STANDBY + valid_endpoint_uri_list = ( + list(WEB3_HTTP_PROVIDER) + WEB3_HTTP_PROVIDER_STANDBY + ) self.__delete_old_node( - db_session=db_session, - valid_endpoint_uri_list=valid_endpoint_uri_list + db_session=db_session, valid_endpoint_uri_list=valid_endpoint_uri_list ) # Initial setting self.node_info = {} - self.__set_node_info(db_session=db_session, endpoint_uri=WEB3_HTTP_PROVIDER, priority=0) + self.__set_node_info( + db_session=db_session, endpoint_uri=WEB3_HTTP_PROVIDER, priority=0 + ) for endpoint_uri in WEB3_HTTP_PROVIDER_STANDBY: - self.__set_node_info(db_session=db_session, endpoint_uri=endpoint_uri, priority=1) + self.__set_node_info( + db_session=db_session, endpoint_uri=endpoint_uri, priority=1 + ) db_session.commit() finally: db_session.close() @@ -135,9 +138,7 @@ def process(self): db_session.close() def __set_node_info(self, db_session: Session, endpoint_uri: str, priority: int): - self.node_info[endpoint_uri] = { - "priority": priority - } + self.node_info[endpoint_uri] = {"priority": priority} web3 = Web3(Web3.HTTPProvider(endpoint_uri)) web3.middleware_onion.inject(geth_poa_middleware, layer=0) @@ -148,19 +149,15 @@ def __set_node_info(self, db_session: Session, endpoint_uri: str, priority: int) try: # NOTE: Immediately after the processing, the monitoring data is not retained, # so the past block number is acquired. - block = web3.eth.get_block(max(web3.eth.block_number - BLOCK_SYNC_STATUS_CALC_PERIOD, 0)) + block = web3.eth.get_block( + max(web3.eth.block_number - BLOCK_SYNC_STATUS_CALC_PERIOD, 0) + ) except Web3WrapperException: self.__web3_errors(db_session=db_session, endpoint_uri=endpoint_uri) LOG.error(f"Node connection failed: {endpoint_uri}") - block = { - "timestamp": time.time(), - "number": 0 - } - - data = { - "time": block["timestamp"], - "block_number": block["number"] - } + block = {"timestamp": time.time(), "number": 0} + + data = {"time": block["timestamp"], "block_number": block["number"]} history = RingBuffer(BLOCK_SYNC_STATUS_CALC_PERIOD, data) self.node_info[endpoint_uri]["history"] = history @@ -177,19 +174,18 @@ def __process(self, db_session: Session, endpoint_uri: str): remaining_blocks = syncing["highestBlock"] - syncing["currentBlock"] if remaining_blocks > BLOCK_SYNC_REMAINING_THRESHOLD: is_synced = False - errors.append(f"highestBlock={syncing['highestBlock']}, currentBlock={syncing['currentBlock']}") + errors.append( + f"highestBlock={syncing['highestBlock']}, currentBlock={syncing['currentBlock']}" + ) # Check increased block number - data = { - "time": time.time(), - "block_number": web3.eth.block_number - } + data = {"time": time.time(), "block_number": web3.eth.block_number} old_data = history.peek_oldest() elapsed_time = data["time"] - old_data["time"] generated_block_count = data["block_number"] - old_data["block_number"] - generated_block_count_threshold = \ - (elapsed_time / EXPECTED_BLOCKS_PER_SEC) * \ - (BLOCK_GENERATION_SPEED_THRESHOLD / 100) # count of block generation theoretical value + generated_block_count_threshold = (elapsed_time / EXPECTED_BLOCKS_PER_SEC) * ( + BLOCK_GENERATION_SPEED_THRESHOLD / 100 + ) # count of block generation theoretical value if generated_block_count < generated_block_count_threshold: is_synced = False errors.append(f"{generated_block_count} blocks in {int(elapsed_time)} sec") @@ -197,12 +193,14 @@ def __process(self, db_session: Session, endpoint_uri: str): # Update database _node = db_session.query(Node).filter(Node.endpoint_uri == endpoint_uri).first() - status_changed = False if _node is not None and _node.is_synced == is_synced else True + status_changed = ( + False if _node is not None and _node.is_synced == is_synced else True + ) self.__sink_on_node( db_session=db_session, endpoint_uri=endpoint_uri, priority=priority, - is_synced=is_synced + is_synced=is_synced, ) # Output logs @@ -225,7 +223,7 @@ def __web3_errors(self, db_session: Session, endpoint_uri: str): db_session=db_session, endpoint_uri=endpoint_uri, priority=priority, - is_synced=False + is_synced=False, ) db_session.commit() except Exception as ex: @@ -238,10 +236,16 @@ def __get_db_session(): @staticmethod def __delete_old_node(db_session: Session, valid_endpoint_uri_list: list[str]): - _node = db_session.query(Node).filter(Node.endpoint_uri.not_in(valid_endpoint_uri_list)).delete() + _node = ( + db_session.query(Node) + .filter(Node.endpoint_uri.not_in(valid_endpoint_uri_list)) + .delete() + ) @staticmethod - def __sink_on_node(db_session: Session, endpoint_uri: str, priority: int, is_synced: bool): + def __sink_on_node( + db_session: Session, endpoint_uri: str, priority: int, is_synced: bool + ): _node = db_session.query(Node).filter(Node.endpoint_uri == endpoint_uri).first() if _node is not None: _node.is_synced = is_synced diff --git a/batch/processor_rotate_e2e_messaging_rsa_key.py b/batch/processor_rotate_e2e_messaging_rsa_key.py index 1921a720..89f5cfff 100644 --- a/batch/processor_rotate_e2e_messaging_rsa_key.py +++ b/batch/processor_rotate_e2e_messaging_rsa_key.py @@ -22,38 +22,33 @@ from datetime import datetime from typing import Type -from eth_keyfile import decode_keyfile_json from Crypto import Random from Crypto.PublicKey import RSA -from sqlalchemy import ( - create_engine, - desc -) -from sqlalchemy.orm import Session +from eth_keyfile import decode_keyfile_json +from sqlalchemy import create_engine, desc from sqlalchemy.exc import SQLAlchemyError +from sqlalchemy.orm import Session path = os.path.join(os.path.dirname(__file__), "../") sys.path.append(path) -from config import ( - DATABASE_URL, - ROTATE_E2E_MESSAGING_RSA_KEY_INTERVAL, - E2E_MESSAGING_CONTRACT_ADDRESS +import batch_log + +from app.exceptions import ( + ContractRevertError, + SendTransactionError, + ServiceUnavailableError, ) from app.model.blockchain import E2EMessaging -from app.model.db import ( - E2EMessagingAccount, - E2EMessagingAccountRsaKey -) +from app.model.db import E2EMessagingAccount, E2EMessagingAccountRsaKey from app.utils.contract_utils import ContractUtils from app.utils.e2ee_utils import E2EEUtils from app.utils.web3_utils import Web3Wrapper -from app.exceptions import ( - SendTransactionError, - ServiceUnavailableError, - ContractRevertError +from config import ( + DATABASE_URL, + E2E_MESSAGING_CONTRACT_ADDRESS, + ROTATE_E2E_MESSAGING_RSA_KEY_INTERVAL, ) -import batch_log """ [PROCESSOR-Rotate-E2E-Messaging-RSA-Key] @@ -73,43 +68,55 @@ class Processor: def __init__(self): self.e2e_messaging_contract = ContractUtils.get_contract( contract_name="E2EMessaging", - contract_address=E2E_MESSAGING_CONTRACT_ADDRESS) + contract_address=E2E_MESSAGING_CONTRACT_ADDRESS, + ) def process(self): db_session = Session(autocommit=False, autoflush=True, bind=db_engine) try: base_time = int(time.time()) - e2e_messaging_account_list = self.__get_e2e_messaging_account_list(db_session=db_session) + e2e_messaging_account_list = self.__get_e2e_messaging_account_list( + db_session=db_session + ) for _e2e_messaging_account in e2e_messaging_account_list: self.__auto_generate_rsa_key( db_session=db_session, base_time=base_time, - e2e_messaging_account=_e2e_messaging_account + e2e_messaging_account=_e2e_messaging_account, ) self.__rotate_rsa_key( - db_session=db_session, - e2e_messaging_account=_e2e_messaging_account + db_session=db_session, e2e_messaging_account=_e2e_messaging_account ) db_session.commit() finally: db_session.close() def __get_e2e_messaging_account_list(self, db_session: Session): - e2e_messaging_account_list = db_session.query(E2EMessagingAccount). \ - filter(E2EMessagingAccount.is_deleted == False). \ - order_by(E2EMessagingAccount.account_address). \ - all() + e2e_messaging_account_list = ( + db_session.query(E2EMessagingAccount) + .filter(E2EMessagingAccount.is_deleted == False) + .order_by(E2EMessagingAccount.account_address) + .all() + ) return e2e_messaging_account_list - def __auto_generate_rsa_key(self, db_session: Session, base_time: int, e2e_messaging_account: Type[E2EMessagingAccount]): - + def __auto_generate_rsa_key( + self, + db_session: Session, + base_time: int, + e2e_messaging_account: Type[E2EMessagingAccount], + ): if e2e_messaging_account.rsa_key_generate_interval > 0: - # Get latest RSA key - _account_rsa_key = db_session.query(E2EMessagingAccountRsaKey). \ - filter(E2EMessagingAccountRsaKey.account_address == e2e_messaging_account.account_address). \ - order_by(desc(E2EMessagingAccountRsaKey.block_timestamp)). \ - first() + _account_rsa_key = ( + db_session.query(E2EMessagingAccountRsaKey) + .filter( + E2EMessagingAccountRsaKey.account_address + == e2e_messaging_account.account_address + ) + .order_by(desc(E2EMessagingAccountRsaKey.block_timestamp)) + .first() + ) latest_time = int(_account_rsa_key.block_timestamp.timestamp()) interval = e2e_messaging_account.rsa_key_generate_interval * 3600 if base_time - latest_time < interval: @@ -120,7 +127,9 @@ def __auto_generate_rsa_key(self, db_session: Session, base_time: int, e2e_messa # Generate RSA key random_func = Random.new().read rsa = RSA.generate(4096, random_func) - rsa_private_key = rsa.exportKey(format="PEM", passphrase=pass_phrase).decode() + rsa_private_key = rsa.exportKey( + format="PEM", passphrase=pass_phrase + ).decode() rsa_public_key = rsa.publickey().exportKey().decode() # Register RSA Public key to Blockchain @@ -128,25 +137,35 @@ def __auto_generate_rsa_key(self, db_session: Session, base_time: int, e2e_messa eoa_password = E2EEUtils.decrypt(e2e_messaging_account.eoa_password) private_key = decode_keyfile_json( raw_keyfile_json=e2e_messaging_account.keyfile, - password=eoa_password.encode("utf-8") + password=eoa_password.encode("utf-8"), ) except Exception: - LOG.exception(f"Could not get the EOA private key: " - f"account_address={e2e_messaging_account.account_address}") + LOG.exception( + f"Could not get the EOA private key: " + f"account_address={e2e_messaging_account.account_address}" + ) return try: - tx_hash, _ = E2EMessaging(E2E_MESSAGING_CONTRACT_ADDRESS).set_public_key( + tx_hash, _ = E2EMessaging( + E2E_MESSAGING_CONTRACT_ADDRESS + ).set_public_key( public_key=rsa_public_key, key_type="RSA4096", tx_from=e2e_messaging_account.account_address, - private_key=private_key + private_key=private_key, + ) + LOG.info( + f"New RSA key created: account_address={e2e_messaging_account.account_address}" ) - LOG.info(f"New RSA key created: account_address={e2e_messaging_account.account_address}") except ContractRevertError as e: - LOG.warning(f"Transaction reverted: account_address=<{e2e_messaging_account.account_address}> error_code:<{e.code}> error_msg:<{e.message}>") + LOG.warning( + f"Transaction reverted: account_address=<{e2e_messaging_account.account_address}> error_code:<{e.code}> error_msg:<{e.message}>" + ) return except SendTransactionError: - LOG.warning(f"Failed to send transaction: account_address={e2e_messaging_account.account_address}") + LOG.warning( + f"Failed to send transaction: account_address={e2e_messaging_account.account_address}" + ) return # Register RSA key to DB @@ -157,19 +176,26 @@ def __auto_generate_rsa_key(self, db_session: Session, base_time: int, e2e_messa _account_rsa_key.rsa_private_key = rsa_private_key _account_rsa_key.rsa_public_key = rsa_public_key _account_rsa_key.rsa_passphrase = E2EEUtils.encrypt(pass_phrase) - _account_rsa_key.block_timestamp = datetime.utcfromtimestamp(block["timestamp"]) + _account_rsa_key.block_timestamp = datetime.utcfromtimestamp( + block["timestamp"] + ) db_session.add(_account_rsa_key) - def __rotate_rsa_key(self, db_session: Session, e2e_messaging_account: Type[E2EMessagingAccount]): - + def __rotate_rsa_key( + self, db_session: Session, e2e_messaging_account: Type[E2EMessagingAccount] + ): if e2e_messaging_account.rsa_generation > 0: - # Delete RSA key that exceeds the number of generations - _account_rsa_key_over_generation_list = db_session.query(E2EMessagingAccountRsaKey). \ - filter(E2EMessagingAccountRsaKey.account_address == e2e_messaging_account.account_address). \ - order_by(desc(E2EMessagingAccountRsaKey.block_timestamp)). \ - offset(e2e_messaging_account.rsa_generation). \ - all() + _account_rsa_key_over_generation_list = ( + db_session.query(E2EMessagingAccountRsaKey) + .filter( + E2EMessagingAccountRsaKey.account_address + == e2e_messaging_account.account_address + ) + .order_by(desc(E2EMessagingAccountRsaKey.block_timestamp)) + .offset(e2e_messaging_account.rsa_generation) + .all() + ) for _account_rsa_key in _account_rsa_key_over_generation_list: db_session.delete(_account_rsa_key) diff --git a/batch/processor_scheduled_events.py b/batch/processor_scheduled_events.py index 4043e438..90fcffb2 100644 --- a/batch/processor_scheduled_events.py +++ b/batch/processor_scheduled_events.py @@ -21,52 +21,47 @@ import threading import time import uuid -from typing import ( - List, - Set, - Optional -) +from typing import List, Optional, Set from eth_keyfile import decode_keyfile_json from sqlalchemy import create_engine -from sqlalchemy.orm import Session from sqlalchemy.exc import SQLAlchemyError +from sqlalchemy.orm import Session path = os.path.join(os.path.dirname(__file__), "../") sys.path.append(path) from datetime import datetime -from config import ( - DATABASE_URL, - SCHEDULED_EVENTS_INTERVAL, - SCHEDULED_EVENTS_WORKER_COUNT + +import batch_log + +from app.exceptions import ( + ContractRevertError, + SendTransactionError, + ServiceUnavailableError, +) +from app.model.blockchain import IbetShareContract, IbetStraightBondContract +from app.model.blockchain.tx_params.ibet_share import ( + UpdateParams as IbetShareUpdateParams, +) +from app.model.blockchain.tx_params.ibet_straight_bond import ( + UpdateParams as IbetStraightBondUpdateParams, ) -from app.utils.e2ee_utils import E2EEUtils -from app.utils.web3_utils import Web3Wrapper from app.model.db import ( Account, + Notification, + NotificationType, ScheduledEvents, ScheduledEventType, TokenType, - Notification, - NotificationType -) -from app.model.blockchain import ( - IbetStraightBondContract, - IbetShareContract ) -from app.model.blockchain.tx_params.ibet_share import ( - UpdateParams as IbetShareUpdateParams -) -from app.model.blockchain.tx_params.ibet_straight_bond import ( - UpdateParams as IbetStraightBondUpdateParams -) -from app.exceptions import ( - SendTransactionError, - ServiceUnavailableError, - ContractRevertError +from app.utils.e2ee_utils import E2EEUtils +from app.utils.web3_utils import Web3Wrapper +from config import ( + DATABASE_URL, + SCHEDULED_EVENTS_INTERVAL, + SCHEDULED_EVENTS_WORKER_COUNT, ) -import batch_log """ [PROCESSOR-Scheduled-Events] @@ -95,8 +90,7 @@ def process(self): process_start_time = datetime.utcnow() while True: events_list = self.__get_events_of_one_issuer( - db_session=db_session, - filter_time=process_start_time + db_session=db_session, filter_time=process_start_time ) if len(events_list) < 1: return @@ -110,25 +104,31 @@ def process(self): finally: db_session.close() - def __get_events_of_one_issuer(self, db_session: Session, filter_time: datetime) -> List[ScheduledEvents]: + def __get_events_of_one_issuer( + self, db_session: Session, filter_time: datetime + ) -> List[ScheduledEvents]: with lock: - event: Optional[ScheduledEvents] = db_session.query(ScheduledEvents). \ - filter(ScheduledEvents.status == 0). \ - filter(ScheduledEvents.scheduled_datetime <= filter_time). \ - filter(ScheduledEvents.issuer_address.notin_(processing_issuers)). \ - order_by(ScheduledEvents.scheduled_datetime, ScheduledEvents.id). \ - first() + event: Optional[ScheduledEvents] = ( + db_session.query(ScheduledEvents) + .filter(ScheduledEvents.status == 0) + .filter(ScheduledEvents.scheduled_datetime <= filter_time) + .filter(ScheduledEvents.issuer_address.notin_(processing_issuers)) + .order_by(ScheduledEvents.scheduled_datetime, ScheduledEvents.id) + .first() + ) if event is None: return [] issuer_address = event.issuer_address processing_issuers.add(issuer_address) - events_list: List[ScheduledEvents] = db_session.query(ScheduledEvents). \ - filter(ScheduledEvents.status == 0). \ - filter(ScheduledEvents.scheduled_datetime <= filter_time). \ - filter(ScheduledEvents.issuer_address == issuer_address). \ - order_by(ScheduledEvents.scheduled_datetime, ScheduledEvents.id). \ - all() + events_list: List[ScheduledEvents] = ( + db_session.query(ScheduledEvents) + .filter(ScheduledEvents.status == 0) + .filter(ScheduledEvents.scheduled_datetime <= filter_time) + .filter(ScheduledEvents.issuer_address == issuer_address) + .order_by(ScheduledEvents.scheduled_datetime, ScheduledEvents.id) + .all() + ) return events_list def __release_processing_issuer(self, issuer_address: str): @@ -143,22 +143,25 @@ def __process(self, db_session: Session, events_list: List[ScheduledEvents]): # Get issuer's private key try: - _account = db_session.query(Account). \ - filter(Account.issuer_address == _event.issuer_address). \ - first() - if _account is None: # If issuer does not exist, update the status of the upload to ERROR + _account = ( + db_session.query(Account) + .filter(Account.issuer_address == _event.issuer_address) + .first() + ) + if ( + _account is None + ): # If issuer does not exist, update the status of the upload to ERROR LOG.warning(f"Issuer of the event_id:{_event.id} does not exist") self.__sink_on_finish_event_process( - db_session=db_session, - record_id=_event.id, - status=2 + db_session=db_session, record_id=_event.id, status=2 ) self.__sink_on_error_notification( db_session=db_session, - issuer_address=_event.issuer_address, code=0, + issuer_address=_event.issuer_address, + code=0, scheduled_event_id=_event.event_id, token_type=_event.token_type, - token_address=_event.token_address + token_address=_event.token_address, ) db_session.commit() continue @@ -166,21 +169,22 @@ def __process(self, db_session: Session, events_list: List[ScheduledEvents]): decrypt_password = E2EEUtils.decrypt(_account.eoa_password) private_key = decode_keyfile_json( raw_keyfile_json=keyfile_json, - password=decrypt_password.encode("utf-8") + password=decrypt_password.encode("utf-8"), ) except Exception: - LOG.exception(f"Could not get the private key of the issuer of id:{_event.id}") + LOG.exception( + f"Could not get the private key of the issuer of id:{_event.id}" + ) self.__sink_on_finish_event_process( - db_session=db_session, - record_id=_event.id, - status=2 + db_session=db_session, record_id=_event.id, status=2 ) self.__sink_on_error_notification( db_session=db_session, - issuer_address=_event.issuer_address, code=1, + issuer_address=_event.issuer_address, + code=1, scheduled_event_id=_event.event_id, token_type=_event.token_type, - token_address=_event.token_address + token_address=_event.token_address, ) db_session.commit() continue @@ -194,7 +198,7 @@ def __process(self, db_session: Session, events_list: List[ScheduledEvents]): IbetShareContract(_event.token_address).update( data=_update_data, tx_from=_event.issuer_address, - private_key=private_key + private_key=private_key, ) elif _event.token_type == TokenType.IBET_STRAIGHT_BOND.value: # Update @@ -203,20 +207,18 @@ def __process(self, db_session: Session, events_list: List[ScheduledEvents]): IbetStraightBondContract(_event.token_address).update( data=_update_data, tx_from=_event.issuer_address, - private_key=private_key + private_key=private_key, ) self.__sink_on_finish_event_process( - db_session=db_session, - record_id=_event.id, - status=1 + db_session=db_session, record_id=_event.id, status=1 ) except ContractRevertError as e: - LOG.warning(f"Transaction reverted: id=<{_event.id}> error_code:<{e.code}> error_msg:<{e.message}>") + LOG.warning( + f"Transaction reverted: id=<{_event.id}> error_code:<{e.code}> error_msg:<{e.message}>" + ) self.__sink_on_finish_event_process( - db_session=db_session, - record_id=_event.id, - status=2 + db_session=db_session, record_id=_event.id, status=2 ) self.__sink_on_error_notification( db_session=db_session, @@ -224,14 +226,12 @@ def __process(self, db_session: Session, events_list: List[ScheduledEvents]): code=2, scheduled_event_id=_event.event_id, token_type=_event.token_type, - token_address=_event.token_address + token_address=_event.token_address, ) except SendTransactionError: LOG.warning(f"Failed to send transaction: id=<{_event.id}>") self.__sink_on_finish_event_process( - db_session=db_session, - record_id=_event.id, - status=2 + db_session=db_session, record_id=_event.id, status=2 ) self.__sink_on_error_notification( db_session=db_session, @@ -239,28 +239,34 @@ def __process(self, db_session: Session, events_list: List[ScheduledEvents]): code=2, scheduled_event_id=_event.event_id, token_type=_event.token_type, - token_address=_event.token_address + token_address=_event.token_address, ) db_session.commit() LOG.info(f"<{self.thread_num}> Process end: upload_id={_event.id}") @staticmethod - def __sink_on_finish_event_process(db_session: Session, record_id: int, status: int): - scheduled_event_record = db_session.query(ScheduledEvents). \ - filter(ScheduledEvents.id == record_id). \ - first() + def __sink_on_finish_event_process( + db_session: Session, record_id: int, status: int + ): + scheduled_event_record = ( + db_session.query(ScheduledEvents) + .filter(ScheduledEvents.id == record_id) + .first() + ) if scheduled_event_record is not None: scheduled_event_record.status = status db_session.merge(scheduled_event_record) @staticmethod - def __sink_on_error_notification(db_session: Session, - issuer_address: str, - code: int, - scheduled_event_id: str, - token_type: str, - token_address: str): + def __sink_on_error_notification( + db_session: Session, + issuer_address: str, + code: int, + scheduled_event_id: str, + token_type: str, + token_address: str, + ): notification = Notification() notification.notice_id = uuid.uuid4() notification.issuer_address = issuer_address @@ -270,19 +276,17 @@ def __sink_on_error_notification(db_session: Session, notification.metainfo = { "scheduled_event_id": scheduled_event_id, "token_type": token_type, - "token_address": token_address + "token_address": token_address, } db_session.add(notification) class Worker: - def __init__(self, thread_num: int): processor = Processor(thread_num=thread_num) self.processor = processor def run(self): - while True: started_at = time.time() try: @@ -290,10 +294,14 @@ def run(self): except ServiceUnavailableError: LOG.warning("An external service was unavailable") except SQLAlchemyError as sa_err: - LOG.error(f"A database error has occurred: code={sa_err.code}\n{sa_err}") + LOG.error( + f"A database error has occurred: code={sa_err.code}\n{sa_err}" + ) except Exception as ex: LOG.error(ex) - sleeping_time = max(0, SCHEDULED_EVENTS_INTERVAL - (time.time() - started_at)) + sleeping_time = max( + 0, SCHEDULED_EVENTS_INTERVAL - (time.time() - started_at) + ) time.sleep(sleeping_time) diff --git a/batch/processor_update_token.py b/batch/processor_update_token.py index b5d5bd8b..5d7e0fbf 100644 --- a/batch/processor_update_token.py +++ b/batch/processor_update_token.py @@ -16,59 +16,52 @@ SPDX-License-Identifier: Apache-2.0 """ -from datetime import datetime -from typing import ( - List, - Type -) import os import sys import time import uuid +from datetime import datetime +from typing import List, Type from eth_keyfile import decode_keyfile_json from sqlalchemy import create_engine -from sqlalchemy.orm import Session from sqlalchemy.exc import SQLAlchemyError +from sqlalchemy.orm import Session path = os.path.join(os.path.dirname(__file__), "../") sys.path.append(path) -from config import ( - DATABASE_URL, - UPDATE_TOKEN_INTERVAL, - TOKEN_LIST_CONTRACT_ADDRESS -) -from app.utils.contract_utils import ContractUtils -from app.utils.e2ee_utils import E2EEUtils -from app.model.db import ( - Account, - Token, - TokenType, - UpdateToken, - Notification, - NotificationType, - IDXPosition, - UTXO +import batch_log + +from app.exceptions import ( + ContractRevertError, + SendTransactionError, + ServiceUnavailableError, ) from app.model.blockchain import ( - IbetStraightBondContract, IbetShareContract, - TokenListContract + IbetStraightBondContract, + TokenListContract, ) from app.model.blockchain.tx_params.ibet_share import ( - UpdateParams as IbetShareUpdateParams + UpdateParams as IbetShareUpdateParams, ) from app.model.blockchain.tx_params.ibet_straight_bond import ( - UpdateParams as IbetStraightBondUpdateParams + UpdateParams as IbetStraightBondUpdateParams, ) - -from app.exceptions import ( - SendTransactionError, - ServiceUnavailableError, - ContractRevertError +from app.model.db import ( + UTXO, + Account, + IDXPosition, + Notification, + NotificationType, + Token, + TokenType, + UpdateToken, ) -import batch_log +from app.utils.contract_utils import ContractUtils +from app.utils.e2ee_utils import E2EEUtils +from config import DATABASE_URL, TOKEN_LIST_CONTRACT_ADDRESS, UPDATE_TOKEN_INTERVAL """ [PROCESSOR-Update-token] @@ -83,7 +76,6 @@ class Processor: - def process(self): db_session = Session(autocommit=False, autoflush=True, bind=db_engine) try: @@ -97,15 +89,19 @@ def process(self): # Get issuer's private key try: - _account = db_session.query(Account). \ - filter(Account.issuer_address == _update_token.issuer_address). \ - first() - if _account is None: # If issuer does not exist, update the status of the upload to ERROR - LOG.warning(f"Issuer of the event_id:{_update_token.id} does not exist") + _account = ( + db_session.query(Account) + .filter(Account.issuer_address == _update_token.issuer_address) + .first() + ) + if ( + _account is None + ): # If issuer does not exist, update the status of the upload to ERROR + LOG.warning( + f"Issuer of the event_id:{_update_token.id} does not exist" + ) self.__sink_on_finish_update_process( - db_session=db_session, - record_id=_update_token.id, - status=2 + db_session=db_session, record_id=_update_token.id, status=2 ) self.__sink_on_error_notification( db_session=db_session, @@ -114,21 +110,23 @@ def process(self): code=0, token_address=_update_token.token_address, token_type=_update_token.type, - arguments=_update_token.arguments) + arguments=_update_token.arguments, + ) db_session.commit() continue keyfile_json = _account.keyfile decrypt_password = E2EEUtils.decrypt(_account.eoa_password) private_key = decode_keyfile_json( raw_keyfile_json=keyfile_json, - password=decrypt_password.encode("utf-8") + password=decrypt_password.encode("utf-8"), ) except Exception as err: - LOG.exception(f"Could not get the private key of the issuer of id:{_update_token.id}", err) + LOG.exception( + f"Could not get the private key of the issuer of id:{_update_token.id}", + err, + ) self.__sink_on_finish_update_process( - db_session=db_session, - record_id=_update_token.id, - status=2 + db_session=db_session, record_id=_update_token.id, status=2 ) self.__sink_on_error_notification( db_session=db_session, @@ -137,7 +135,8 @@ def process(self): code=1, token_address=_update_token.token_address, token_type=_update_token.type, - arguments=_update_token.arguments) + arguments=_update_token.arguments, + ) db_session.commit() continue @@ -148,12 +147,12 @@ def process(self): _update_data = self.__create_update_data( trigger=_update_token.trigger, token_type=TokenType.IBET_SHARE.value, - arguments=_update_token.arguments + arguments=_update_token.arguments, ) IbetShareContract(_update_token.token_address).update( data=_update_data, tx_from=_update_token.issuer_address, - private_key=private_key + private_key=private_key, ) token_template = TokenType.IBET_SHARE.value @@ -161,23 +160,22 @@ def process(self): _update_data = self.__create_update_data( trigger=_update_token.trigger, token_type=TokenType.IBET_STRAIGHT_BOND.value, - arguments=_update_token.arguments + arguments=_update_token.arguments, ) IbetStraightBondContract(_update_token.token_address).update( data=_update_data, tx_from=_update_token.issuer_address, - private_key=private_key + private_key=private_key, ) token_template = TokenType.IBET_STRAIGHT_BOND.value if _update_token.trigger == "Issue": - # Register token_address token list TokenListContract(TOKEN_LIST_CONTRACT_ADDRESS).register( token_address=_update_token.token_address, token_template=token_template, tx_from=_update_token.issuer_address, - private_key=private_key + private_key=private_key, ) # Insert initial position data @@ -191,30 +189,34 @@ def process(self): db_session.add(_position) # Insert issuer's UTXO data - _token = db_session.query(Token). \ - filter(Token.token_address == _update_token.token_address). \ - first() - block = ContractUtils.get_block_by_transaction_hash(_token.tx_hash) + _token = ( + db_session.query(Token) + .filter(Token.token_address == _update_token.token_address) + .first() + ) + block = ContractUtils.get_block_by_transaction_hash( + _token.tx_hash + ) _utxo = UTXO() _utxo.transaction_hash = _token.tx_hash _utxo.account_address = _update_token.issuer_address _utxo.token_address = _update_token.token_address _utxo.amount = _update_token.arguments.get("total_supply") _utxo.block_number = block["number"] - _utxo.block_timestamp = datetime.utcfromtimestamp(block["timestamp"]) + _utxo.block_timestamp = datetime.utcfromtimestamp( + block["timestamp"] + ) db_session.add(_utxo) self.__sink_on_finish_update_process( - db_session=db_session, - record_id=_update_token.id, - status=1 + db_session=db_session, record_id=_update_token.id, status=1 ) except ContractRevertError as e: - LOG.warning(f"Transaction reverted: id=<{_update_token.id}> error_code:<{e.code}> error_msg:<{e.message}>") + LOG.warning( + f"Transaction reverted: id=<{_update_token.id}> error_code:<{e.code}> error_msg:<{e.message}>" + ) self.__sink_on_finish_update_process( - db_session=db_session, - record_id=_update_token.id, - status=2 + db_session=db_session, record_id=_update_token.id, status=2 ) self.__sink_on_error_notification( db_session=db_session, @@ -223,14 +225,13 @@ def process(self): code=2, token_address=_update_token.token_address, token_type=_update_token.type, - arguments=_update_token.arguments) + arguments=_update_token.arguments, + ) except SendTransactionError as tx_err: LOG.warning(f"Failed to send transaction: id=<{_update_token.id}>") LOG.exception(tx_err) self.__sink_on_finish_update_process( - db_session=db_session, - record_id=_update_token.id, - status=2 + db_session=db_session, record_id=_update_token.id, status=2 ) self.__sink_on_error_notification( db_session=db_session, @@ -239,7 +240,8 @@ def process(self): code=2, token_address=_update_token.token_address, token_type=_update_token.type, - arguments=_update_token.arguments) + arguments=_update_token.arguments, + ) db_session.commit() LOG.info(f"Process end: upload_id={_update_token.token_address}") @@ -247,10 +249,12 @@ def process(self): db_session.close() def __get_update_token_list(self, db_session: Session) -> List[Type[UpdateToken]]: - _update_token_list = db_session.query(UpdateToken). \ - filter(UpdateToken.status == 0). \ - order_by(UpdateToken.id). \ - all() + _update_token_list = ( + db_session.query(UpdateToken) + .filter(UpdateToken.status == 0) + .order_by(UpdateToken.id) + .all() + ) return _update_token_list def __create_update_data(self, trigger, token_type, arguments): @@ -258,15 +262,21 @@ def __create_update_data(self, trigger, token_type, arguments): # NOTE: Items set at the time of issue do not need to be updated. if token_type == TokenType.IBET_SHARE.value: update_data = { - "tradable_exchange_contract_address": arguments.get("tradable_exchange_contract_address"), - "personal_info_contract_address": arguments.get("personal_info_contract_address"), + "tradable_exchange_contract_address": arguments.get( + "tradable_exchange_contract_address" + ), + "personal_info_contract_address": arguments.get( + "personal_info_contract_address" + ), "transferable": arguments.get("transferable"), "status": arguments.get("status"), "is_offering": arguments.get("is_offering"), "contact_information": arguments.get("contact_information"), "privacy_policy": arguments.get("privacy_policy"), - "transfer_approval_required": arguments.get("transfer_approval_required"), - "is_canceled": arguments.get("is_canceled") + "transfer_approval_required": arguments.get( + "transfer_approval_required" + ), + "is_canceled": arguments.get("is_canceled"), } return IbetShareUpdateParams(**update_data) elif token_type == TokenType.IBET_STRAIGHT_BOND.value: @@ -277,41 +287,52 @@ def __create_update_data(self, trigger, token_type, arguments): "status": arguments.get("status"), "is_offering": arguments.get("is_offering"), "is_redeemed": arguments.get("is_redeemed"), - "tradable_exchange_contract_address": arguments.get("tradable_exchange_contract_address"), - "personal_info_contract_address": arguments.get("personal_info_contract_address"), + "tradable_exchange_contract_address": arguments.get( + "tradable_exchange_contract_address" + ), + "personal_info_contract_address": arguments.get( + "personal_info_contract_address" + ), "contact_information": arguments.get("contact_information"), "privacy_policy": arguments.get("privacy_policy"), - "transfer_approval_required": arguments.get("transfer_approval_required"), + "transfer_approval_required": arguments.get( + "transfer_approval_required" + ), } return IbetStraightBondUpdateParams(**update_data) return @staticmethod - def __sink_on_finish_update_process(db_session: Session, record_id: int, status: int): - - _update_token = db_session.query(UpdateToken). \ - filter(UpdateToken.id == record_id). \ - first() + def __sink_on_finish_update_process( + db_session: Session, record_id: int, status: int + ): + _update_token = ( + db_session.query(UpdateToken).filter(UpdateToken.id == record_id).first() + ) if _update_token is not None: _update_token.status = status db_session.merge(_update_token) if _update_token.trigger == "Issue": - _token = db_session.query(Token). \ - filter(Token.token_address == _update_token.token_address). \ - first() + _token = ( + db_session.query(Token) + .filter(Token.token_address == _update_token.token_address) + .first() + ) if _token is not None: _token.token_status = status db_session.merge(_token) @staticmethod - def __sink_on_error_notification(db_session: Session, - issuer_address: str, - notice_type: str, - code: int, - token_address: str, - token_type: str, - arguments: dict): + def __sink_on_error_notification( + db_session: Session, + issuer_address: str, + notice_type: str, + code: int, + token_address: str, + token_type: str, + arguments: dict, + ): notification = Notification() notification.notice_id = uuid.uuid4() notification.issuer_address = issuer_address @@ -321,7 +342,7 @@ def __sink_on_error_notification(db_session: Session, notification.metainfo = { "token_address": token_address, "token_type": token_type, - "arguments": arguments + "arguments": arguments, } db_session.add(notification) diff --git a/cmd/explorer/src/connector/__init__.py b/cmd/explorer/src/connector/__init__.py index 532829c4..34464b59 100644 --- a/cmd/explorer/src/connector/__init__.py +++ b/cmd/explorer/src/connector/__init__.py @@ -22,6 +22,7 @@ from typing import Any from aiohttp import ClientSession + from cache import AsyncTTL path = os.path.join(os.path.dirname(__file__), "../../../../") @@ -59,8 +60,13 @@ def dict_factory(x: list[tuple[str, Any]]): @AsyncTTL(time_to_live=3600, skip_args=1) -async def list_block_data(session: ClientSession, url: str, query: ListBlockDataQuery) -> BlockDataListResponse: - async with session.get(url=f"{url}/blockchain_explorer/block_data", params=asdict(query, dict_factory=dict_factory)) as resp: +async def list_block_data( + session: ClientSession, url: str, query: ListBlockDataQuery +) -> BlockDataListResponse: + async with session.get( + url=f"{url}/blockchain_explorer/block_data", + params=asdict(query, dict_factory=dict_factory), + ) as resp: data = await resp.json() if resp.status == 404: raise ApiNotEnabledException(data) @@ -68,15 +74,24 @@ async def list_block_data(session: ClientSession, url: str, query: ListBlockData @AsyncTTL(time_to_live=3600, skip_args=1) -async def get_block_data(session: ClientSession, url: str, block_number: int) -> BlockDataDetail: - async with session.get(url=f"{url}/blockchain_explorer/block_data/{block_number}") as resp: +async def get_block_data( + session: ClientSession, url: str, block_number: int +) -> BlockDataDetail: + async with session.get( + url=f"{url}/blockchain_explorer/block_data/{block_number}" + ) as resp: data = await resp.json() return BlockDataDetail.parse_obj(data) @AsyncTTL(time_to_live=3600, skip_args=1) -async def list_tx_data(session: ClientSession, url: str, query: ListTxDataQuery) -> TxDataListResponse: - async with session.get(url=f"{url}/blockchain_explorer/tx_data", params=asdict(query, dict_factory=dict_factory)) as resp: +async def list_tx_data( + session: ClientSession, url: str, query: ListTxDataQuery +) -> TxDataListResponse: + async with session.get( + url=f"{url}/blockchain_explorer/tx_data", + params=asdict(query, dict_factory=dict_factory), + ) as resp: data = await resp.json() return TxDataListResponse.parse_obj(data) diff --git a/cmd/explorer/src/gui/explorer.py b/cmd/explorer/src/gui/explorer.py index bd67ecc5..384e5f7e 100644 --- a/cmd/explorer/src/gui/explorer.py +++ b/cmd/explorer/src/gui/explorer.py @@ -19,14 +19,13 @@ import os from pydantic import ValidationError -from textual.app import App, ReturnType -from textual.binding import Binding - from src.connector import ApiNotEnabledException +from src.gui.error import Error from src.gui.screen.block import BlockScreen from src.gui.screen.traceback import TracebackScreen from src.gui.screen.transaction import TransactionScreen -from src.gui.error import Error +from textual.app import App, ReturnType +from textual.binding import Binding from app.model.schema import ListBlockDataQuery, ListTxDataQuery @@ -44,7 +43,10 @@ class ExplorerApp(App): # Base App Setting BINDINGS = [Binding("ctrl+c", "quit", "Quit")] CSS_PATH = f"{os.path.dirname(os.path.abspath(__file__))}/explorer.css" - SCREENS = {"transaction_screen": TransactionScreen, "traceback_screen": TracebackScreen} + SCREENS = { + "transaction_screen": TransactionScreen, + "traceback_screen": TracebackScreen, + } # Injectable App Setting url: str @@ -65,7 +67,9 @@ async def run_async( ) -> ReturnType | None: self.url = url self.lot_size = lot_size - return await super().run_async(headless=headless, size=size, auto_pilot=auto_pilot) + return await super().run_async( + headless=headless, size=size, auto_pilot=auto_pilot + ) ################################################## # Event diff --git a/cmd/explorer/src/gui/rendarable/block_detail_info.py b/cmd/explorer/src/gui/rendarable/block_detail_info.py index bd8343fb..14f25453 100644 --- a/cmd/explorer/src/gui/rendarable/block_detail_info.py +++ b/cmd/explorer/src/gui/rendarable/block_detail_info.py @@ -18,15 +18,15 @@ """ import time -from app.model.schema import BlockDataDetail from rich.console import Group from rich.panel import Panel from rich.progress_bar import ProgressBar from rich.table import Table from rich.text import Text - from src.utils.time import human_time, unix_to_iso +from app.model.schema import BlockDataDetail + class BlockDetailInfo: def __init__(self, block_detail: BlockDataDetail) -> None: @@ -39,33 +39,50 @@ def __rich__(self) -> Group: basic_table.add_column(style="deep_pink2 bold") basic_table.add_column() - basic_table.add_row(Text.from_markup("Block Height:"), str(self.block_detail.number)) + basic_table.add_row( + Text.from_markup("Block Height:"), str(self.block_detail.number) + ) basic_table.add_row( Text.from_markup("Timestamp:"), f"{human_time(current - self.block_detail.timestamp)} ({unix_to_iso(self.block_detail.timestamp)})", ) basic_table.add_row( - Text.from_markup("Transactions:"), f"{len(self.block_detail.transactions)} transactions in this block" + Text.from_markup("Transactions:"), + f"{len(self.block_detail.transactions)} transactions in this block", ) - content_table = Table(box=None, expand=False, show_header=False, show_edge=False) + content_table = Table( + box=None, expand=False, show_header=False, show_edge=False + ) content_table.add_column(style="deep_pink2 bold") content_table.add_column() content_table.add_column() - content_table.add_row(Text.from_markup("Total Difficulty:"), str(self.block_detail.difficulty), "") + content_table.add_row( + Text.from_markup("Total Difficulty:"), str(self.block_detail.difficulty), "" + ) content_table.add_row( Text.from_markup("Gas Used:"), f"{self.block_detail.gas_used} ({(self.block_detail.gas_used/self.block_detail.gas_limit)*100:.4f} %)", - ProgressBar(completed=(self.block_detail.gas_used / self.block_detail.gas_limit) * 100, width=10), + ProgressBar( + completed=(self.block_detail.gas_used / self.block_detail.gas_limit) + * 100, + width=10, + ), + ) + content_table.add_row( + Text.from_markup("Gas Limit:"), f"{self.block_detail.gas_limit}" "" + ) + content_table.add_row( + Text.from_markup("Size:"), f"{self.block_detail.size} Bytes" "" ) - content_table.add_row(Text.from_markup("Gas Limit:"), f"{self.block_detail.gas_limit}" "") - content_table.add_row(Text.from_markup("Size:"), f"{self.block_detail.size} Bytes" "") hash_table = Table(box=None, expand=False, show_header=False, show_edge=False) hash_table.add_column(style="deep_pink2 bold") hash_table.add_column() hash_table.add_row(Text.from_markup("Hash:"), self.block_detail.hash) - hash_table.add_row(Text.from_markup("Parent Hash:"), self.block_detail.parent_hash) + hash_table.add_row( + Text.from_markup("Parent Hash:"), self.block_detail.parent_hash + ) hash_table.add_row("StateRoot: ", self.block_detail.state_root) hash_table.add_row("Nonce: ", self.block_detail.nonce) diff --git a/cmd/explorer/src/gui/rendarable/tx_detail_info.py b/cmd/explorer/src/gui/rendarable/tx_detail_info.py index f0e6e039..49098eb5 100644 --- a/cmd/explorer/src/gui/rendarable/tx_detail_info.py +++ b/cmd/explorer/src/gui/rendarable/tx_detail_info.py @@ -45,15 +45,21 @@ def __rich__(self) -> Group: common_table.add_row("Gas Price:", str(self.tx_detail.gas_price)) common_table.add_row("Gas:", str(self.tx_detail.gas)) - contract_table = Table(box=None, expand=False, show_header=False, show_edge=False) + contract_table = Table( + box=None, expand=False, show_header=False, show_edge=False + ) contract_table.add_column(style="deep_pink2 bold") contract_table.add_row("Contract Name:", self.tx_detail.contract_name) contract_table.add_row("Contract Function:", self.tx_detail.contract_function) if self.tx_detail.contract_parameters is not None: - function_arguments_table = Table(box=None, expand=False, show_header=False, show_edge=False) + function_arguments_table = Table( + box=None, expand=False, show_header=False, show_edge=False + ) for k, v in self.tx_detail.contract_parameters.items(): function_arguments_table.add_row(f"{k}: ", str(v)) - contract_table.add_row("Contract Function Arguments:", Panel(function_arguments_table)) + contract_table.add_row( + "Contract Function Arguments:", Panel(function_arguments_table) + ) return Group( Panel(common_table, expand=True, title="Common", title_align="left"), diff --git a/cmd/explorer/src/gui/screen/block.py b/cmd/explorer/src/gui/screen/block.py index f35b012e..eea7fc78 100644 --- a/cmd/explorer/src/gui/screen/block.py +++ b/cmd/explorer/src/gui/screen/block.py @@ -21,27 +21,8 @@ from datetime import datetime from typing import Optional -from aiohttp import ( - ClientSession, - ClientTimeout, - TCPConnector -) +from aiohttp import ClientSession, ClientTimeout, TCPConnector from rich.text import Text -from textual.app import ComposeResult -from textual.binding import Binding -from textual.containers import ( - Horizontal, - Vertical -) -from textual.reactive import Reactive -from textual.widgets import ( - Button, - DataTable, - Footer, - Label, - Static -) - from src import connector from src.gui.consts import ID from src.gui.error import Error @@ -51,13 +32,15 @@ from src.gui.widget.block_list_view import ( BlockListQueryPanel, BlockListSummaryPanel, - BlockListView -) -from src.gui.widget.menu import ( - Menu, - MenuInstruction + BlockListView, ) +from src.gui.widget.menu import Menu, MenuInstruction from src.gui.widget.query_panel import QuerySetting +from textual.app import ComposeResult +from textual.binding import Binding +from textual.containers import Horizontal, Vertical +from textual.reactive import Reactive +from textual.widgets import Button, DataTable, Footer, Label, Static from app.model.schema import ( BlockDataDetail, @@ -77,7 +60,9 @@ class BlockScreen(TuiScreen): mutex_reload_block = Reactive(Lock()) background_lock: Optional[Event] = None - def __init__(self, name: str | None = None, id: str | None = None, classes: str | None = None): + def __init__( + self, name: str | None = None, id: str | None = None, classes: str | None = None + ): super().__init__(name=name, id=id, classes=classes) self.base_url = self.tui.url self.refresh_rate = 5.0 @@ -87,16 +72,20 @@ def compose(self) -> ComposeResult: yield Horizontal( Vertical( Horizontal( - Label(Text.from_markup(" [bold]ibet-Wallet-API BC Explorer[/bold]")), + Label(Text.from_markup(" [bold]ibet-Prime BC Explorer[/bold]")), Label(" | "), - Label("Fetching current block...", id=ID.BLOCK_CURRENT_BLOCK_NUMBER), + Label( + "Fetching current block...", id=ID.BLOCK_CURRENT_BLOCK_NUMBER + ), Label(" | "), Label("Fetching current status...", id=ID.BLOCK_IS_SYNCED), Label(" | "), Label("Loading...", id=ID.BLOCK_NOTION), id=ID.BLOCK_SCREEN_HEADER, ), - Horizontal(BlockListView(classes="column"), self.block_detail_header_widget), + Horizontal( + BlockListView(classes="column"), self.block_detail_header_widget + ), classes="column", ) ) @@ -167,17 +156,22 @@ async def on_data_table_row_selected(self, event: DataTable.RowSelected) -> None MenuInstruction( block_number=selected_row[0], block_hash=selected_row[3], - selected_row=event.cursor_row + selected_row=event.cursor_row, ) ) self.add_class("menu") self.query(BlockListTable)[0].can_focus = False def reload_block(self) -> None: - if self.tui.state.current_block_number is None or self.tui.state.block_list_query is None: + if ( + self.tui.state.current_block_number is None + or self.tui.state.block_list_query is None + ): return - self.query_one(BlockListQueryPanel).block_list_query = self.tui.state.block_list_query + self.query_one( + BlockListQueryPanel + ).block_list_query = self.tui.state.block_list_query asyncio.create_task(self.fetch_block_list()) ################################################## @@ -188,7 +182,10 @@ def action_edit_query(self) -> None: """ Occurs when keybind related to `edit_query` is called. """ - if self.tui.state.current_block_number is None or self.tui.state.block_list_query is None: + if ( + self.tui.state.current_block_number is None + or self.tui.state.block_list_query is None + ): return self.query_one(QuerySetting).show() @@ -200,9 +197,13 @@ def action_edit_query(self) -> None: async def fetch_sync_status(self): async with TCPConnector(limit=2, keepalive_timeout=0) as tcp_connector: - async with ClientSession(connector=tcp_connector, timeout=ClientTimeout(30)) as session: + async with ClientSession( + connector=tcp_connector, timeout=ClientTimeout(30) + ) as session: try: - block_number_response: BlockNumberResponse = await connector.get_block_number(session, self.base_url) + block_number_response: BlockNumberResponse = ( + await connector.get_block_number(session, self.base_url) + ) block_number = block_number_response.block_number except Exception as e: if hasattr(self, "emit_no_wait"): @@ -210,11 +211,16 @@ async def fetch_sync_status(self): return self.update_current_block(block_number) self.update_is_synced(True) - if self.tui.state.current_block_number is None and self.tui.state.block_list_query is None: + if ( + self.tui.state.current_block_number is None + and self.tui.state.block_list_query is None + ): # initialize block list query query = ListBlockDataQuery() query.to_block_number = block_number - query.from_block_number = max(block_number - self.tui.lot_size - 1, 0) + query.from_block_number = max( + block_number - self.tui.lot_size - 1, 0 + ) query.sort_order = SortOrder.DESC self.tui.state.block_list_query = query self.query_one(BlockListQueryPanel).block_list_query = query @@ -228,16 +234,22 @@ async def fetch_block_list(self) -> None: self.query_one(BlockListSummaryPanel).loading = True await asyncio.sleep(5) async with TCPConnector(limit=1, keepalive_timeout=0) as tcp_connector: - async with ClientSession(connector=tcp_connector, timeout=ClientTimeout(30)) as session: + async with ClientSession( + connector=tcp_connector, timeout=ClientTimeout(30) + ) as session: try: - block_data_list: BlockDataListResponse = await connector.list_block_data( - session, self.base_url, self.tui.state.block_list_query + block_data_list: BlockDataListResponse = ( + await connector.list_block_data( + session, self.base_url, self.tui.state.block_list_query + ) ) except Exception as e: if hasattr(self, "emit_no_wait"): self.emit_no_wait(Error(e, self)) return - self.query_one(BlockListTable).update_rows(block_data_list.block_data) + self.query_one(BlockListTable).update_rows( + block_data_list.block_data + ) self.query_one(BlockListSummaryPanel).loaded_time = datetime.now() finally: @@ -245,7 +257,9 @@ async def fetch_block_list(self) -> None: async def fetch_block_detail(self, block_number: int): async with TCPConnector(limit=1, keepalive_timeout=0) as tcp_connector: - async with ClientSession(connector=tcp_connector, timeout=ClientTimeout(30)) as session: + async with ClientSession( + connector=tcp_connector, timeout=ClientTimeout(30) + ) as session: try: block_detail: BlockDataDetail = await connector.get_block_data( session, @@ -259,8 +273,14 @@ async def fetch_block_detail(self, block_number: int): self.query_one(BlockDetailView).block_detail = block_detail def update_current_block(self, latest_block_number: int): - self.query_one(f"#{ID.BLOCK_CURRENT_BLOCK_NUMBER}", Static).update(f"Current Block: {latest_block_number}") + self.query_one(f"#{ID.BLOCK_CURRENT_BLOCK_NUMBER}", Static).update( + f"Current Block: {latest_block_number}" + ) def update_is_synced(self, is_synced: bool): - self.query_one(f"#{ID.BLOCK_IS_SYNCED}", Static).update(f"Is Synced: {is_synced}") - self.query_one(f"#{ID.BLOCK_NOTION}", Static).update(f"Press [E] To Load Block List") + self.query_one(f"#{ID.BLOCK_IS_SYNCED}", Static).update( + f"Is Synced: {is_synced}" + ) + self.query_one(f"#{ID.BLOCK_NOTION}", Static).update( + f"Press [E] To Load Block List" + ) diff --git a/cmd/explorer/src/gui/screen/traceback.py b/cmd/explorer/src/gui/screen/traceback.py index c23e6b85..eabfc891 100644 --- a/cmd/explorer/src/gui/screen/traceback.py +++ b/cmd/explorer/src/gui/screen/traceback.py @@ -16,13 +16,12 @@ SPDX-License-Identifier: Apache-2.0 """ -from textual.app import ComposeResult -from textual.binding import Binding -from textual.widgets import Footer - from src.gui.screen.base import TuiScreen from src.gui.widget.block_list_table import BlockListTable from src.gui.widget.traceback import TracebackWidget +from textual.app import ComposeResult +from textual.binding import Binding +from textual.widgets import Footer class TracebackScreen(TuiScreen): diff --git a/cmd/explorer/src/gui/screen/transaction.py b/cmd/explorer/src/gui/screen/transaction.py index 659e79ca..d0459ae6 100644 --- a/cmd/explorer/src/gui/screen/transaction.py +++ b/cmd/explorer/src/gui/screen/transaction.py @@ -18,11 +18,6 @@ """ from aiohttp import ClientSession, ClientTimeout, TCPConnector from rich.text import Text -from textual.app import ComposeResult -from textual.binding import Binding -from textual.containers import Horizontal, Vertical -from textual.widgets import DataTable, Footer, Label - from src import connector from src.gui.consts import ID from src.gui.screen.base import TuiScreen @@ -30,6 +25,10 @@ from src.gui.widget.tx_detail_view import TxDetailView from src.gui.widget.tx_list_table import TxListTable from src.gui.widget.tx_list_view import TxListView +from textual.app import ComposeResult +from textual.binding import Binding +from textual.containers import Horizontal, Vertical +from textual.widgets import DataTable, Footer, Label from app.model.schema.bc_explorer import TxDataDetail @@ -41,12 +40,14 @@ def compose(self) -> ComposeResult: yield Horizontal( Vertical( Horizontal( - Label(Text.from_markup(" [bold]ibet-Wallet-API BC Explorer[/bold]")), + Label(Text.from_markup(" [bold]ibet-Prime BC Explorer[/bold]")), Label(" | "), Label(f"Selected block: -", id=ID.TX_SELECTED_BLOCK_NUMBER), id="tx_list_header", ), - Horizontal(TxListView(classes="column"), TxDetailView(classes="column")), + Horizontal( + TxListView(classes="column"), TxDetailView(classes="column") + ), classes="column", ) ) @@ -74,7 +75,9 @@ async def on_data_table_row_selected(self, event: DataTable.RowSelected) -> None tx_hash = selected_row[0] async with TCPConnector(limit=1, keepalive_timeout=0) as tcp_connector: - async with ClientSession(connector=tcp_connector, timeout=ClientTimeout(30)) as session: + async with ClientSession( + connector=tcp_connector, timeout=ClientTimeout(30) + ) as session: tx_detail: TxDataDetail = await connector.get_tx_data( session, self.tui.url, @@ -94,9 +97,13 @@ async def on_screen_resume(self): """ if self.tui.state.tx_list_query is not None: async with TCPConnector(limit=1, keepalive_timeout=0) as tcp_connector: - async with ClientSession(connector=tcp_connector, timeout=ClientTimeout(30)) as session: + async with ClientSession( + connector=tcp_connector, timeout=ClientTimeout(30) + ) as session: tx_list = await connector.list_tx_data( - session=session, url=self.tui.url, query=self.tui.state.tx_list_query + session=session, + url=self.tui.url, + query=self.tui.state.tx_list_query, ) self.query_one(TxListTable).update_rows(tx_list.tx_data) self.query_one(f"#{ID.TX_SELECTED_BLOCK_NUMBER}", Label).update( diff --git a/cmd/explorer/src/gui/widget/block_detail_view.py b/cmd/explorer/src/gui/widget/block_detail_view.py index ae12cc7d..259e6f7e 100644 --- a/cmd/explorer/src/gui/widget/block_detail_view.py +++ b/cmd/explorer/src/gui/widget/block_detail_view.py @@ -21,11 +21,11 @@ from rich.align import Align from rich.panel import Panel from rich.style import Style -from textual.reactive import Reactive, reactive - from src.gui import styles from src.gui.rendarable.block_detail_info import BlockDetailInfo from src.gui.widget.base import TuiWidget +from textual.reactive import Reactive, reactive + from app.model.schema import BlockDataDetail @@ -39,7 +39,9 @@ def watch_block_detail(self, old: BlockDetailInfo, new: BlockDetailInfo): self.render() def render(self) -> Panel: - block_detail: Union[Align, BlockDetailInfo] = Align.center("Press [E] to set query", vertical="middle") + block_detail: Union[Align, BlockDetailInfo] = Align.center( + "Press [E] to set query", vertical="middle" + ) style: Style | Literal["none"] = Style(bgcolor="#004578") if self.block_detail is not None: diff --git a/cmd/explorer/src/gui/widget/block_list_table.py b/cmd/explorer/src/gui/widget/block_list_table.py index 84110636..1bd0ea53 100644 --- a/cmd/explorer/src/gui/widget/block_list_table.py +++ b/cmd/explorer/src/gui/widget/block_list_table.py @@ -20,12 +20,12 @@ from typing import Iterable from rich.progress_bar import ProgressBar +from src.utils.time import human_time from textual.binding import Binding from textual.coordinate import Coordinate from textual.reactive import reactive from textual.widgets import DataTable -from src.utils.time import human_time from app.model.schema.bc_explorer import BlockData diff --git a/cmd/explorer/src/gui/widget/block_list_view.py b/cmd/explorer/src/gui/widget/block_list_view.py index d7625d61..5f77d3cf 100644 --- a/cmd/explorer/src/gui/widget/block_list_view.py +++ b/cmd/explorer/src/gui/widget/block_list_view.py @@ -21,16 +21,16 @@ from rich.panel import Panel from rich.spinner import Spinner from rich.table import Table +from src.gui import styles +from src.gui.consts import ID +from src.gui.widget.base import TuiStatic, TuiWidget +from src.gui.widget.block_list_table import BlockListTable from textual.app import ComposeResult from textual.binding import Binding from textual.containers import Horizontal from textual.reactive import Reactive, reactive from textual.timer import Timer -from src.gui import styles -from src.gui.consts import ID -from src.gui.widget.base import TuiStatic, TuiWidget -from src.gui.widget.block_list_table import BlockListTable from app.model.schema import ListBlockDataQuery @@ -44,7 +44,9 @@ def watch_block_list_query(self, old: ListBlockDataQuery, new: ListBlockDataQuer self.render() def render(self) -> Panel: - content = Table(show_header=True, header_style="bold", show_edge=False, show_lines=False) + content = Table( + show_header=True, header_style="bold", show_edge=False, show_lines=False + ) content.add_column("From", justify="center", width=10) content.add_column("To", justify="center", width=10) content.add_column("Sort", justify="center", width=7) @@ -114,7 +116,9 @@ def update_spinner(self) -> None: self.refresh() def render(self) -> Panel: - content = Table(show_header=True, header_style="bold", show_edge=False, show_lines=False) + content = Table( + show_header=True, header_style="bold", show_edge=False, show_lines=False + ) content.add_column("Loading", justify="center") content.add_column("Only Blocks Including Tx", style="dim", justify="center") content.add_column("Loaded Time", style="dim", justify="center") @@ -122,7 +126,9 @@ def render(self) -> Panel: content.add_row( self._spinner if self.loading else "", f"{self.only_block_filter}", - f"{self.loaded_time.strftime('%Y/%m/%d %H:%M:%S')}" if self.loaded_time is not None else "", + f"{self.loaded_time.strftime('%Y/%m/%d %H:%M:%S')}" + if self.loaded_time is not None + else "", ) style = "none" @@ -149,7 +155,9 @@ def compose(self) -> ComposeResult: BlockListSummaryPanel(classes="column"), id=ID.BLOCK_LIST_DESCRIPTION, ) - yield BlockListTable(name="blocks", complete_refresh=True, id=ID.BLOCK_LIST_TABLE) + yield BlockListTable( + name="blocks", complete_refresh=True, id=ID.BLOCK_LIST_TABLE + ) def action_filter(self): """ diff --git a/cmd/explorer/src/gui/widget/menu.py b/cmd/explorer/src/gui/widget/menu.py index 48a06cf8..fbcf6cf0 100644 --- a/cmd/explorer/src/gui/widget/menu.py +++ b/cmd/explorer/src/gui/widget/menu.py @@ -18,13 +18,12 @@ """ from pydantic import BaseModel from rich.text import Text +from src.gui.consts import ID +from src.gui.widget.base import TuiWidget from textual.app import ComposeResult from textual.binding import Binding from textual.widgets import Button -from src.gui.consts import ID -from src.gui.widget.base import TuiWidget - class MenuInstruction(BaseModel): block_number: int @@ -43,7 +42,11 @@ class Menu(TuiWidget): ix: MenuInstruction | None = None def compose(self) -> ComposeResult: - yield Button(Text.from_markup("\[t] Show Transactions :package:"), id=ID.MENU_SHOW_TX, classes="menubutton") + yield Button( + Text.from_markup("\[t] Show Transactions :package:"), + id=ID.MENU_SHOW_TX, + classes="menubutton", + ) yield Button("\[c] Cancel", id=ID.MENU_CANCEL, classes="menubutton") def show(self, ix: MenuInstruction): diff --git a/cmd/explorer/src/gui/widget/query_panel.py b/cmd/explorer/src/gui/widget/query_panel.py index 36f83852..6c720ee4 100644 --- a/cmd/explorer/src/gui/widget/query_panel.py +++ b/cmd/explorer/src/gui/widget/query_panel.py @@ -18,20 +18,20 @@ """ from typing import TYPE_CHECKING, cast -from app.model.schema import ListBlockDataQuery -from app.model.schema.types import SortOrder from rich.markdown import Markdown +from src.gui.consts import ID +from src.gui.widget.base import TuiWidget +from src.gui.widget.block_list_table import BlockListTable +from src.gui.widget.block_list_view import BlockListQueryPanel +from src.gui.widget.choice import Choices from textual import events from textual.app import ComposeResult from textual.binding import Binding from textual.message import Message from textual.widgets import Button, Input, Label -from src.gui.consts import ID -from src.gui.widget.base import TuiWidget -from src.gui.widget.block_list_table import BlockListTable -from src.gui.widget.block_list_view import BlockListQueryPanel -from src.gui.widget.choice import Choices +from app.model.schema import ListBlockDataQuery +from app.model.schema.types import SortOrder if TYPE_CHECKING: from src.gui.explorer import ExplorerApp @@ -147,7 +147,10 @@ async def on_key(self, event: events.Key) -> None: self.value = self.value[:-1] self.cursor_position -= 1 else: - new_value = self.value[: self.cursor_position - 1] + self.value[self.cursor_position :] + new_value = ( + self.value[: self.cursor_position - 1] + + self.value[self.cursor_position :] + ) if new_value != "": self.value = new_value self.cursor_position -= 1 @@ -157,7 +160,9 @@ class QuerySetting(TuiWidget): BINDINGS = [ Binding("c,q,escape", "cancel()", "Cancel", key_display="Q, C", priority=True), Binding("tab", "focus_next", "Focus Next", show=True, priority=True), - Binding("shift+tab", "focus_previous", "Focus Previous", show=True, priority=True), + Binding( + "shift+tab", "focus_previous", "Focus Previous", show=True, priority=True + ), Binding("enter", "enter()", "Enter", priority=True), Binding("e", "", "", show=False), Binding("ctrl+c", "", "", show=False), @@ -169,9 +174,13 @@ class QuerySetting(TuiWidget): def compose(self) -> ComposeResult: yield Label(Markdown("# Query Setting")) yield Label(Markdown("#### To Block")) - yield ToBlockInput(placeholder="100", name="to_block", id=ID.QUERY_PANEL_TO_BLOCK_INPUT) + yield ToBlockInput( + placeholder="100", name="to_block", id=ID.QUERY_PANEL_TO_BLOCK_INPUT + ) yield Label(Markdown("#### From Block(Auto set)")) - yield Input(placeholder="0", name="from_block", id=ID.QUERY_PANEL_FROM_BLOCK_INPUT) + yield Input( + placeholder="0", name="from_block", id=ID.QUERY_PANEL_FROM_BLOCK_INPUT + ) yield Label(Markdown("#### Sort Order")) yield Choices(["DESC", "ASC"], id=ID.QUERY_PANEL_SORT_ORDER_CHOICE) yield Button("Enter", id=ID.QUERY_PANEL_ENTER) @@ -183,13 +192,21 @@ def show(self): if self.tui.state.block_list_query is not None: query = self.tui.state.block_list_query - self.query_one(f"#{ID.QUERY_PANEL_FROM_BLOCK_INPUT}", Input).value = str(query.from_block_number) - self.query_one(f"#{ID.QUERY_PANEL_TO_BLOCK_INPUT}", Input).value = str(query.to_block_number) + self.query_one(f"#{ID.QUERY_PANEL_FROM_BLOCK_INPUT}", Input).value = str( + query.from_block_number + ) + self.query_one(f"#{ID.QUERY_PANEL_TO_BLOCK_INPUT}", Input).value = str( + query.to_block_number + ) item = "ASC" if query.sort_order.value == 0 else "DESC" - self.query_one(f"#{ID.QUERY_PANEL_SORT_ORDER_CHOICE}", Choices).index = self.query_one( + self.query_one( + f"#{ID.QUERY_PANEL_SORT_ORDER_CHOICE}", Choices + ).index = self.query_one( f"#{ID.QUERY_PANEL_SORT_ORDER_CHOICE}", Choices - ).choices.index(item) + ).choices.index( + item + ) def hide(self) -> None: self.remove_class("visible") @@ -202,9 +219,13 @@ def on_key(self, event: events.Key): """ if event.key == "Enter": self.action_enter() - from_block = self.query_one(f"#{ID.QUERY_PANEL_FROM_BLOCK_INPUT}", Input).value + from_block = self.query_one( + f"#{ID.QUERY_PANEL_FROM_BLOCK_INPUT}", Input + ).value to_block = self.query_one(f"#{ID.QUERY_PANEL_TO_BLOCK_INPUT}", Input).value - sort_order = self.query_one(f"#{ID.QUERY_PANEL_SORT_ORDER_CHOICE}", Choices).current_value() + sort_order = self.query_one( + f"#{ID.QUERY_PANEL_SORT_ORDER_CHOICE}", Choices + ).current_value() query = ListBlockDataQuery( from_block_number=int(from_block), @@ -249,7 +270,9 @@ def action_enter(self): """ from_block = self.query_one(f"#{ID.QUERY_PANEL_FROM_BLOCK_INPUT}", Input).value to_block = self.query_one(f"#{ID.QUERY_PANEL_TO_BLOCK_INPUT}", Input).value - sort_order = self.query_one(f"#{ID.QUERY_PANEL_SORT_ORDER_CHOICE}", Choices).current_value() + sort_order = self.query_one( + f"#{ID.QUERY_PANEL_SORT_ORDER_CHOICE}", Choices + ).current_value() query = ListBlockDataQuery( from_block_number=int(from_block), diff --git a/cmd/explorer/src/gui/widget/traceback.py b/cmd/explorer/src/gui/widget/traceback.py index b9bd2b05..40484aa5 100644 --- a/cmd/explorer/src/gui/widget/traceback.py +++ b/cmd/explorer/src/gui/widget/traceback.py @@ -22,7 +22,6 @@ from rich.panel import Panel from rich.style import Style from rich.traceback import Traceback - from src.gui import styles from src.gui.widget.base import TuiWidget diff --git a/cmd/explorer/src/gui/widget/tx_detail_view.py b/cmd/explorer/src/gui/widget/tx_detail_view.py index c6ba6ccf..00b160a8 100644 --- a/cmd/explorer/src/gui/widget/tx_detail_view.py +++ b/cmd/explorer/src/gui/widget/tx_detail_view.py @@ -18,15 +18,15 @@ """ from typing import Literal, Union -from app.model.schema import TxDataDetail from rich.align import Align from rich.panel import Panel from rich.style import Style -from textual.reactive import Reactive, reactive - from src.gui import styles from src.gui.rendarable.tx_detail_info import TxDetailInfo from src.gui.widget.base import TuiWidget +from textual.reactive import Reactive, reactive + +from app.model.schema import TxDataDetail class TxDetailView(TuiWidget): @@ -45,7 +45,9 @@ def watch_tx_detail(self, old: TxDetailInfo, new: TxDetailInfo): self.render() def render(self) -> Panel: - tx_detail: Union[Align, TxDetailInfo] = Align.center("Not selected", vertical="middle") + tx_detail: Union[Align, TxDetailInfo] = Align.center( + "Not selected", vertical="middle" + ) style: Style | Literal["none"] = Style(bgcolor="#004578") if self.tx_detail is not None: diff --git a/cmd/explorer/src/gui/widget/tx_list_table.py b/cmd/explorer/src/gui/widget/tx_list_table.py index e2ebe11a..213b040d 100644 --- a/cmd/explorer/src/gui/widget/tx_list_table.py +++ b/cmd/explorer/src/gui/widget/tx_list_table.py @@ -18,11 +18,12 @@ """ from typing import Iterable -from app.model.schema.bc_explorer import TxData from textual.binding import Binding from textual.reactive import reactive from textual.widgets import DataTable +from app.model.schema.bc_explorer import TxData + class TxListTable(DataTable): BINDINGS = [ diff --git a/cmd/explorer/src/gui/widget/tx_list_view.py b/cmd/explorer/src/gui/widget/tx_list_view.py index acf0ba15..8fa4b176 100644 --- a/cmd/explorer/src/gui/widget/tx_list_view.py +++ b/cmd/explorer/src/gui/widget/tx_list_view.py @@ -16,19 +16,24 @@ SPDX-License-Identifier: Apache-2.0 """ +from src.gui.widget.base import TuiWidget +from src.gui.widget.tx_list_table import TxListTable from textual.app import ComposeResult from textual.containers import Horizontal from textual.widget import Widget from textual.widgets import Static -from src.gui.widget.base import TuiWidget -from src.gui.widget.tx_list_table import TxListTable - class TxListView(TuiWidget): BINDINGS = [] - def __init__(self, *children: Widget, name: str | None = None, id: str | None = None, classes: str | None = None): + def __init__( + self, + *children: Widget, + name: str | None = None, + id: str | None = None, + classes: str | None = None + ): super().__init__(*children, name=name, id=id, classes=classes) def compose(self) -> ComposeResult: diff --git a/cmd/explorer/src/main.py b/cmd/explorer/src/main.py index c86d3570..82a7d939 100644 --- a/cmd/explorer/src/main.py +++ b/cmd/explorer/src/main.py @@ -16,13 +16,13 @@ SPDX-License-Identifier: Apache-2.0 """ -import logging import asyncio +import logging + logging.getLogger("asyncio").setLevel(logging.WARNING) logging.getLogger("psycopg").setLevel(logging.WARNING) import typer - from src.gui.explorer import ExplorerApp app = typer.Typer(pretty_exceptions_show_locals=False) @@ -30,7 +30,9 @@ @app.command() def run( - url: str = typer.Option("http://localhost:5000", help="ibet-Prime server URL to connect"), + url: str = typer.Option( + "http://localhost:5000", help="ibet-Prime server URL to connect" + ), lot_size: int = typer.Option(100, help="Lot size to fetch Block Data list"), ): explorer = ExplorerApp() diff --git a/config.py b/config.py index 8dcbed15..d9dd9bee 100644 --- a/config.py +++ b/config.py @@ -16,11 +16,11 @@ SPDX-License-Identifier: Apache-2.0 """ -import sys -import os import configparser +import os +import sys -SERVER_NAME = 'ibet-Prime' +SERVER_NAME = "ibet-Prime" #################################################### # Basic settings @@ -32,19 +32,27 @@ NETWORK = os.environ.get("NETWORK") or "IBET" # IBET or IBETFIN # Environment-specific settings -APP_ENV = os.environ.get('APP_ENV') or 'local' +APP_ENV = os.environ.get("APP_ENV") or "local" if APP_ENV != "live": - INI_FILE = os.path.join(os.path.dirname(os.path.realpath(__file__)), f"conf/{APP_ENV}.ini") + INI_FILE = os.path.join( + os.path.dirname(os.path.realpath(__file__)), f"conf/{APP_ENV}.ini" + ) else: if NETWORK == "IBET": # ibet - INI_FILE = os.path.join(os.path.dirname(os.path.realpath(__file__)), f"conf/live.ini") + INI_FILE = os.path.join( + os.path.dirname(os.path.realpath(__file__)), f"conf/live.ini" + ) else: # ibet for Fin - INI_FILE = os.path.join(os.path.dirname(os.path.realpath(__file__)), f"conf/live_fin.ini") + INI_FILE = os.path.join( + os.path.dirname(os.path.realpath(__file__)), f"conf/live_fin.ini" + ) CONFIG = configparser.ConfigParser() CONFIG.read(INI_FILE) # Response validation mode -RESPONSE_VALIDATION_MODE = True if os.environ.get("RESPONSE_VALIDATION_MODE") == "1" else False +RESPONSE_VALIDATION_MODE = ( + True if os.environ.get("RESPONSE_VALIDATION_MODE") == "1" else False +) #################################################### @@ -52,60 +60,89 @@ #################################################### # Database -if 'pytest' in sys.modules: # for unit test - DATABASE_URL = os.environ.get("TEST_DATABASE_URL") or \ - 'postgresql+psycopg://issuerapi:issuerapipass@localhost:5432/issuerapidb_test' +if "pytest" in sys.modules: # for unit test + DATABASE_URL = ( + os.environ.get("TEST_DATABASE_URL") + or "postgresql+psycopg://issuerapi:issuerapipass@localhost:5432/issuerapidb_test" + ) else: - DATABASE_URL = os.environ.get("DATABASE_URL") or \ - 'postgresql+psycopg://issuerapi:issuerapipass@localhost:5432/issuerapidb' -DATABASE_SCHEMA = os.environ.get('DATABASE_SCHEMA') -DB_ECHO = True if CONFIG['database']['echo'] == 'yes' else False + DATABASE_URL = ( + os.environ.get("DATABASE_URL") + or "postgresql+psycopg://issuerapi:issuerapipass@localhost:5432/issuerapidb" + ) +DATABASE_SCHEMA = os.environ.get("DATABASE_SCHEMA") +DB_ECHO = True if CONFIG["database"]["echo"] == "yes" else False # Logging -LOG_LEVEL = CONFIG['logging']['level'] -AUTH_LOGFILE = os.environ.get('AUTH_LOGFILE') or '/dev/stdout' -ACCESS_LOGFILE = os.environ.get('ACCESS_LOGFILE') or '/dev/stdout' +LOG_LEVEL = CONFIG["logging"]["level"] +AUTH_LOGFILE = os.environ.get("AUTH_LOGFILE") or "/dev/stdout" +ACCESS_LOGFILE = os.environ.get("ACCESS_LOGFILE") or "/dev/stdout" #################################################### # Blockchain monitoring settings #################################################### # Block synchronization monitoring interval [sec] -BLOCK_SYNC_STATUS_SLEEP_INTERVAL = int(os.environ.get("BLOCK_SYNC_STATUS_SLEEP_INTERVAL")) \ - if os.environ.get("BLOCK_SYNC_STATUS_SLEEP_INTERVAL") else 3 +BLOCK_SYNC_STATUS_SLEEP_INTERVAL = ( + int(os.environ.get("BLOCK_SYNC_STATUS_SLEEP_INTERVAL")) + if os.environ.get("BLOCK_SYNC_STATUS_SLEEP_INTERVAL") + else 3 +) # Number of monitoring data period -BLOCK_SYNC_STATUS_CALC_PERIOD = int(os.environ.get("BLOCK_SYNC_STATUS_CALC_PERIOD")) \ - if os.environ.get("BLOCK_SYNC_STATUS_CALC_PERIOD") else 3 +BLOCK_SYNC_STATUS_CALC_PERIOD = ( + int(os.environ.get("BLOCK_SYNC_STATUS_CALC_PERIOD")) + if os.environ.get("BLOCK_SYNC_STATUS_CALC_PERIOD") + else 3 +) # Threshold for remaining block synchronization # - Threshold for difference between highestBlock and currentBlock -BLOCK_SYNC_REMAINING_THRESHOLD = int(os.environ.get("BLOCK_SYNC_REMAINING_THRESHOLD", 2)) +BLOCK_SYNC_REMAINING_THRESHOLD = int( + os.environ.get("BLOCK_SYNC_REMAINING_THRESHOLD", 2) +) # Threshold of block generation speed for judging synchronous stop [%] if APP_ENV == "local": - BLOCK_GENERATION_SPEED_THRESHOLD = int(os.environ.get("BLOCK_GENERATION_SPEED_THRESHOLD")) \ - if os.environ.get("BLOCK_GENERATION_SPEED_THRESHOLD") else 0 + BLOCK_GENERATION_SPEED_THRESHOLD = ( + int(os.environ.get("BLOCK_GENERATION_SPEED_THRESHOLD")) + if os.environ.get("BLOCK_GENERATION_SPEED_THRESHOLD") + else 0 + ) else: - BLOCK_GENERATION_SPEED_THRESHOLD = int(os.environ.get("BLOCK_GENERATION_SPEED_THRESHOLD")) \ - if os.environ.get("BLOCK_GENERATION_SPEED_THRESHOLD") else 20 + BLOCK_GENERATION_SPEED_THRESHOLD = ( + int(os.environ.get("BLOCK_GENERATION_SPEED_THRESHOLD")) + if os.environ.get("BLOCK_GENERATION_SPEED_THRESHOLD") + else 20 + ) #################################################### # Web3 settings #################################################### # Provider -WEB3_HTTP_PROVIDER = os.environ.get('WEB3_HTTP_PROVIDER') or 'http://localhost:8545' -WEB3_HTTP_PROVIDER_STANDBY = [node.strip() for node in os.environ.get("WEB3_HTTP_PROVIDER_STANDBY").split(",")] \ - if os.environ.get("WEB3_HTTP_PROVIDER_STANDBY") else [] +WEB3_HTTP_PROVIDER = os.environ.get("WEB3_HTTP_PROVIDER") or "http://localhost:8545" +WEB3_HTTP_PROVIDER_STANDBY = ( + [node.strip() for node in os.environ.get("WEB3_HTTP_PROVIDER_STANDBY").split(",")] + if os.environ.get("WEB3_HTTP_PROVIDER_STANDBY") + else [] +) # Chain ID CHAIN_ID = int(os.environ.get("CHAIN_ID")) if os.environ.get("CHAIN_ID") else 2017 # Gas limit -TX_GAS_LIMIT = int(os.environ.get("TX_GAS_LIMIT")) if os.environ.get("TX_GAS_LIMIT") else 6000000 - -WEB3_REQUEST_RETRY_COUNT = int(os.environ.get("WEB3_REQUEST_RETRY_COUNT")) if os.environ.get( - "WEB3_REQUEST_RETRY_COUNT") else 3 -WEB3_REQUEST_WAIT_TIME = int(os.environ.get("WEB3_REQUEST_WAIT_TIME")) \ - if os.environ.get("WEB3_REQUEST_WAIT_TIME") else BLOCK_SYNC_STATUS_SLEEP_INTERVAL # Same batch interval +TX_GAS_LIMIT = ( + int(os.environ.get("TX_GAS_LIMIT")) if os.environ.get("TX_GAS_LIMIT") else 6000000 +) + +WEB3_REQUEST_RETRY_COUNT = ( + int(os.environ.get("WEB3_REQUEST_RETRY_COUNT")) + if os.environ.get("WEB3_REQUEST_RETRY_COUNT") + else 3 +) +WEB3_REQUEST_WAIT_TIME = ( + int(os.environ.get("WEB3_REQUEST_WAIT_TIME")) + if os.environ.get("WEB3_REQUEST_WAIT_TIME") + else BLOCK_SYNC_STATUS_SLEEP_INTERVAL +) # Same batch interval #################################################### @@ -114,12 +151,16 @@ # Default addresses ZERO_ADDRESS = "0x0000000000000000000000000000000000000000" -TOKEN_LIST_CONTRACT_ADDRESS = os.environ.get('TOKEN_LIST_CONTRACT_ADDRESS') -E2E_MESSAGING_CONTRACT_ADDRESS = os.environ.get('E2E_MESSAGING_CONTRACT_ADDRESS') +TOKEN_LIST_CONTRACT_ADDRESS = os.environ.get("TOKEN_LIST_CONTRACT_ADDRESS") +E2E_MESSAGING_CONTRACT_ADDRESS = os.environ.get("E2E_MESSAGING_CONTRACT_ADDRESS") # Token data cache TOKEN_CACHE = False if os.environ.get("TOKEN_CACHE") == "0" else True -TOKEN_CACHE_TTL = int(os.environ.get("TOKEN_CACHE_TTL")) if os.environ.get("TOKEN_CACHE_TTL") else 43200 +TOKEN_CACHE_TTL = ( + int(os.environ.get("TOKEN_CACHE_TTL")) + if os.environ.get("TOKEN_CACHE_TTL") + else 43200 +) #################################################### @@ -127,45 +168,84 @@ #################################################### # Indexer INDEXER_SYNC_INTERVAL = 10 -INDEXER_BLOCK_LOT_MAX_SIZE = int(os.environ.get("INDEXER_BLOCK_LOT_MAX_SIZE")) \ - if os.environ.get("INDEXER_BLOCK_LOT_MAX_SIZE") else 1000000 +INDEXER_BLOCK_LOT_MAX_SIZE = ( + int(os.environ.get("INDEXER_BLOCK_LOT_MAX_SIZE")) + if os.environ.get("INDEXER_BLOCK_LOT_MAX_SIZE") + else 1000000 +) # Processor # Bulk Transfer -BULK_TRANSFER_INTERVAL = int(os.environ.get("BULK_TRANSFER_INTERVAL")) \ - if os.environ.get("BULK_TRANSFER_INTERVAL") else 10 -BULK_TRANSFER_WORKER_COUNT = int(os.environ.get("BULK_TRANSFER_WORKER_COUNT")) \ - if os.environ.get("BULK_TRANSFER_WORKER_COUNT") else 5 -BULK_TRANSFER_WORKER_LOT_SIZE = int(os.environ.get("BULK_TRANSFER_WORKER_LOT_SIZE")) \ - if os.environ.get("BULK_TRANSFER_WORKER_LOT_SIZE") else 5 +BULK_TRANSFER_INTERVAL = ( + int(os.environ.get("BULK_TRANSFER_INTERVAL")) + if os.environ.get("BULK_TRANSFER_INTERVAL") + else 10 +) +BULK_TRANSFER_WORKER_COUNT = ( + int(os.environ.get("BULK_TRANSFER_WORKER_COUNT")) + if os.environ.get("BULK_TRANSFER_WORKER_COUNT") + else 5 +) +BULK_TRANSFER_WORKER_LOT_SIZE = ( + int(os.environ.get("BULK_TRANSFER_WORKER_LOT_SIZE")) + if os.environ.get("BULK_TRANSFER_WORKER_LOT_SIZE") + else 5 +) # Batch Register Personal Info -BATCH_REGISTER_PERSONAL_INFO_INTERVAL = int(os.environ.get("BATCH_REGISTER_PERSONAL_INFO_INTERVAL")) \ - if os.environ.get("BATCH_REGISTER_PERSONAL_INFO_INTERVAL") else 60 -BATCH_REGISTER_PERSONAL_INFO_WORKER_COUNT = int(os.environ.get("BATCH_REGISTER_PERSONAL_INFO_WORKER_COUNT")) \ - if os.environ.get("BATCH_REGISTER_PERSONAL_INFO_WORKER_COUNT") else 1 -BATCH_REGISTER_PERSONAL_INFO_WORKER_LOT_SIZE = int(os.environ.get("BATCH_REGISTER_PERSONAL_INFO_WORKER_LOT_SIZE")) \ - if os.environ.get("BATCH_REGISTER_PERSONAL_INFO_WORKER_LOT_SIZE") else 2 +BATCH_REGISTER_PERSONAL_INFO_INTERVAL = ( + int(os.environ.get("BATCH_REGISTER_PERSONAL_INFO_INTERVAL")) + if os.environ.get("BATCH_REGISTER_PERSONAL_INFO_INTERVAL") + else 60 +) +BATCH_REGISTER_PERSONAL_INFO_WORKER_COUNT = ( + int(os.environ.get("BATCH_REGISTER_PERSONAL_INFO_WORKER_COUNT")) + if os.environ.get("BATCH_REGISTER_PERSONAL_INFO_WORKER_COUNT") + else 1 +) +BATCH_REGISTER_PERSONAL_INFO_WORKER_LOT_SIZE = ( + int(os.environ.get("BATCH_REGISTER_PERSONAL_INFO_WORKER_LOT_SIZE")) + if os.environ.get("BATCH_REGISTER_PERSONAL_INFO_WORKER_LOT_SIZE") + else 2 +) # Scheduled Events -SCHEDULED_EVENTS_INTERVAL = int(os.environ.get("SCHEDULED_EVENTS_INTERVAL")) \ - if os.environ.get("SCHEDULED_EVENTS_INTERVAL") else 60 -SCHEDULED_EVENTS_WORKER_COUNT = int(os.environ.get("SCHEDULED_EVENTS_WORKER_COUNT")) \ - if os.environ.get("SCHEDULED_EVENTS_WORKER_COUNT") else 5 +SCHEDULED_EVENTS_INTERVAL = ( + int(os.environ.get("SCHEDULED_EVENTS_INTERVAL")) + if os.environ.get("SCHEDULED_EVENTS_INTERVAL") + else 60 +) +SCHEDULED_EVENTS_WORKER_COUNT = ( + int(os.environ.get("SCHEDULED_EVENTS_WORKER_COUNT")) + if os.environ.get("SCHEDULED_EVENTS_WORKER_COUNT") + else 5 +) # Update Token -UPDATE_TOKEN_INTERVAL = int(os.environ.get("UPDATE_TOKEN_INTERVAL")) \ - if os.environ.get("UPDATE_TOKEN_INTERVAL") else 10 +UPDATE_TOKEN_INTERVAL = ( + int(os.environ.get("UPDATE_TOKEN_INTERVAL")) + if os.environ.get("UPDATE_TOKEN_INTERVAL") + else 10 +) # Create UTXO -CREATE_UTXO_INTERVAL = int(os.environ.get("CREATE_UTXO_INTERVAL")) \ - if os.environ.get("CREATE_UTXO_INTERVAL") else 600 -CREATE_UTXO_BLOCK_LOT_MAX_SIZE = int(os.environ.get("CREATE_UTXO_BLOCK_LOT_MAX_SIZE")) \ - if os.environ.get("CREATE_UTXO_BLOCK_LOT_MAX_SIZE") else 10000 +CREATE_UTXO_INTERVAL = ( + int(os.environ.get("CREATE_UTXO_INTERVAL")) + if os.environ.get("CREATE_UTXO_INTERVAL") + else 600 +) +CREATE_UTXO_BLOCK_LOT_MAX_SIZE = ( + int(os.environ.get("CREATE_UTXO_BLOCK_LOT_MAX_SIZE")) + if os.environ.get("CREATE_UTXO_BLOCK_LOT_MAX_SIZE") + else 10000 +) # Rotate E2E Messaging RSA Key -ROTATE_E2E_MESSAGING_RSA_KEY_INTERVAL = int(os.environ.get("ROTATE_E2E_MESSAGING_RSA_KEY_INTERVAL")) \ - if os.environ.get("ROTATE_E2E_MESSAGING_RSA_KEY_INTERVAL") else 10 +ROTATE_E2E_MESSAGING_RSA_KEY_INTERVAL = ( + int(os.environ.get("ROTATE_E2E_MESSAGING_RSA_KEY_INTERVAL")) + if os.environ.get("ROTATE_E2E_MESSAGING_RSA_KEY_INTERVAL") + else 10 +) #################################################### @@ -178,31 +258,39 @@ # ^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9])(?=.*?[\*\+\.\\\(\)\?\[\]\^\$\-\|!#%&"',/:;<=>@_`{}~])[a-zA-Z0-9\*\+\.\\\(\)\?\[\]\^\$\-\|!#%&"',/:;<=>@_`{}~]{12,}$ # => 12 or higher length of mixed characters with # lowercase alphabetic, uppercase alphabetic, numeric, and symbolic(space exclude) -EOA_PASSWORD_PATTERN = \ - os.environ.get("EOA_PASSWORD_PATTERN") or \ - r"^[a-zA-Z0-9 \*\+\.\\\(\)\?\[\]\^\$\-\|!#%&\"',/:;<=>@_`{}~]{8,200}$" -EOA_PASSWORD_PATTERN_MSG = \ - os.environ.get("EOA_PASSWORD_PATTERN_MSG") or \ - "password must be 8 to 200 alphanumeric or symbolic character" -PERSONAL_INFO_RSA_PASSPHRASE_PATTERN = \ - os.environ.get("PERSONAL_INFO_RSA_PASSPHRASE_PATTERN") or \ - r"^[a-zA-Z0-9 \*\+\.\\\(\)\?\[\]\^\$\-\|!#%&\"',/:;<=>@_`{}~]{8,200}$" -PERSONAL_INFO_RSA_PASSPHRASE_PATTERN_MSG = \ - os.environ.get("PERSONAL_INFO_RSA_PASSPHRASE_PATTERN_MSG") or \ - "passphrase must be 8 to 200 alphanumeric or symbolic characters" -PERSONAL_INFO_RSA_DEFAULT_PASSPHRASE = \ - os.environ.get("PERSONAL_INFO_RSA_DEFAULT_PASSPHRASE") or \ - "password" -E2E_MESSAGING_RSA_PASSPHRASE_PATTERN = \ - os.environ.get("E2E_MESSAGING_RSA_PASSPHRASE_PATTERN") or \ - r"^[a-zA-Z0-9 \*\+\.\\\(\)\?\[\]\^\$\-\|!#%&\"',/:;<=>@_`{}~]{8,200}$" -E2E_MESSAGING_RSA_PASSPHRASE_PATTERN_MSG = \ - os.environ.get("E2E_MESSAGING_RSA_PASSPHRASE_PATTERN_MSG") or \ - "passphrase must be 8 to 200 alphanumeric or symbolic characters" -E2E_MESSAGING_RSA_DEFAULT_PASSPHRASE = \ - os.environ.get("E2E_MESSAGING_RSA_DEFAULT_PASSPHRASE") or \ - "password" -EOA_PASSWORD_CHECK_ENABLED = False if os.environ.get("EOA_PASSWORD_CHECK_ENABLED") == "0" else True +EOA_PASSWORD_PATTERN = ( + os.environ.get("EOA_PASSWORD_PATTERN") + or r"^[a-zA-Z0-9 \*\+\.\\\(\)\?\[\]\^\$\-\|!#%&\"',/:;<=>@_`{}~]{8,200}$" +) +EOA_PASSWORD_PATTERN_MSG = ( + os.environ.get("EOA_PASSWORD_PATTERN_MSG") + or "password must be 8 to 200 alphanumeric or symbolic character" +) +PERSONAL_INFO_RSA_PASSPHRASE_PATTERN = ( + os.environ.get("PERSONAL_INFO_RSA_PASSPHRASE_PATTERN") + or r"^[a-zA-Z0-9 \*\+\.\\\(\)\?\[\]\^\$\-\|!#%&\"',/:;<=>@_`{}~]{8,200}$" +) +PERSONAL_INFO_RSA_PASSPHRASE_PATTERN_MSG = ( + os.environ.get("PERSONAL_INFO_RSA_PASSPHRASE_PATTERN_MSG") + or "passphrase must be 8 to 200 alphanumeric or symbolic characters" +) +PERSONAL_INFO_RSA_DEFAULT_PASSPHRASE = ( + os.environ.get("PERSONAL_INFO_RSA_DEFAULT_PASSPHRASE") or "password" +) +E2E_MESSAGING_RSA_PASSPHRASE_PATTERN = ( + os.environ.get("E2E_MESSAGING_RSA_PASSPHRASE_PATTERN") + or r"^[a-zA-Z0-9 \*\+\.\\\(\)\?\[\]\^\$\-\|!#%&\"',/:;<=>@_`{}~]{8,200}$" +) +E2E_MESSAGING_RSA_PASSPHRASE_PATTERN_MSG = ( + os.environ.get("E2E_MESSAGING_RSA_PASSPHRASE_PATTERN_MSG") + or "passphrase must be 8 to 200 alphanumeric or symbolic characters" +) +E2E_MESSAGING_RSA_DEFAULT_PASSPHRASE = ( + os.environ.get("E2E_MESSAGING_RSA_DEFAULT_PASSPHRASE") or "password" +) +EOA_PASSWORD_CHECK_ENABLED = ( + False if os.environ.get("EOA_PASSWORD_CHECK_ENABLED") == "0" else True +) # End-to-End Encryption (RSA) # NOTE: @@ -210,14 +298,26 @@ # - 0:File, Set the file path to E2EE_RSA_RESOURCE. # - 1:AWS SecretsManager, Set the SecretsManagerARN to E2EE_RSA_RESOURCE. if "pytest" in sys.modules: # for unit test - E2EE_RSA_RESOURCE_MODE = int(os.environ.get("E2EE_RSA_RESOURCE_MODE")) \ - if os.environ.get("E2EE_RSA_RESOURCE_MODE") else 0 - E2EE_RSA_RESOURCE = os.environ.get("E2EE_RSA_RESOURCE") or "tests/data/rsa_private.pem" + E2EE_RSA_RESOURCE_MODE = ( + int(os.environ.get("E2EE_RSA_RESOURCE_MODE")) + if os.environ.get("E2EE_RSA_RESOURCE_MODE") + else 0 + ) + E2EE_RSA_RESOURCE = ( + os.environ.get("E2EE_RSA_RESOURCE") or "tests/data/rsa_private.pem" + ) E2EE_RSA_PASSPHRASE = os.environ.get("E2EE_RSA_PASSPHRASE") or "password" -elif "alembic" in sys.modules or "manage.py" in sys.argv[0] or APP_ENV == "local": # for migration or local - E2EE_RSA_RESOURCE_MODE = int(os.environ.get("E2EE_RSA_RESOURCE_MODE")) \ - if os.environ.get("E2EE_RSA_RESOURCE_MODE") else 0 - E2EE_RSA_RESOURCE = os.environ.get("E2EE_RSA_RESOURCE") or "tests/data/rsa_private.pem" +elif ( + "alembic" in sys.modules or "manage.py" in sys.argv[0] or APP_ENV == "local" +): # for migration or local + E2EE_RSA_RESOURCE_MODE = ( + int(os.environ.get("E2EE_RSA_RESOURCE_MODE")) + if os.environ.get("E2EE_RSA_RESOURCE_MODE") + else 0 + ) + E2EE_RSA_RESOURCE = ( + os.environ.get("E2EE_RSA_RESOURCE") or "tests/data/rsa_private.pem" + ) E2EE_RSA_PASSPHRASE = os.environ.get("E2EE_RSA_PASSPHRASE") or "password" else: E2EE_RSA_RESOURCE_MODE = int(os.environ.get("E2EE_RSA_RESOURCE_MODE")) @@ -240,9 +340,14 @@ AWS_REGION_NAME = os.environ.get("AWS_REGION_NAME") or "ap-northeast-1" # Random Bytes Generator -AWS_KMS_GENERATE_RANDOM_ENABLED = True if os.environ.get("AWS_KMS_GENERATE_RANDOM_ENABLED") == "1" else False +AWS_KMS_GENERATE_RANDOM_ENABLED = ( + True if os.environ.get("AWS_KMS_GENERATE_RANDOM_ENABLED") == "1" else False +) # File Upload # NOTE: (Reference information) WSGI server and app used by ibet-Prime has no request body size limit. -MAX_UPLOAD_FILE_SIZE = int(os.environ.get("MAX_UPLOAD_FILE_SIZE")) \ - if os.environ.get("MAX_UPLOAD_FILE_SIZE") else 100_000_000 +MAX_UPLOAD_FILE_SIZE = ( + int(os.environ.get("MAX_UPLOAD_FILE_SIZE")) + if os.environ.get("MAX_UPLOAD_FILE_SIZE") + else 100_000_000 +) diff --git a/migrations/env.py b/migrations/env.py index 2b8c596c..4eed69f1 100644 --- a/migrations/env.py +++ b/migrations/env.py @@ -1,16 +1,14 @@ -import sys import re +import sys from logging.config import fileConfig -from alembic.autogenerate import render -from sqlalchemy import engine_from_config -from sqlalchemy import pool - from alembic import context +from alembic.autogenerate import render +from sqlalchemy import engine_from_config, pool -from config import DATABASE_URL from app.database import engine, get_db_schema from app.model.db import Base +from config import DATABASE_URL # this is the Alembic Config object, which provides # access to the values within the .ini file in use. @@ -58,7 +56,7 @@ def run_migrations_offline(): url=url, target_metadata=target_metadata, literal_binds=True, - dialect_opts={"paramstyle": "named"} + dialect_opts={"paramstyle": "named"}, ) with context.begin_transaction(): @@ -92,7 +90,7 @@ def run_migrations_online(): compare_type=True, version_table_schema=get_db_schema(), include_schemas=include_schemas, - include_name=include_name + include_name=include_name, ) with context.begin_transaction(): @@ -103,22 +101,20 @@ def run_migrations_online(): if "--autogenerate" in argv: _render_op_org = getattr(render, "render_op") - def render_op_wrapper(autogen_context, op): lines = _render_op_org(autogen_context, op) new_lines = [] for line in lines: new_line = line - if 'get_db_schema())' not in new_line: + if "get_db_schema())" not in new_line: # Set schema of migration exec-environment - if 'schema=' not in new_line: - new_line = re.sub('\)$', ', schema=get_db_schema())', line) + if "schema=" not in new_line: + new_line = re.sub("\)$", ", schema=get_db_schema())", line) else: # If local environment has a schema set - new_line = re.sub('schema=(.|\s)*\)$', 'schema=get_db_schema())', line) + new_line = re.sub("schema=(.)*\)$", "schema=get_db_schema())", line) new_lines.append(new_line) return new_lines - setattr(render, "render_op", render_op_wrapper) if "--sql" in argv: diff --git a/migrations/manage.py b/migrations/manage.py index 213a3a61..da9a8627 100644 --- a/migrations/manage.py +++ b/migrations/manage.py @@ -16,10 +16,10 @@ SPDX-License-Identifier: Apache-2.0 """ -import sys import os +import sys -path = os.path.join(os.path.dirname(__file__), '../') +path = os.path.join(os.path.dirname(__file__), "../") sys.path.append(path) from sqlalchemy import Table diff --git a/migrations/versions/05eab8fbc21b_v0_1_0_fix_188.py b/migrations/versions/05eab8fbc21b_v0_1_0_fix_188.py index 782a66ae..b050541a 100644 --- a/migrations/versions/05eab8fbc21b_v0_1_0_fix_188.py +++ b/migrations/versions/05eab8fbc21b_v0_1_0_fix_188.py @@ -5,35 +5,46 @@ Create Date: 2021-08-02 15:04:21.851447 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = '05eab8fbc21b' -down_revision = 'beccf439af5a' +revision = "05eab8fbc21b" +down_revision = "beccf439af5a" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.create_table('token_attr_update', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), - sa.Column('token_address', sa.String(length=42), nullable=True), - sa.Column('updated_datetime', sa.DateTime(), nullable=False), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) - op.create_index(op.f('ix_token_attr_update_token_address'), 'token_attr_update', ['token_address'], unique=False, schema=get_db_schema()) + op.create_table( + "token_attr_update", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), + sa.Column("token_address", sa.String(length=42), nullable=True), + sa.Column("updated_datetime", sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_token_attr_update_token_address"), + "token_attr_update", + ["token_address"], + unique=False, + schema=get_db_schema(), + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_index(op.f('ix_token_attr_update_token_address'), table_name='token_attr_update', schema=get_db_schema()) - op.drop_table('token_attr_update', schema=get_db_schema()) + op.drop_index( + op.f("ix_token_attr_update_token_address"), + table_name="token_attr_update", + schema=get_db_schema(), + ) + op.drop_table("token_attr_update", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/migrations/versions/0d4133a5b0e3_v0_1_0_feature_155.py b/migrations/versions/0d4133a5b0e3_v0_1_0_feature_155.py index fb06da39..7fd73c68 100644 --- a/migrations/versions/0d4133a5b0e3_v0_1_0_feature_155.py +++ b/migrations/versions/0d4133a5b0e3_v0_1_0_feature_155.py @@ -5,28 +5,35 @@ Create Date: 2021-06-21 20:01:39.441290 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = '0d4133a5b0e3' -down_revision = 'd5d96e880adb' +revision = "0d4133a5b0e3" +down_revision = "d5d96e880adb" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.add_column('node', sa.Column('endpoint_uri', sa.String(length=267), nullable=True), schema=get_db_schema()) - op.add_column('node', sa.Column('priority', sa.Integer(), nullable=True), schema=get_db_schema()) + op.add_column( + "node", + sa.Column("endpoint_uri", sa.String(length=267), nullable=True), + schema=get_db_schema(), + ) + op.add_column( + "node", + sa.Column("priority", sa.Integer(), nullable=True), + schema=get_db_schema(), + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_column('node', 'priority', schema=get_db_schema()) - op.drop_column('node', 'endpoint_uri', schema=get_db_schema()) + op.drop_column("node", "priority", schema=get_db_schema()) + op.drop_column("node", "endpoint_uri", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/migrations/versions/0fc0196253f8_v22_9_0_feature_334.py b/migrations/versions/0fc0196253f8_v22_9_0_feature_334.py index abb6581e..312ac76f 100644 --- a/migrations/versions/0fc0196253f8_v22_9_0_feature_334.py +++ b/migrations/versions/0fc0196253f8_v22_9_0_feature_334.py @@ -5,32 +5,45 @@ Create Date: 2022-07-06 16:46:51.725890 """ -from alembic import op import sqlalchemy as sa +from alembic import op from sqlalchemy.dialects import postgresql from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = '0fc0196253f8' -down_revision = '7fe46c2af01e' +revision = "0fc0196253f8" +down_revision = "7fe46c2af01e" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_table('additional_token_info', schema=get_db_schema()) + op.drop_table("additional_token_info", schema=get_db_schema()) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.create_table('additional_token_info', - sa.Column('created', postgresql.TIMESTAMP(), autoincrement=False, nullable=True), - sa.Column('modified', postgresql.TIMESTAMP(), autoincrement=False, nullable=True), - sa.Column('token_address', sa.VARCHAR(length=42), autoincrement=False, nullable=False), - sa.Column('is_manual_transfer_approval', sa.BOOLEAN(), autoincrement=False, nullable=True), - sa.PrimaryKeyConstraint('token_address', name='additional_token_info_pkey') - , schema=get_db_schema()) + op.create_table( + "additional_token_info", + sa.Column( + "created", postgresql.TIMESTAMP(), autoincrement=False, nullable=True + ), + sa.Column( + "modified", postgresql.TIMESTAMP(), autoincrement=False, nullable=True + ), + sa.Column( + "token_address", sa.VARCHAR(length=42), autoincrement=False, nullable=False + ), + sa.Column( + "is_manual_transfer_approval", + sa.BOOLEAN(), + autoincrement=False, + nullable=True, + ), + sa.PrimaryKeyConstraint("token_address", name="additional_token_info_pkey"), + schema=get_db_schema(), + ) # ### end Alembic commands ### diff --git a/migrations/versions/102b3b000e56_v23_3_0.py b/migrations/versions/102b3b000e56_v23_3_0.py index 4d1050ed..a0b3b94a 100644 --- a/migrations/versions/102b3b000e56_v23_3_0.py +++ b/migrations/versions/102b3b000e56_v23_3_0.py @@ -5,26 +5,35 @@ Create Date: 2022-12-28 14:16:11.566526 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = '102b3b000e56' -down_revision = 'ff1d28df9f37' +revision = "102b3b000e56" +down_revision = "ff1d28df9f37" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.create_index(op.f('ix_idx_e2e_messaging_type'), 'idx_e2e_messaging', ['type'], unique=False, schema=get_db_schema()) + op.create_index( + op.f("ix_idx_e2e_messaging_type"), + "idx_e2e_messaging", + ["type"], + unique=False, + schema=get_db_schema(), + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_index(op.f('ix_idx_e2e_messaging_type'), table_name='idx_e2e_messaging', schema=get_db_schema()) + op.drop_index( + op.f("ix_idx_e2e_messaging_type"), + table_name="idx_e2e_messaging", + schema=get_db_schema(), + ) # ### end Alembic commands ### diff --git a/migrations/versions/1dddc4e2d4e6_v22_12_0_feature_401.py b/migrations/versions/1dddc4e2d4e6_v22_12_0_feature_401.py index a94c2ffe..dea00441 100644 --- a/migrations/versions/1dddc4e2d4e6_v22_12_0_feature_401.py +++ b/migrations/versions/1dddc4e2d4e6_v22_12_0_feature_401.py @@ -5,34 +5,35 @@ Create Date: 2022-10-12 23:12:33.296953 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = '1dddc4e2d4e6' -down_revision = '5b1e810b1e89' +revision = "1dddc4e2d4e6" +down_revision = "5b1e810b1e89" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.create_table('token_cache', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('token_address', sa.String(length=42), nullable=False), - sa.Column('attributes', sa.JSON(), nullable=False), - sa.Column('cached_datetime', sa.DateTime(), nullable=True), - sa.Column('expiration_datetime', sa.DateTime(), nullable=True), - sa.PrimaryKeyConstraint('token_address') - , schema=get_db_schema()) + op.create_table( + "token_cache", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("token_address", sa.String(length=42), nullable=False), + sa.Column("attributes", sa.JSON(), nullable=False), + sa.Column("cached_datetime", sa.DateTime(), nullable=True), + sa.Column("expiration_datetime", sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint("token_address"), + schema=get_db_schema(), + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_table('token_cache', schema=get_db_schema()) + op.drop_table("token_cache", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/migrations/versions/2eee006a38d5_v0_1_0_feature_54.py b/migrations/versions/2eee006a38d5_v0_1_0_feature_54.py index 3f6c243c..3ecfd0a7 100644 --- a/migrations/versions/2eee006a38d5_v0_1_0_feature_54.py +++ b/migrations/versions/2eee006a38d5_v0_1_0_feature_54.py @@ -5,52 +5,116 @@ Create Date: 2021-04-08 20:24:22.465013 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = '2eee006a38d5' -down_revision = 'fe0437ec5e6d' +revision = "2eee006a38d5" +down_revision = "fe0437ec5e6d" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.create_table('scheduled_events', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), - sa.Column('issuer_address', sa.String(length=42), nullable=False), - sa.Column('token_address', sa.String(length=42), nullable=False), - sa.Column('token_type', sa.String(length=40), nullable=False), - sa.Column('scheduled_datetime', sa.DateTime(), nullable=False), - sa.Column('event_type', sa.String(length=40), nullable=False), - sa.Column('status', sa.Integer(), nullable=False), - sa.Column('data', sa.JSON(), nullable=False), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) - op.create_index(op.f('ix_scheduled_events_status'), 'scheduled_events', ['status'], unique=False, schema=get_db_schema()) - op.add_column('corporate_bond_ledger_template_jpn', sa.Column('ledger_admin_headquarters', sa.String(length=200), nullable=False), schema=get_db_schema()) - op.add_column('corporate_bond_ledger_template_jpn', sa.Column('ledger_admin_name', sa.String(length=200), nullable=False), schema=get_db_schema()) - op.add_column('corporate_bond_ledger_template_jpn', sa.Column('ledger_admin_office_address', sa.String(length=200), nullable=False), schema=get_db_schema()) - op.drop_column('corporate_bond_ledger_template_jpn', 'hq_address', schema=get_db_schema()) - op.drop_column('corporate_bond_ledger_template_jpn', 'hq_name', schema=get_db_schema()) - op.drop_column('corporate_bond_ledger_template_jpn', 'hq_office_address', schema=get_db_schema()) + op.create_table( + "scheduled_events", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), + sa.Column("issuer_address", sa.String(length=42), nullable=False), + sa.Column("token_address", sa.String(length=42), nullable=False), + sa.Column("token_type", sa.String(length=40), nullable=False), + sa.Column("scheduled_datetime", sa.DateTime(), nullable=False), + sa.Column("event_type", sa.String(length=40), nullable=False), + sa.Column("status", sa.Integer(), nullable=False), + sa.Column("data", sa.JSON(), nullable=False), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_scheduled_events_status"), + "scheduled_events", + ["status"], + unique=False, + schema=get_db_schema(), + ) + op.add_column( + "corporate_bond_ledger_template_jpn", + sa.Column("ledger_admin_headquarters", sa.String(length=200), nullable=False), + schema=get_db_schema(), + ) + op.add_column( + "corporate_bond_ledger_template_jpn", + sa.Column("ledger_admin_name", sa.String(length=200), nullable=False), + schema=get_db_schema(), + ) + op.add_column( + "corporate_bond_ledger_template_jpn", + sa.Column("ledger_admin_office_address", sa.String(length=200), nullable=False), + schema=get_db_schema(), + ) + op.drop_column( + "corporate_bond_ledger_template_jpn", "hq_address", schema=get_db_schema() + ) + op.drop_column( + "corporate_bond_ledger_template_jpn", "hq_name", schema=get_db_schema() + ) + op.drop_column( + "corporate_bond_ledger_template_jpn", + "hq_office_address", + schema=get_db_schema(), + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.add_column('corporate_bond_ledger_template_jpn', sa.Column('hq_office_address', sa.VARCHAR(length=200), autoincrement=False, nullable=False), schema=get_db_schema()) - op.add_column('corporate_bond_ledger_template_jpn', sa.Column('hq_name', sa.VARCHAR(length=200), autoincrement=False, nullable=False), schema=get_db_schema()) - op.add_column('corporate_bond_ledger_template_jpn', sa.Column('hq_address', sa.VARCHAR(length=200), autoincrement=False, nullable=False), schema=get_db_schema()) - op.drop_column('corporate_bond_ledger_template_jpn', 'ledger_admin_office_address', schema=get_db_schema()) - op.drop_column('corporate_bond_ledger_template_jpn', 'ledger_admin_name', schema=get_db_schema()) - op.drop_column('corporate_bond_ledger_template_jpn', 'ledger_admin_headquarters', schema=get_db_schema()) - op.drop_index(op.f('ix_scheduled_events_status'), table_name='scheduled_events', schema=get_db_schema()) - op.drop_table('scheduled_events', schema=get_db_schema()) + op.add_column( + "corporate_bond_ledger_template_jpn", + sa.Column( + "hq_office_address", + sa.VARCHAR(length=200), + autoincrement=False, + nullable=False, + ), + schema=get_db_schema(), + ) + op.add_column( + "corporate_bond_ledger_template_jpn", + sa.Column( + "hq_name", sa.VARCHAR(length=200), autoincrement=False, nullable=False + ), + schema=get_db_schema(), + ) + op.add_column( + "corporate_bond_ledger_template_jpn", + sa.Column( + "hq_address", sa.VARCHAR(length=200), autoincrement=False, nullable=False + ), + schema=get_db_schema(), + ) + op.drop_column( + "corporate_bond_ledger_template_jpn", + "ledger_admin_office_address", + schema=get_db_schema(), + ) + op.drop_column( + "corporate_bond_ledger_template_jpn", + "ledger_admin_name", + schema=get_db_schema(), + ) + op.drop_column( + "corporate_bond_ledger_template_jpn", + "ledger_admin_headquarters", + schema=get_db_schema(), + ) + op.drop_index( + op.f("ix_scheduled_events_status"), + table_name="scheduled_events", + schema=get_db_schema(), + ) + op.drop_table("scheduled_events", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/migrations/versions/38eb462293cd_v22_9_0_feature_339.py b/migrations/versions/38eb462293cd_v22_9_0_feature_339.py index c27255c9..57d03297 100644 --- a/migrations/versions/38eb462293cd_v22_9_0_feature_339.py +++ b/migrations/versions/38eb462293cd_v22_9_0_feature_339.py @@ -5,53 +5,96 @@ Create Date: 2022-07-11 20:36:30.195927 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = '38eb462293cd' -down_revision = 'fad6669cad84' +revision = "38eb462293cd" +down_revision = "fad6669cad84" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.create_table('batch_register_personal_info', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), - sa.Column('upload_id', sa.String(length=36), nullable=True), - sa.Column('token_address', sa.String(length=42), nullable=False), - sa.Column('account_address', sa.String(length=42), nullable=False), - sa.Column('status', sa.Integer(), nullable=False), - sa.Column('personal_info', sa.JSON(), nullable=False), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) - op.create_index(op.f('ix_batch_register_personal_info_status'), 'batch_register_personal_info', ['status'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_batch_register_personal_info_upload_id'), 'batch_register_personal_info', ['upload_id'], unique=False, schema=get_db_schema()) - op.create_table('batch_register_personal_info_upload', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('upload_id', sa.String(length=36), nullable=False), - sa.Column('issuer_address', sa.String(length=42), nullable=False), - sa.Column('status', sa.String(), nullable=False), - sa.PrimaryKeyConstraint('upload_id') - , schema=get_db_schema()) - op.create_index(op.f('ix_batch_register_personal_info_upload_issuer_address'), 'batch_register_personal_info_upload', ['issuer_address'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_batch_register_personal_info_upload_status'), 'batch_register_personal_info_upload', ['status'], unique=False, schema=get_db_schema()) + op.create_table( + "batch_register_personal_info", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), + sa.Column("upload_id", sa.String(length=36), nullable=True), + sa.Column("token_address", sa.String(length=42), nullable=False), + sa.Column("account_address", sa.String(length=42), nullable=False), + sa.Column("status", sa.Integer(), nullable=False), + sa.Column("personal_info", sa.JSON(), nullable=False), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_batch_register_personal_info_status"), + "batch_register_personal_info", + ["status"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_batch_register_personal_info_upload_id"), + "batch_register_personal_info", + ["upload_id"], + unique=False, + schema=get_db_schema(), + ) + op.create_table( + "batch_register_personal_info_upload", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("upload_id", sa.String(length=36), nullable=False), + sa.Column("issuer_address", sa.String(length=42), nullable=False), + sa.Column("status", sa.String(), nullable=False), + sa.PrimaryKeyConstraint("upload_id"), + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_batch_register_personal_info_upload_issuer_address"), + "batch_register_personal_info_upload", + ["issuer_address"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_batch_register_personal_info_upload_status"), + "batch_register_personal_info_upload", + ["status"], + unique=False, + schema=get_db_schema(), + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_index(op.f('ix_batch_register_personal_info_upload_status'), table_name='batch_register_personal_info_upload', schema=get_db_schema()) - op.drop_index(op.f('ix_batch_register_personal_info_upload_issuer_address'), table_name='batch_register_personal_info_upload', schema=get_db_schema()) - op.drop_table('batch_register_personal_info_upload', schema=get_db_schema()) - op.drop_index(op.f('ix_batch_register_personal_info_upload_id'), table_name='batch_register_personal_info', schema=get_db_schema()) - op.drop_index(op.f('ix_batch_register_personal_info_status'), table_name='batch_register_personal_info', schema=get_db_schema()) - op.drop_table('batch_register_personal_info', schema=get_db_schema()) + op.drop_index( + op.f("ix_batch_register_personal_info_upload_status"), + table_name="batch_register_personal_info_upload", + schema=get_db_schema(), + ) + op.drop_index( + op.f("ix_batch_register_personal_info_upload_issuer_address"), + table_name="batch_register_personal_info_upload", + schema=get_db_schema(), + ) + op.drop_table("batch_register_personal_info_upload", schema=get_db_schema()) + op.drop_index( + op.f("ix_batch_register_personal_info_upload_id"), + table_name="batch_register_personal_info", + schema=get_db_schema(), + ) + op.drop_index( + op.f("ix_batch_register_personal_info_status"), + table_name="batch_register_personal_info", + schema=get_db_schema(), + ) + op.drop_table("batch_register_personal_info", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/migrations/versions/3a0cc5e324b4_v23_3_0_feature_465.py b/migrations/versions/3a0cc5e324b4_v23_3_0_feature_465.py index 305dd2ee..5c01c5d4 100644 --- a/migrations/versions/3a0cc5e324b4_v23_3_0_feature_465.py +++ b/migrations/versions/3a0cc5e324b4_v23_3_0_feature_465.py @@ -5,35 +5,52 @@ Create Date: 2023-01-17 18:15:07.271586 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = '3a0cc5e324b4' -down_revision = '6920ad60f134' +revision = "3a0cc5e324b4" +down_revision = "6920ad60f134" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.add_column('idx_transfer', sa.Column('data', sa.JSON(), nullable=True), schema=get_db_schema()) + op.add_column( + "idx_transfer", + sa.Column("data", sa.JSON(), nullable=True), + schema=get_db_schema(), + ) # ### end Alembic commands ### # NOTE: Manually modified # 1. Added server_default arg to migrate existing record. # 2. Added alter column operation to remove server default setting. - op.add_column('idx_transfer', sa.Column('source_event', sa.String(length=50), server_default='Transfer', nullable=False), schema=get_db_schema()) - op.alter_column('idx_transfer', 'source_event', - existing_type=sa.String(length=50), - existing_nullable=False, server_default=None, schema=get_db_schema()) + op.add_column( + "idx_transfer", + sa.Column( + "source_event", + sa.String(length=50), + server_default="Transfer", + nullable=False, + ), + schema=get_db_schema(), + ) + op.alter_column( + "idx_transfer", + "source_event", + existing_type=sa.String(length=50), + existing_nullable=False, + server_default=None, + schema=get_db_schema(), + ) def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_column('idx_transfer', 'data', schema=get_db_schema()) - op.drop_column('idx_transfer', 'source_event', schema=get_db_schema()) + op.drop_column("idx_transfer", "data", schema=get_db_schema()) + op.drop_column("idx_transfer", "source_event", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/migrations/versions/3a809fa594f8_v22_9_0_feature_377.py b/migrations/versions/3a809fa594f8_v22_9_0_feature_377.py index 076a6fb5..f2a94d48 100644 --- a/migrations/versions/3a809fa594f8_v22_9_0_feature_377.py +++ b/migrations/versions/3a809fa594f8_v22_9_0_feature_377.py @@ -5,56 +5,109 @@ Create Date: 2022-08-30 22:08:31.516245 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = '3a809fa594f8' -down_revision = 'f770297833c5' +revision = "3a809fa594f8" +down_revision = "f770297833c5" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.create_table('idx_issue_redeem', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.BigInteger(), autoincrement=True, nullable=False), - sa.Column('event_type', sa.String(length=10), nullable=True), - sa.Column('transaction_hash', sa.String(length=66), nullable=True), - sa.Column('token_address', sa.String(length=42), nullable=True), - sa.Column('locked_address', sa.String(length=42), nullable=True), - sa.Column('target_address', sa.String(length=42), nullable=True), - sa.Column('amount', sa.BigInteger(), nullable=True), - sa.Column('block_timestamp', sa.DateTime(), nullable=True), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) - op.create_index(op.f('ix_idx_issue_redeem_event_type'), 'idx_issue_redeem', ['event_type'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_idx_issue_redeem_locked_address'), 'idx_issue_redeem', ['locked_address'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_idx_issue_redeem_target_address'), 'idx_issue_redeem', ['target_address'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_idx_issue_redeem_token_address'), 'idx_issue_redeem', ['token_address'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_idx_issue_redeem_transaction_hash'), 'idx_issue_redeem', ['transaction_hash'], unique=False, schema=get_db_schema()) - op.create_table('idx_issue_redeem_block_number', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.BigInteger(), autoincrement=True, nullable=False), - sa.Column('latest_block_number', sa.BigInteger(), nullable=True), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) + op.create_table( + "idx_issue_redeem", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False), + sa.Column("event_type", sa.String(length=10), nullable=True), + sa.Column("transaction_hash", sa.String(length=66), nullable=True), + sa.Column("token_address", sa.String(length=42), nullable=True), + sa.Column("locked_address", sa.String(length=42), nullable=True), + sa.Column("target_address", sa.String(length=42), nullable=True), + sa.Column("amount", sa.BigInteger(), nullable=True), + sa.Column("block_timestamp", sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_idx_issue_redeem_event_type"), + "idx_issue_redeem", + ["event_type"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_idx_issue_redeem_locked_address"), + "idx_issue_redeem", + ["locked_address"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_idx_issue_redeem_target_address"), + "idx_issue_redeem", + ["target_address"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_idx_issue_redeem_token_address"), + "idx_issue_redeem", + ["token_address"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_idx_issue_redeem_transaction_hash"), + "idx_issue_redeem", + ["transaction_hash"], + unique=False, + schema=get_db_schema(), + ) + op.create_table( + "idx_issue_redeem_block_number", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False), + sa.Column("latest_block_number", sa.BigInteger(), nullable=True), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_table('idx_issue_redeem_block_number', schema=get_db_schema()) - op.drop_index(op.f('ix_idx_issue_redeem_transaction_hash'), table_name='idx_issue_redeem', schema=get_db_schema()) - op.drop_index(op.f('ix_idx_issue_redeem_token_address'), table_name='idx_issue_redeem', schema=get_db_schema()) - op.drop_index(op.f('ix_idx_issue_redeem_target_address'), table_name='idx_issue_redeem', schema=get_db_schema()) - op.drop_index(op.f('ix_idx_issue_redeem_locked_address'), table_name='idx_issue_redeem', schema=get_db_schema()) - op.drop_index(op.f('ix_idx_issue_redeem_event_type'), table_name='idx_issue_redeem', schema=get_db_schema()) - op.drop_table('idx_issue_redeem', schema=get_db_schema()) + op.drop_table("idx_issue_redeem_block_number", schema=get_db_schema()) + op.drop_index( + op.f("ix_idx_issue_redeem_transaction_hash"), + table_name="idx_issue_redeem", + schema=get_db_schema(), + ) + op.drop_index( + op.f("ix_idx_issue_redeem_token_address"), + table_name="idx_issue_redeem", + schema=get_db_schema(), + ) + op.drop_index( + op.f("ix_idx_issue_redeem_target_address"), + table_name="idx_issue_redeem", + schema=get_db_schema(), + ) + op.drop_index( + op.f("ix_idx_issue_redeem_locked_address"), + table_name="idx_issue_redeem", + schema=get_db_schema(), + ) + op.drop_index( + op.f("ix_idx_issue_redeem_event_type"), + table_name="idx_issue_redeem", + schema=get_db_schema(), + ) + op.drop_table("idx_issue_redeem", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/migrations/versions/47bf57b85b0a_v22_9_0_feature_354.py b/migrations/versions/47bf57b85b0a_v22_9_0_feature_354.py index 19839e7a..dd2e9806 100644 --- a/migrations/versions/47bf57b85b0a_v22_9_0_feature_354.py +++ b/migrations/versions/47bf57b85b0a_v22_9_0_feature_354.py @@ -5,34 +5,35 @@ Create Date: 2022-07-15 16:34:04.214970 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = '47bf57b85b0a' -down_revision = '38eb462293cd' +revision = "47bf57b85b0a" +down_revision = "38eb462293cd" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.create_table('auth_token', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('issuer_address', sa.String(length=42), nullable=False), - sa.Column('auth_token', sa.String(length=64), nullable=True), - sa.Column('usage_start', sa.DateTime(), nullable=True), - sa.Column('valid_duration', sa.Integer(), nullable=False), - sa.PrimaryKeyConstraint('issuer_address') - , schema=get_db_schema()) + op.create_table( + "auth_token", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("issuer_address", sa.String(length=42), nullable=False), + sa.Column("auth_token", sa.String(length=64), nullable=True), + sa.Column("usage_start", sa.DateTime(), nullable=True), + sa.Column("valid_duration", sa.Integer(), nullable=False), + sa.PrimaryKeyConstraint("issuer_address"), + schema=get_db_schema(), + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_table('auth_token', schema=get_db_schema()) + op.drop_table("auth_token", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/migrations/versions/4884346fad46_v0_1_0_feature_136.py b/migrations/versions/4884346fad46_v0_1_0_feature_136.py index fb8d6f8b..2ac40e21 100644 --- a/migrations/versions/4884346fad46_v0_1_0_feature_136.py +++ b/migrations/versions/4884346fad46_v0_1_0_feature_136.py @@ -5,41 +5,56 @@ Create Date: 2021-06-07 11:50:55.188253 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = '4884346fad46' -down_revision = 'e91c3d19e99f' +revision = "4884346fad46" +down_revision = "e91c3d19e99f" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.create_table('update_token', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), - sa.Column('token_address', sa.String(length=42), nullable=True), - sa.Column('issuer_address', sa.String(length=42), nullable=True), - sa.Column('type', sa.String(length=40), nullable=False), - sa.Column('arguments', sa.JSON(), nullable=False), - sa.Column('status', sa.Integer(), nullable=False), - sa.Column('trigger', sa.String(length=40), nullable=False), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) - op.create_index(op.f('ix_update_token_token_address'), 'update_token', ['token_address'], unique=False, schema=get_db_schema()) - op.add_column('token', sa.Column('token_status', sa.Integer(), nullable=True), schema=get_db_schema()) + op.create_table( + "update_token", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), + sa.Column("token_address", sa.String(length=42), nullable=True), + sa.Column("issuer_address", sa.String(length=42), nullable=True), + sa.Column("type", sa.String(length=40), nullable=False), + sa.Column("arguments", sa.JSON(), nullable=False), + sa.Column("status", sa.Integer(), nullable=False), + sa.Column("trigger", sa.String(length=40), nullable=False), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_update_token_token_address"), + "update_token", + ["token_address"], + unique=False, + schema=get_db_schema(), + ) + op.add_column( + "token", + sa.Column("token_status", sa.Integer(), nullable=True), + schema=get_db_schema(), + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_column('token', 'token_status', schema=get_db_schema()) - op.drop_index(op.f('ix_update_token_token_address'), table_name='update_token', schema=get_db_schema()) - op.drop_table('update_token', schema=get_db_schema()) + op.drop_column("token", "token_status", schema=get_db_schema()) + op.drop_index( + op.f("ix_update_token_token_address"), + table_name="update_token", + schema=get_db_schema(), + ) + op.drop_table("update_token", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/migrations/versions/498c64b0a5ad_v0_1_0_feature_114.py b/migrations/versions/498c64b0a5ad_v0_1_0_feature_114.py index 98578630..a16aff8e 100644 --- a/migrations/versions/498c64b0a5ad_v0_1_0_feature_114.py +++ b/migrations/versions/498c64b0a5ad_v0_1_0_feature_114.py @@ -5,28 +5,41 @@ Create Date: 2021-05-24 20:02:56.156876 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = '498c64b0a5ad' -down_revision = 'ff1cb5a4411c' +revision = "498c64b0a5ad" +down_revision = "ff1cb5a4411c" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.add_column('scheduled_events', sa.Column('event_id', sa.String(length=36), nullable=True), schema=get_db_schema()) - op.create_index(op.f('ix_scheduled_events_event_id'), 'scheduled_events', ['event_id'], unique=False, schema=get_db_schema()) + op.add_column( + "scheduled_events", + sa.Column("event_id", sa.String(length=36), nullable=True), + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_scheduled_events_event_id"), + "scheduled_events", + ["event_id"], + unique=False, + schema=get_db_schema(), + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_index(op.f('ix_scheduled_events_event_id'), table_name='scheduled_events', schema=get_db_schema()) - op.drop_column('scheduled_events', 'event_id', schema=get_db_schema()) + op.drop_index( + op.f("ix_scheduled_events_event_id"), + table_name="scheduled_events", + schema=get_db_schema(), + ) + op.drop_column("scheduled_events", "event_id", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/migrations/versions/5144d0ec6eac_v22_6_0_feature_293.py b/migrations/versions/5144d0ec6eac_v22_6_0_feature_293.py index b206a562..21aed1c2 100644 --- a/migrations/versions/5144d0ec6eac_v22_6_0_feature_293.py +++ b/migrations/versions/5144d0ec6eac_v22_6_0_feature_293.py @@ -5,27 +5,32 @@ Create Date: 2022-04-13 11:40:48.985574 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = '5144d0ec6eac' -down_revision = 'f22f8ac0a121' +revision = "5144d0ec6eac" +down_revision = "f22f8ac0a121" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.add_column('idx_transfer_approval', sa.Column('escrow_finished', sa.Boolean(), nullable=True), schema=get_db_schema()) - op.execute('UPDATE idx_transfer_approval SET escrow_finished = true WHERE exchange_address IS NOT NULL AND transfer_approved = true;') + op.add_column( + "idx_transfer_approval", + sa.Column("escrow_finished", sa.Boolean(), nullable=True), + schema=get_db_schema(), + ) + op.execute( + "UPDATE idx_transfer_approval SET escrow_finished = true WHERE exchange_address IS NOT NULL AND transfer_approved = true;" + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_column('idx_transfer_approval', 'escrow_finished', schema=get_db_schema()) + op.drop_column("idx_transfer_approval", "escrow_finished", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/migrations/versions/52b9095d9dff_v21_12_0_feature_207.py b/migrations/versions/52b9095d9dff_v21_12_0_feature_207.py index 44b4c76a..250755f4 100644 --- a/migrations/versions/52b9095d9dff_v21_12_0_feature_207.py +++ b/migrations/versions/52b9095d9dff_v21_12_0_feature_207.py @@ -5,15 +5,15 @@ Create Date: 2021-10-08 13:40:57.416791 """ -from alembic import op import sqlalchemy as sa +from alembic import op -from app.database import get_db_schema, engine +from app.database import engine, get_db_schema from config import MAX_UPLOAD_FILE_SIZE # revision identifiers, used by Alembic. -revision = '52b9095d9dff' -down_revision = '05eab8fbc21b' +revision = "52b9095d9dff" +down_revision = "05eab8fbc21b" branch_labels = None depends_on = None @@ -39,24 +39,28 @@ def upgrade(): # NOTE: # Specify length, because switch column type to BLOB, MEDIUMBLOB, and LONGBLOB. # Don’t support modifying environment variable value after migration. - content_column = sa.Column('content', sa.LargeBinary(length=MAX_UPLOAD_FILE_SIZE), nullable=False) + content_column = sa.Column( + "content", sa.LargeBinary(length=MAX_UPLOAD_FILE_SIZE), nullable=False + ) else: - content_column = sa.Column('content', sa.LargeBinary(), nullable=False) - op.create_table('upload_file', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('file_id', sa.String(length=36), nullable=False), - sa.Column('issuer_address', sa.String(length=42), nullable=False), - sa.Column('relation', sa.String(length=50), nullable=True), - sa.Column('file_name', sa.String(length=256), nullable=False), - content_column, - sa.Column('content_size', sa.Integer(), nullable=True), - sa.Column('description', sa.String(length=1000), nullable=True), - sa.PrimaryKeyConstraint('file_id'), - schema=get_db_schema()) + content_column = sa.Column("content", sa.LargeBinary(), nullable=False) + op.create_table( + "upload_file", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("file_id", sa.String(length=36), nullable=False), + sa.Column("issuer_address", sa.String(length=42), nullable=False), + sa.Column("relation", sa.String(length=50), nullable=True), + sa.Column("file_name", sa.String(length=256), nullable=False), + content_column, + sa.Column("content_size", sa.Integer(), nullable=True), + sa.Column("description", sa.String(length=1000), nullable=True), + sa.PrimaryKeyConstraint("file_id"), + schema=get_db_schema(), + ) def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_table('upload_file', schema=get_db_schema()) + op.drop_table("upload_file", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/migrations/versions/5b1e810b1e89_v22_12_0_feature_390.py b/migrations/versions/5b1e810b1e89_v22_12_0_feature_390.py index f3c3e1ab..445cbc91 100644 --- a/migrations/versions/5b1e810b1e89_v22_12_0_feature_390.py +++ b/migrations/versions/5b1e810b1e89_v22_12_0_feature_390.py @@ -5,68 +5,139 @@ Create Date: 2022-10-03 19:07:38.330652 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = '5b1e810b1e89' -down_revision = 'b1844596cae5' +revision = "5b1e810b1e89" +down_revision = "b1844596cae5" branch_labels = None depends_on = None def upgrade(): - op.execute('UPDATE idx_transfer_approval SET exchange_address = \'0x0000000000000000000000000000000000000000\' WHERE exchange_address IS NULL;') - op.alter_column('idx_transfer_approval', 'application_id', - existing_type=sa.BIGINT(), - nullable=False, schema=get_db_schema()) - op.alter_column('idx_transfer_approval', 'exchange_address', - existing_type=sa.VARCHAR(length=42), - nullable=False, schema=get_db_schema()) - op.alter_column('idx_transfer_approval', 'token_address', - existing_type=sa.VARCHAR(length=42), - nullable=False, schema=get_db_schema()) + op.execute( + "UPDATE idx_transfer_approval SET exchange_address = '0x0000000000000000000000000000000000000000' WHERE exchange_address IS NULL;" + ) + op.alter_column( + "idx_transfer_approval", + "application_id", + existing_type=sa.BIGINT(), + nullable=False, + schema=get_db_schema(), + ) + op.alter_column( + "idx_transfer_approval", + "exchange_address", + existing_type=sa.VARCHAR(length=42), + nullable=False, + schema=get_db_schema(), + ) + op.alter_column( + "idx_transfer_approval", + "token_address", + existing_type=sa.VARCHAR(length=42), + nullable=False, + schema=get_db_schema(), + ) - op.execute('UPDATE transfer_approval_history SET exchange_address = \'0x0000000000000000000000000000000000000000\' WHERE exchange_address IS NULL;') - op.add_column('transfer_approval_history', sa.Column('operation_type', sa.String(length=20), nullable=False), schema=get_db_schema()) - op.alter_column('transfer_approval_history', 'application_id', - existing_type=sa.BIGINT(), - nullable=False, schema=get_db_schema()) - op.alter_column('transfer_approval_history', 'exchange_address', - existing_type=sa.VARCHAR(length=42), - nullable=False, schema=get_db_schema()) - op.alter_column('transfer_approval_history', 'token_address', - existing_type=sa.VARCHAR(length=42), - nullable=False, schema=get_db_schema()) - op.create_index(op.f('ix_transfer_approval_history_operation_type'), 'transfer_approval_history', ['operation_type'], unique=False, schema=get_db_schema()) - op.drop_column('transfer_approval_history', 'result', schema=get_db_schema()) + op.execute( + "UPDATE transfer_approval_history SET exchange_address = '0x0000000000000000000000000000000000000000' WHERE exchange_address IS NULL;" + ) + op.add_column( + "transfer_approval_history", + sa.Column("operation_type", sa.String(length=20), nullable=False), + schema=get_db_schema(), + ) + op.alter_column( + "transfer_approval_history", + "application_id", + existing_type=sa.BIGINT(), + nullable=False, + schema=get_db_schema(), + ) + op.alter_column( + "transfer_approval_history", + "exchange_address", + existing_type=sa.VARCHAR(length=42), + nullable=False, + schema=get_db_schema(), + ) + op.alter_column( + "transfer_approval_history", + "token_address", + existing_type=sa.VARCHAR(length=42), + nullable=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_transfer_approval_history_operation_type"), + "transfer_approval_history", + ["operation_type"], + unique=False, + schema=get_db_schema(), + ) + op.drop_column("transfer_approval_history", "result", schema=get_db_schema()) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.add_column('transfer_approval_history', sa.Column('result', sa.INTEGER(), autoincrement=False, nullable=True), schema=get_db_schema()) - op.drop_index(op.f('ix_transfer_approval_history_operation_type'), table_name='transfer_approval_history', schema=get_db_schema()) - op.alter_column('transfer_approval_history', 'token_address', - existing_type=sa.VARCHAR(length=42), - nullable=True, schema=get_db_schema()) - op.alter_column('transfer_approval_history', 'exchange_address', - existing_type=sa.VARCHAR(length=42), - nullable=True, schema=get_db_schema()) - op.alter_column('transfer_approval_history', 'application_id', - existing_type=sa.BIGINT(), - nullable=True, schema=get_db_schema()) - op.drop_column('transfer_approval_history', 'operation_type', schema=get_db_schema()) - op.alter_column('idx_transfer_approval', 'token_address', - existing_type=sa.VARCHAR(length=42), - nullable=True, schema=get_db_schema()) - op.alter_column('idx_transfer_approval', 'exchange_address', - existing_type=sa.VARCHAR(length=42), - nullable=True, schema=get_db_schema()) - op.alter_column('idx_transfer_approval', 'application_id', - existing_type=sa.BIGINT(), - nullable=True, schema=get_db_schema()) + op.add_column( + "transfer_approval_history", + sa.Column("result", sa.INTEGER(), autoincrement=False, nullable=True), + schema=get_db_schema(), + ) + op.drop_index( + op.f("ix_transfer_approval_history_operation_type"), + table_name="transfer_approval_history", + schema=get_db_schema(), + ) + op.alter_column( + "transfer_approval_history", + "token_address", + existing_type=sa.VARCHAR(length=42), + nullable=True, + schema=get_db_schema(), + ) + op.alter_column( + "transfer_approval_history", + "exchange_address", + existing_type=sa.VARCHAR(length=42), + nullable=True, + schema=get_db_schema(), + ) + op.alter_column( + "transfer_approval_history", + "application_id", + existing_type=sa.BIGINT(), + nullable=True, + schema=get_db_schema(), + ) + op.drop_column( + "transfer_approval_history", "operation_type", schema=get_db_schema() + ) + op.alter_column( + "idx_transfer_approval", + "token_address", + existing_type=sa.VARCHAR(length=42), + nullable=True, + schema=get_db_schema(), + ) + op.alter_column( + "idx_transfer_approval", + "exchange_address", + existing_type=sa.VARCHAR(length=42), + nullable=True, + schema=get_db_schema(), + ) + op.alter_column( + "idx_transfer_approval", + "application_id", + existing_type=sa.BIGINT(), + nullable=True, + schema=get_db_schema(), + ) # ### end Alembic commands ### diff --git a/migrations/versions/6920ad60f134_v23_3_0_feature_448.py b/migrations/versions/6920ad60f134_v23_3_0_feature_448.py index f1f85d84..844ac50e 100644 --- a/migrations/versions/6920ad60f134_v23_3_0_feature_448.py +++ b/migrations/versions/6920ad60f134_v23_3_0_feature_448.py @@ -5,73 +5,162 @@ Create Date: 2023-01-07 23:19:30.763226 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = '6920ad60f134' -down_revision = 'e17921783d89' +revision = "6920ad60f134" +down_revision = "e17921783d89" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.create_table('idx_lock', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.BigInteger(), autoincrement=True, nullable=False), - sa.Column('transaction_hash', sa.String(length=66), nullable=False), - sa.Column('block_number', sa.BigInteger(), nullable=False), - sa.Column('token_address', sa.String(length=42), nullable=False), - sa.Column('lock_address', sa.String(length=42), nullable=False), - sa.Column('account_address', sa.String(length=42), nullable=False), - sa.Column('value', sa.BigInteger(), nullable=False), - sa.Column('data', sa.JSON(), nullable=False), - sa.Column('block_timestamp', sa.DateTime(), nullable=False), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) - op.create_index(op.f('ix_idx_lock_account_address'), 'idx_lock', ['account_address'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_idx_lock_lock_address'), 'idx_lock', ['lock_address'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_idx_lock_token_address'), 'idx_lock', ['token_address'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_idx_lock_transaction_hash'), 'idx_lock', ['transaction_hash'], unique=False, schema=get_db_schema()) - op.create_table('idx_unlock', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.BigInteger(), autoincrement=True, nullable=False), - sa.Column('transaction_hash', sa.String(length=66), nullable=False), - sa.Column('block_number', sa.BigInteger(), nullable=False), - sa.Column('token_address', sa.String(length=42), nullable=False), - sa.Column('lock_address', sa.String(length=42), nullable=False), - sa.Column('account_address', sa.String(length=42), nullable=False), - sa.Column('recipient_address', sa.String(length=42), nullable=False), - sa.Column('value', sa.BigInteger(), nullable=False), - sa.Column('data', sa.JSON(), nullable=False), - sa.Column('block_timestamp', sa.DateTime(), nullable=False), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) - op.create_index(op.f('ix_idx_unlock_account_address'), 'idx_unlock', ['account_address'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_idx_unlock_lock_address'), 'idx_unlock', ['lock_address'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_idx_unlock_recipient_address'), 'idx_unlock', ['recipient_address'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_idx_unlock_token_address'), 'idx_unlock', ['token_address'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_idx_unlock_transaction_hash'), 'idx_unlock', ['transaction_hash'], unique=False, schema=get_db_schema()) + op.create_table( + "idx_lock", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False), + sa.Column("transaction_hash", sa.String(length=66), nullable=False), + sa.Column("block_number", sa.BigInteger(), nullable=False), + sa.Column("token_address", sa.String(length=42), nullable=False), + sa.Column("lock_address", sa.String(length=42), nullable=False), + sa.Column("account_address", sa.String(length=42), nullable=False), + sa.Column("value", sa.BigInteger(), nullable=False), + sa.Column("data", sa.JSON(), nullable=False), + sa.Column("block_timestamp", sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_idx_lock_account_address"), + "idx_lock", + ["account_address"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_idx_lock_lock_address"), + "idx_lock", + ["lock_address"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_idx_lock_token_address"), + "idx_lock", + ["token_address"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_idx_lock_transaction_hash"), + "idx_lock", + ["transaction_hash"], + unique=False, + schema=get_db_schema(), + ) + op.create_table( + "idx_unlock", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False), + sa.Column("transaction_hash", sa.String(length=66), nullable=False), + sa.Column("block_number", sa.BigInteger(), nullable=False), + sa.Column("token_address", sa.String(length=42), nullable=False), + sa.Column("lock_address", sa.String(length=42), nullable=False), + sa.Column("account_address", sa.String(length=42), nullable=False), + sa.Column("recipient_address", sa.String(length=42), nullable=False), + sa.Column("value", sa.BigInteger(), nullable=False), + sa.Column("data", sa.JSON(), nullable=False), + sa.Column("block_timestamp", sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_idx_unlock_account_address"), + "idx_unlock", + ["account_address"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_idx_unlock_lock_address"), + "idx_unlock", + ["lock_address"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_idx_unlock_recipient_address"), + "idx_unlock", + ["recipient_address"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_idx_unlock_token_address"), + "idx_unlock", + ["token_address"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_idx_unlock_transaction_hash"), + "idx_unlock", + ["transaction_hash"], + unique=False, + schema=get_db_schema(), + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_index(op.f('ix_idx_unlock_transaction_hash'), table_name='idx_unlock', schema=get_db_schema()) - op.drop_index(op.f('ix_idx_unlock_token_address'), table_name='idx_unlock', schema=get_db_schema()) - op.drop_index(op.f('ix_idx_unlock_recipient_address'), table_name='idx_unlock', schema=get_db_schema()) - op.drop_index(op.f('ix_idx_unlock_lock_address'), table_name='idx_unlock', schema=get_db_schema()) - op.drop_index(op.f('ix_idx_unlock_account_address'), table_name='idx_unlock', schema=get_db_schema()) - op.drop_table('idx_unlock', schema=get_db_schema()) - op.drop_index(op.f('ix_idx_lock_transaction_hash'), table_name='idx_lock', schema=get_db_schema()) - op.drop_index(op.f('ix_idx_lock_token_address'), table_name='idx_lock', schema=get_db_schema()) - op.drop_index(op.f('ix_idx_lock_lock_address'), table_name='idx_lock', schema=get_db_schema()) - op.drop_index(op.f('ix_idx_lock_account_address'), table_name='idx_lock', schema=get_db_schema()) - op.drop_table('idx_lock', schema=get_db_schema()) + op.drop_index( + op.f("ix_idx_unlock_transaction_hash"), + table_name="idx_unlock", + schema=get_db_schema(), + ) + op.drop_index( + op.f("ix_idx_unlock_token_address"), + table_name="idx_unlock", + schema=get_db_schema(), + ) + op.drop_index( + op.f("ix_idx_unlock_recipient_address"), + table_name="idx_unlock", + schema=get_db_schema(), + ) + op.drop_index( + op.f("ix_idx_unlock_lock_address"), + table_name="idx_unlock", + schema=get_db_schema(), + ) + op.drop_index( + op.f("ix_idx_unlock_account_address"), + table_name="idx_unlock", + schema=get_db_schema(), + ) + op.drop_table("idx_unlock", schema=get_db_schema()) + op.drop_index( + op.f("ix_idx_lock_transaction_hash"), + table_name="idx_lock", + schema=get_db_schema(), + ) + op.drop_index( + op.f("ix_idx_lock_token_address"), table_name="idx_lock", schema=get_db_schema() + ) + op.drop_index( + op.f("ix_idx_lock_lock_address"), table_name="idx_lock", schema=get_db_schema() + ) + op.drop_index( + op.f("ix_idx_lock_account_address"), + table_name="idx_lock", + schema=get_db_schema(), + ) + op.drop_table("idx_lock", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/migrations/versions/7d09371c365e_v23_3_0_feature_471.py b/migrations/versions/7d09371c365e_v23_3_0_feature_471.py index ea9aaac3..7a8ee129 100644 --- a/migrations/versions/7d09371c365e_v23_3_0_feature_471.py +++ b/migrations/versions/7d09371c365e_v23_3_0_feature_471.py @@ -5,15 +5,14 @@ Create Date: 2023-01-31 15:08:30.238839 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = '7d09371c365e' -down_revision = '3a0cc5e324b4' +revision = "7d09371c365e" +down_revision = "3a0cc5e324b4" branch_labels = None depends_on = None @@ -25,13 +24,22 @@ def upgrade(): # NOTE: Manually modified # 1. Added server_default arg to migrate existing record. # 2. Added alter column operation to remove server default setting. - op.add_column('token_holder', sa.Column('locked_balance', sa.BigInteger(), server_default='0', nullable=True), schema=get_db_schema()) - op.alter_column('token_holder', 'locked_balance', - existing_type=sa.BigInteger(), - existing_nullable=True, server_default=None, schema=get_db_schema()) + op.add_column( + "token_holder", + sa.Column("locked_balance", sa.BigInteger(), server_default="0", nullable=True), + schema=get_db_schema(), + ) + op.alter_column( + "token_holder", + "locked_balance", + existing_type=sa.BigInteger(), + existing_nullable=True, + server_default=None, + schema=get_db_schema(), + ) def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_column('token_holder', 'locked_balance', schema=get_db_schema()) + op.drop_column("token_holder", "locked_balance", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/migrations/versions/7fe46c2af01e_v22_6_0_feature_309.py b/migrations/versions/7fe46c2af01e_v22_6_0_feature_309.py index 37cdfa05..127448e9 100644 --- a/migrations/versions/7fe46c2af01e_v22_6_0_feature_309.py +++ b/migrations/versions/7fe46c2af01e_v22_6_0_feature_309.py @@ -5,44 +5,47 @@ Create Date: 2022-05-09 17:56:44.525807 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = '7fe46c2af01e' -down_revision = '5144d0ec6eac' +revision = "7fe46c2af01e" +down_revision = "5144d0ec6eac" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.create_table('token_holder', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('holder_list_id', sa.BigInteger(), nullable=False), - sa.Column('account_address', sa.String(length=42), nullable=False), - sa.Column('hold_balance', sa.BigInteger(), nullable=True), - sa.PrimaryKeyConstraint('holder_list_id', 'account_address') - , schema=get_db_schema()) - op.create_table('token_holders_list', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.BigInteger(), autoincrement=True, nullable=False), - sa.Column('token_address', sa.String(length=42), nullable=True), - sa.Column('block_number', sa.BigInteger(), nullable=True), - sa.Column('list_id', sa.String(length=36), nullable=True), - sa.Column('batch_status', sa.String(length=256), nullable=True), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) + op.create_table( + "token_holder", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("holder_list_id", sa.BigInteger(), nullable=False), + sa.Column("account_address", sa.String(length=42), nullable=False), + sa.Column("hold_balance", sa.BigInteger(), nullable=True), + sa.PrimaryKeyConstraint("holder_list_id", "account_address"), + schema=get_db_schema(), + ) + op.create_table( + "token_holders_list", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False), + sa.Column("token_address", sa.String(length=42), nullable=True), + sa.Column("block_number", sa.BigInteger(), nullable=True), + sa.Column("list_id", sa.String(length=36), nullable=True), + sa.Column("batch_status", sa.String(length=256), nullable=True), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_table('token_holders_list', schema=get_db_schema()) - op.drop_table('token_holder', schema=get_db_schema()) + op.drop_table("token_holders_list", schema=get_db_schema()) + op.drop_table("token_holder", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/migrations/versions/8bde2ff68ed1_v21_12_0_feature_227.py b/migrations/versions/8bde2ff68ed1_v21_12_0_feature_227.py index d18af311..8f931446 100644 --- a/migrations/versions/8bde2ff68ed1_v21_12_0_feature_227.py +++ b/migrations/versions/8bde2ff68ed1_v21_12_0_feature_227.py @@ -5,32 +5,61 @@ Create Date: 2021-12-09 10:10:13.502671 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = '8bde2ff68ed1' -down_revision = '9c694b5e95aa' +revision = "8bde2ff68ed1" +down_revision = "9c694b5e95aa" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.add_column('idx_transfer_approval', sa.Column('exchange_address', sa.String(length=42), nullable=True), schema=get_db_schema()) - op.create_index(op.f('ix_idx_transfer_approval_exchange_address'), 'idx_transfer_approval', ['exchange_address'], unique=False, schema=get_db_schema()) - op.add_column('transfer_approval_history', sa.Column('exchange_address', sa.String(length=42), nullable=True), schema=get_db_schema()) - op.create_index(op.f('ix_transfer_approval_history_exchange_address'), 'transfer_approval_history', ['exchange_address'], unique=False, schema=get_db_schema()) + op.add_column( + "idx_transfer_approval", + sa.Column("exchange_address", sa.String(length=42), nullable=True), + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_idx_transfer_approval_exchange_address"), + "idx_transfer_approval", + ["exchange_address"], + unique=False, + schema=get_db_schema(), + ) + op.add_column( + "transfer_approval_history", + sa.Column("exchange_address", sa.String(length=42), nullable=True), + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_transfer_approval_history_exchange_address"), + "transfer_approval_history", + ["exchange_address"], + unique=False, + schema=get_db_schema(), + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_index(op.f('ix_transfer_approval_history_exchange_address'), table_name='transfer_approval_history', schema=get_db_schema()) - op.drop_column('transfer_approval_history', 'exchange_address', schema=get_db_schema()) - op.drop_index(op.f('ix_idx_transfer_approval_exchange_address'), table_name='idx_transfer_approval', schema=get_db_schema()) - op.drop_column('idx_transfer_approval', 'exchange_address', schema=get_db_schema()) + op.drop_index( + op.f("ix_transfer_approval_history_exchange_address"), + table_name="transfer_approval_history", + schema=get_db_schema(), + ) + op.drop_column( + "transfer_approval_history", "exchange_address", schema=get_db_schema() + ) + op.drop_index( + op.f("ix_idx_transfer_approval_exchange_address"), + table_name="idx_transfer_approval", + schema=get_db_schema(), + ) + op.drop_column("idx_transfer_approval", "exchange_address", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/migrations/versions/9a178cb445c2_v21_12_0_feature_230.py b/migrations/versions/9a178cb445c2_v21_12_0_feature_230.py index a5360de8..8a5b8618 100644 --- a/migrations/versions/9a178cb445c2_v21_12_0_feature_230.py +++ b/migrations/versions/9a178cb445c2_v21_12_0_feature_230.py @@ -5,32 +5,33 @@ Create Date: 2021-12-10 10:42:25.545296 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = '9a178cb445c2' -down_revision = '8bde2ff68ed1' +revision = "9a178cb445c2" +down_revision = "8bde2ff68ed1" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.create_table('additional_token_info', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('token_address', sa.String(length=42), nullable=False), - sa.Column('is_manual_transfer_approval', sa.Boolean(), nullable=True), - sa.PrimaryKeyConstraint('token_address') - , schema=get_db_schema()) + op.create_table( + "additional_token_info", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("token_address", sa.String(length=42), nullable=False), + sa.Column("is_manual_transfer_approval", sa.Boolean(), nullable=True), + sa.PrimaryKeyConstraint("token_address"), + schema=get_db_schema(), + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_table('additional_token_info', schema=get_db_schema()) + op.drop_table("additional_token_info", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/migrations/versions/9c694b5e95aa_v21_12_0_feature_222.py b/migrations/versions/9c694b5e95aa_v21_12_0_feature_222.py index 7ab15c0a..6e901140 100644 --- a/migrations/versions/9c694b5e95aa_v21_12_0_feature_222.py +++ b/migrations/versions/9c694b5e95aa_v21_12_0_feature_222.py @@ -5,28 +5,35 @@ Create Date: 2021-10-18 13:54:40.783076 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = '9c694b5e95aa' -down_revision = '52b9095d9dff' +revision = "9c694b5e95aa" +down_revision = "52b9095d9dff" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.add_column('idx_position', sa.Column('exchange_balance', sa.BigInteger(), nullable=True), schema=get_db_schema()) - op.add_column('idx_position', sa.Column('exchange_commitment', sa.BigInteger(), nullable=True), schema=get_db_schema()) + op.add_column( + "idx_position", + sa.Column("exchange_balance", sa.BigInteger(), nullable=True), + schema=get_db_schema(), + ) + op.add_column( + "idx_position", + sa.Column("exchange_commitment", sa.BigInteger(), nullable=True), + schema=get_db_schema(), + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_column('idx_position', 'exchange_commitment', schema=get_db_schema()) - op.drop_column('idx_position', 'exchange_balance', schema=get_db_schema()) + op.drop_column("idx_position", "exchange_commitment", schema=get_db_schema()) + op.drop_column("idx_position", "exchange_balance", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/migrations/versions/9ff331ab950b_v0_1_0.py b/migrations/versions/9ff331ab950b_v0_1_0.py index 497863b6..aecbe017 100644 --- a/migrations/versions/9ff331ab950b_v0_1_0.py +++ b/migrations/versions/9ff331ab950b_v0_1_0.py @@ -3,14 +3,13 @@ Revises: Create Date: 2021-03-19 21:03:52.102757 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = '9ff331ab950b' +revision = "9ff331ab950b" down_revision = None branch_labels = None depends_on = None @@ -18,144 +17,294 @@ def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.create_table('account', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('issuer_address', sa.String(length=42), nullable=False), - sa.Column('keyfile', sa.JSON(), nullable=True), - sa.Column('eoa_password', sa.String(length=2000), nullable=True), - sa.Column('rsa_private_key', sa.String(length=8000), nullable=True), - sa.Column('rsa_public_key', sa.String(length=2000), nullable=True), - sa.Column('rsa_passphrase', sa.String(length=2000), nullable=True), - sa.Column('rsa_status', sa.Integer(), nullable=True), - sa.Column('is_deleted', sa.Boolean(), nullable=True), - sa.PrimaryKeyConstraint('issuer_address') - , schema=get_db_schema()) - op.create_table('account_rsa_key_temporary', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('issuer_address', sa.String(length=42), nullable=False), - sa.Column('rsa_private_key', sa.String(length=8000), nullable=True), - sa.Column('rsa_public_key', sa.String(length=2000), nullable=True), - sa.Column('rsa_passphrase', sa.String(length=2000), nullable=True), - sa.PrimaryKeyConstraint('issuer_address') - , schema=get_db_schema()) - op.create_table('bulk_transfer', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), - sa.Column('issuer_address', sa.String(length=42), nullable=False), - sa.Column('upload_id', sa.String(length=36), nullable=True), - sa.Column('token_address', sa.String(length=42), nullable=False), - sa.Column('token_type', sa.String(length=40), nullable=False), - sa.Column('from_address', sa.String(length=42), nullable=False), - sa.Column('to_address', sa.String(length=42), nullable=False), - sa.Column('amount', sa.Integer(), nullable=False), - sa.Column('status', sa.Integer(), nullable=False), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) - op.create_index(op.f('ix_bulk_transfer_issuer_address'), 'bulk_transfer', ['issuer_address'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_bulk_transfer_status'), 'bulk_transfer', ['status'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_bulk_transfer_upload_id'), 'bulk_transfer', ['upload_id'], unique=False, schema=get_db_schema()) - op.create_table('bulk_transfer_upload', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('upload_id', sa.String(length=36), nullable=False), - sa.Column('issuer_address', sa.String(length=42), nullable=False), - sa.Column('token_type', sa.String(length=40), nullable=False), - sa.Column('status', sa.Integer(), nullable=False), - sa.PrimaryKeyConstraint('upload_id') - , schema=get_db_schema()) - op.create_index(op.f('ix_bulk_transfer_upload_issuer_address'), 'bulk_transfer_upload', ['issuer_address'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_bulk_transfer_upload_status'), 'bulk_transfer_upload', ['status'], unique=False, schema=get_db_schema()) - op.create_table('idx_personal_info', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.BigInteger(), autoincrement=True, nullable=False), - sa.Column('account_address', sa.String(length=42), nullable=True), - sa.Column('issuer_address', sa.String(length=42), nullable=True), - sa.Column('personal_info', sa.JSON(), nullable=False), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) - op.create_index(op.f('ix_idx_personal_info_account_address'), 'idx_personal_info', ['account_address'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_idx_personal_info_issuer_address'), 'idx_personal_info', ['issuer_address'], unique=False, schema=get_db_schema()) - op.create_table('idx_personal_info_block_number', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.BigInteger(), autoincrement=True, nullable=False), - sa.Column('latest_block_number', sa.BigInteger(), nullable=True), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) - op.create_table('idx_position', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.BigInteger(), autoincrement=True, nullable=False), - sa.Column('token_address', sa.String(length=42), nullable=True), - sa.Column('account_address', sa.String(length=42), nullable=True), - sa.Column('balance', sa.BigInteger(), nullable=True), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) - op.create_index(op.f('ix_idx_position_account_address'), 'idx_position', ['account_address'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_idx_position_token_address'), 'idx_position', ['token_address'], unique=False, schema=get_db_schema()) - op.create_table('idx_transfer', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.BigInteger(), autoincrement=True, nullable=False), - sa.Column('transaction_hash', sa.String(length=66), nullable=True), - sa.Column('token_address', sa.String(length=42), nullable=True), - sa.Column('transfer_from', sa.String(length=42), nullable=True), - sa.Column('transfer_to', sa.String(length=42), nullable=True), - sa.Column('amount', sa.BigInteger(), nullable=True), - sa.Column('block_timestamp', sa.DateTime(), nullable=True), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) - op.create_index(op.f('ix_idx_transfer_token_address'), 'idx_transfer', ['token_address'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_idx_transfer_transaction_hash'), 'idx_transfer', ['transaction_hash'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_idx_transfer_transfer_from'), 'idx_transfer', ['transfer_from'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_idx_transfer_transfer_to'), 'idx_transfer', ['transfer_to'], unique=False, schema=get_db_schema()) - op.create_table('token', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), - sa.Column('type', sa.String(length=40), nullable=False), - sa.Column('tx_hash', sa.String(length=66), nullable=False), - sa.Column('issuer_address', sa.String(length=42), nullable=True), - sa.Column('token_address', sa.String(length=42), nullable=True), - sa.Column('abi', sa.JSON(), nullable=False), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) - op.create_table('tx_management', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('tx_from', sa.String(length=42), nullable=False), - sa.PrimaryKeyConstraint('tx_from') - , schema=get_db_schema()) + op.create_table( + "account", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("issuer_address", sa.String(length=42), nullable=False), + sa.Column("keyfile", sa.JSON(), nullable=True), + sa.Column("eoa_password", sa.String(length=2000), nullable=True), + sa.Column("rsa_private_key", sa.String(length=8000), nullable=True), + sa.Column("rsa_public_key", sa.String(length=2000), nullable=True), + sa.Column("rsa_passphrase", sa.String(length=2000), nullable=True), + sa.Column("rsa_status", sa.Integer(), nullable=True), + sa.Column("is_deleted", sa.Boolean(), nullable=True), + sa.PrimaryKeyConstraint("issuer_address"), + schema=get_db_schema(), + ) + op.create_table( + "account_rsa_key_temporary", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("issuer_address", sa.String(length=42), nullable=False), + sa.Column("rsa_private_key", sa.String(length=8000), nullable=True), + sa.Column("rsa_public_key", sa.String(length=2000), nullable=True), + sa.Column("rsa_passphrase", sa.String(length=2000), nullable=True), + sa.PrimaryKeyConstraint("issuer_address"), + schema=get_db_schema(), + ) + op.create_table( + "bulk_transfer", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), + sa.Column("issuer_address", sa.String(length=42), nullable=False), + sa.Column("upload_id", sa.String(length=36), nullable=True), + sa.Column("token_address", sa.String(length=42), nullable=False), + sa.Column("token_type", sa.String(length=40), nullable=False), + sa.Column("from_address", sa.String(length=42), nullable=False), + sa.Column("to_address", sa.String(length=42), nullable=False), + sa.Column("amount", sa.Integer(), nullable=False), + sa.Column("status", sa.Integer(), nullable=False), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_bulk_transfer_issuer_address"), + "bulk_transfer", + ["issuer_address"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_bulk_transfer_status"), + "bulk_transfer", + ["status"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_bulk_transfer_upload_id"), + "bulk_transfer", + ["upload_id"], + unique=False, + schema=get_db_schema(), + ) + op.create_table( + "bulk_transfer_upload", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("upload_id", sa.String(length=36), nullable=False), + sa.Column("issuer_address", sa.String(length=42), nullable=False), + sa.Column("token_type", sa.String(length=40), nullable=False), + sa.Column("status", sa.Integer(), nullable=False), + sa.PrimaryKeyConstraint("upload_id"), + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_bulk_transfer_upload_issuer_address"), + "bulk_transfer_upload", + ["issuer_address"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_bulk_transfer_upload_status"), + "bulk_transfer_upload", + ["status"], + unique=False, + schema=get_db_schema(), + ) + op.create_table( + "idx_personal_info", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False), + sa.Column("account_address", sa.String(length=42), nullable=True), + sa.Column("issuer_address", sa.String(length=42), nullable=True), + sa.Column("personal_info", sa.JSON(), nullable=False), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_idx_personal_info_account_address"), + "idx_personal_info", + ["account_address"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_idx_personal_info_issuer_address"), + "idx_personal_info", + ["issuer_address"], + unique=False, + schema=get_db_schema(), + ) + op.create_table( + "idx_personal_info_block_number", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False), + sa.Column("latest_block_number", sa.BigInteger(), nullable=True), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) + op.create_table( + "idx_position", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False), + sa.Column("token_address", sa.String(length=42), nullable=True), + sa.Column("account_address", sa.String(length=42), nullable=True), + sa.Column("balance", sa.BigInteger(), nullable=True), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_idx_position_account_address"), + "idx_position", + ["account_address"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_idx_position_token_address"), + "idx_position", + ["token_address"], + unique=False, + schema=get_db_schema(), + ) + op.create_table( + "idx_transfer", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False), + sa.Column("transaction_hash", sa.String(length=66), nullable=True), + sa.Column("token_address", sa.String(length=42), nullable=True), + sa.Column("transfer_from", sa.String(length=42), nullable=True), + sa.Column("transfer_to", sa.String(length=42), nullable=True), + sa.Column("amount", sa.BigInteger(), nullable=True), + sa.Column("block_timestamp", sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_idx_transfer_token_address"), + "idx_transfer", + ["token_address"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_idx_transfer_transaction_hash"), + "idx_transfer", + ["transaction_hash"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_idx_transfer_transfer_from"), + "idx_transfer", + ["transfer_from"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_idx_transfer_transfer_to"), + "idx_transfer", + ["transfer_to"], + unique=False, + schema=get_db_schema(), + ) + op.create_table( + "token", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), + sa.Column("type", sa.String(length=40), nullable=False), + sa.Column("tx_hash", sa.String(length=66), nullable=False), + sa.Column("issuer_address", sa.String(length=42), nullable=True), + sa.Column("token_address", sa.String(length=42), nullable=True), + sa.Column("abi", sa.JSON(), nullable=False), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) + op.create_table( + "tx_management", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("tx_from", sa.String(length=42), nullable=False), + sa.PrimaryKeyConstraint("tx_from"), + schema=get_db_schema(), + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_table('tx_management', schema=get_db_schema()) - op.drop_table('token', schema=get_db_schema()) - op.drop_index(op.f('ix_idx_transfer_transfer_to'), table_name='idx_transfer', schema=get_db_schema()) - op.drop_index(op.f('ix_idx_transfer_transfer_from'), table_name='idx_transfer', schema=get_db_schema()) - op.drop_index(op.f('ix_idx_transfer_transaction_hash'), table_name='idx_transfer', schema=get_db_schema()) - op.drop_index(op.f('ix_idx_transfer_token_address'), table_name='idx_transfer', schema=get_db_schema()) - op.drop_table('idx_transfer', schema=get_db_schema()) - op.drop_index(op.f('ix_idx_position_token_address'), table_name='idx_position', schema=get_db_schema()) - op.drop_index(op.f('ix_idx_position_account_address'), table_name='idx_position', schema=get_db_schema()) - op.drop_table('idx_position', schema=get_db_schema()) - op.drop_table('idx_personal_info_block_number', schema=get_db_schema()) - op.drop_index(op.f('ix_idx_personal_info_issuer_address'), table_name='idx_personal_info', schema=get_db_schema()) - op.drop_index(op.f('ix_idx_personal_info_account_address'), table_name='idx_personal_info', schema=get_db_schema()) - op.drop_table('idx_personal_info', schema=get_db_schema()) - op.drop_index(op.f('ix_bulk_transfer_upload_status'), table_name='bulk_transfer_upload', schema=get_db_schema()) - op.drop_index(op.f('ix_bulk_transfer_upload_issuer_address'), table_name='bulk_transfer_upload', schema=get_db_schema()) - op.drop_table('bulk_transfer_upload', schema=get_db_schema()) - op.drop_index(op.f('ix_bulk_transfer_upload_id'), table_name='bulk_transfer', schema=get_db_schema()) - op.drop_index(op.f('ix_bulk_transfer_status'), table_name='bulk_transfer', schema=get_db_schema()) - op.drop_index(op.f('ix_bulk_transfer_issuer_address'), table_name='bulk_transfer', schema=get_db_schema()) - op.drop_table('bulk_transfer', schema=get_db_schema()) - op.drop_table('account_rsa_key_temporary', schema=get_db_schema()) - op.drop_table('account', schema=get_db_schema()) - # ### end Alembic commands ### \ No newline at end of file + op.drop_table("tx_management", schema=get_db_schema()) + op.drop_table("token", schema=get_db_schema()) + op.drop_index( + op.f("ix_idx_transfer_transfer_to"), + table_name="idx_transfer", + schema=get_db_schema(), + ) + op.drop_index( + op.f("ix_idx_transfer_transfer_from"), + table_name="idx_transfer", + schema=get_db_schema(), + ) + op.drop_index( + op.f("ix_idx_transfer_transaction_hash"), + table_name="idx_transfer", + schema=get_db_schema(), + ) + op.drop_index( + op.f("ix_idx_transfer_token_address"), + table_name="idx_transfer", + schema=get_db_schema(), + ) + op.drop_table("idx_transfer", schema=get_db_schema()) + op.drop_index( + op.f("ix_idx_position_token_address"), + table_name="idx_position", + schema=get_db_schema(), + ) + op.drop_index( + op.f("ix_idx_position_account_address"), + table_name="idx_position", + schema=get_db_schema(), + ) + op.drop_table("idx_position", schema=get_db_schema()) + op.drop_table("idx_personal_info_block_number", schema=get_db_schema()) + op.drop_index( + op.f("ix_idx_personal_info_issuer_address"), + table_name="idx_personal_info", + schema=get_db_schema(), + ) + op.drop_index( + op.f("ix_idx_personal_info_account_address"), + table_name="idx_personal_info", + schema=get_db_schema(), + ) + op.drop_table("idx_personal_info", schema=get_db_schema()) + op.drop_index( + op.f("ix_bulk_transfer_upload_status"), + table_name="bulk_transfer_upload", + schema=get_db_schema(), + ) + op.drop_index( + op.f("ix_bulk_transfer_upload_issuer_address"), + table_name="bulk_transfer_upload", + schema=get_db_schema(), + ) + op.drop_table("bulk_transfer_upload", schema=get_db_schema()) + op.drop_index( + op.f("ix_bulk_transfer_upload_id"), + table_name="bulk_transfer", + schema=get_db_schema(), + ) + op.drop_index( + op.f("ix_bulk_transfer_status"), + table_name="bulk_transfer", + schema=get_db_schema(), + ) + op.drop_index( + op.f("ix_bulk_transfer_issuer_address"), + table_name="bulk_transfer", + schema=get_db_schema(), + ) + op.drop_table("bulk_transfer", schema=get_db_schema()) + op.drop_table("account_rsa_key_temporary", schema=get_db_schema()) + op.drop_table("account", schema=get_db_schema()) + # ### end Alembic commands ### diff --git a/migrations/versions/b1844596cae5_v22_9_0_feature_383.py b/migrations/versions/b1844596cae5_v22_9_0_feature_383.py index 6ac4877e..1efe8a9a 100644 --- a/migrations/versions/b1844596cae5_v22_9_0_feature_383.py +++ b/migrations/versions/b1844596cae5_v22_9_0_feature_383.py @@ -5,28 +5,35 @@ Create Date: 2022-09-05 19:31:48.858899 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = 'b1844596cae5' -down_revision = '3a809fa594f8' +revision = "b1844596cae5" +down_revision = "3a809fa594f8" branch_labels = None depends_on = None def upgrade(): - op.execute('UPDATE upload_file SET label = \'\' WHERE label IS NULL;') - op.alter_column('upload_file', 'label', - existing_type=sa.VARCHAR(length=200), - nullable=False, schema=get_db_schema()) + op.execute("UPDATE upload_file SET label = '' WHERE label IS NULL;") + op.alter_column( + "upload_file", + "label", + existing_type=sa.VARCHAR(length=200), + nullable=False, + schema=get_db_schema(), + ) def downgrade(): - op.execute('UPDATE upload_file SET label = NULL WHERE label = \'\';') - op.alter_column('upload_file', 'label', - existing_type=sa.VARCHAR(length=200), - nullable=True, schema=get_db_schema()) + op.execute("UPDATE upload_file SET label = NULL WHERE label = '';") + op.alter_column( + "upload_file", + "label", + existing_type=sa.VARCHAR(length=200), + nullable=True, + schema=get_db_schema(), + ) diff --git a/migrations/versions/b1f9da1daeb3_v21_12_0_feature_230_2.py b/migrations/versions/b1f9da1daeb3_v21_12_0_feature_230_2.py index ae34cfee..c8065978 100644 --- a/migrations/versions/b1f9da1daeb3_v21_12_0_feature_230_2.py +++ b/migrations/versions/b1f9da1daeb3_v21_12_0_feature_230_2.py @@ -5,26 +5,29 @@ Create Date: 2021-12-21 13:31:16.534558 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = 'b1f9da1daeb3' -down_revision = '9a178cb445c2' +revision = "b1f9da1daeb3" +down_revision = "9a178cb445c2" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.add_column('idx_transfer_approval', sa.Column('transfer_approved', sa.Boolean(), nullable=True), schema=get_db_schema()) + op.add_column( + "idx_transfer_approval", + sa.Column("transfer_approved", sa.Boolean(), nullable=True), + schema=get_db_schema(), + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_column('idx_transfer_approval', 'transfer_approved', schema=get_db_schema()) + op.drop_column("idx_transfer_approval", "transfer_approved", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/migrations/versions/b54c7dbe300d_v0_1_0_feature_101_119.py b/migrations/versions/b54c7dbe300d_v0_1_0_feature_101_119.py index fa3053f5..0432502c 100644 --- a/migrations/versions/b54c7dbe300d_v0_1_0_feature_101_119.py +++ b/migrations/versions/b54c7dbe300d_v0_1_0_feature_101_119.py @@ -5,110 +5,178 @@ Create Date: 2021-05-26 15:29:07.829466 """ -from alembic import op import sqlalchemy as sa +from alembic import op from sqlalchemy.dialects import postgresql from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = 'b54c7dbe300d' -down_revision = '498c64b0a5ad' +revision = "b54c7dbe300d" +down_revision = "498c64b0a5ad" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.create_table('ledger', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), - sa.Column('token_address', sa.String(length=42), nullable=False), - sa.Column('token_type', sa.String(length=40), nullable=False), - sa.Column('ledger', sa.JSON(), nullable=False), - sa.Column('ledger_created', sa.DateTime(), nullable=False), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) - op.create_table('ledger_details_data', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), - sa.Column('token_address', sa.String(length=42), nullable=False), - sa.Column('data_id', sa.String(length=42), nullable=True), - sa.Column('name', sa.String(length=200), nullable=True), - sa.Column('address', sa.String(length=200), nullable=True), - sa.Column('amount', sa.Integer(), nullable=True), - sa.Column('price', sa.Integer(), nullable=True), - sa.Column('balance', sa.Integer(), nullable=True), - sa.Column('acquisition_date', sa.String(length=10), nullable=True), - sa.Column('data_created', sa.DateTime(), nullable=False), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) - op.create_table('ledger_details_template', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), - sa.Column('token_address', sa.String(length=42), nullable=False), - sa.Column('token_detail_type', sa.String(length=100), nullable=False), - sa.Column('headers', sa.JSON(), nullable=True), - sa.Column('footers', sa.JSON(), nullable=True), - sa.Column('data_type', sa.String(length=20), nullable=False), - sa.Column('data_source', sa.String(length=42), nullable=True), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) - op.create_table('ledger_template', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('token_address', sa.String(length=42), nullable=False), - sa.Column('issuer_address', sa.String(length=42), nullable=True), - sa.Column('token_name', sa.String(length=200), nullable=False), - sa.Column('headers', sa.JSON(), nullable=True), - sa.Column('footers', sa.JSON(), nullable=True), - sa.PrimaryKeyConstraint('token_address') - , schema=get_db_schema()) - op.drop_table('bond_ledger', schema=get_db_schema()) - op.drop_index('ix_corporate_bond_ledger_template_jpn_issuer_address', table_name='corporate_bond_ledger_template_jpn', schema=get_db_schema()) - op.drop_index('ix_corporate_bond_ledger_template_jpn_token_address', table_name='corporate_bond_ledger_template_jpn', schema=get_db_schema()) - op.drop_table('corporate_bond_ledger_template_jpn', schema=get_db_schema()) + op.create_table( + "ledger", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), + sa.Column("token_address", sa.String(length=42), nullable=False), + sa.Column("token_type", sa.String(length=40), nullable=False), + sa.Column("ledger", sa.JSON(), nullable=False), + sa.Column("ledger_created", sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) + op.create_table( + "ledger_details_data", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), + sa.Column("token_address", sa.String(length=42), nullable=False), + sa.Column("data_id", sa.String(length=42), nullable=True), + sa.Column("name", sa.String(length=200), nullable=True), + sa.Column("address", sa.String(length=200), nullable=True), + sa.Column("amount", sa.Integer(), nullable=True), + sa.Column("price", sa.Integer(), nullable=True), + sa.Column("balance", sa.Integer(), nullable=True), + sa.Column("acquisition_date", sa.String(length=10), nullable=True), + sa.Column("data_created", sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) + op.create_table( + "ledger_details_template", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), + sa.Column("token_address", sa.String(length=42), nullable=False), + sa.Column("token_detail_type", sa.String(length=100), nullable=False), + sa.Column("headers", sa.JSON(), nullable=True), + sa.Column("footers", sa.JSON(), nullable=True), + sa.Column("data_type", sa.String(length=20), nullable=False), + sa.Column("data_source", sa.String(length=42), nullable=True), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) + op.create_table( + "ledger_template", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("token_address", sa.String(length=42), nullable=False), + sa.Column("issuer_address", sa.String(length=42), nullable=True), + sa.Column("token_name", sa.String(length=200), nullable=False), + sa.Column("headers", sa.JSON(), nullable=True), + sa.Column("footers", sa.JSON(), nullable=True), + sa.PrimaryKeyConstraint("token_address"), + schema=get_db_schema(), + ) + op.drop_table("bond_ledger", schema=get_db_schema()) + op.drop_index( + "ix_corporate_bond_ledger_template_jpn_issuer_address", + table_name="corporate_bond_ledger_template_jpn", + schema=get_db_schema(), + ) + op.drop_index( + "ix_corporate_bond_ledger_template_jpn_token_address", + table_name="corporate_bond_ledger_template_jpn", + schema=get_db_schema(), + ) + op.drop_table("corporate_bond_ledger_template_jpn", schema=get_db_schema()) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.create_table('corporate_bond_ledger_template_jpn', - sa.Column('created', sa.DateTime(), autoincrement=False, nullable=True), - sa.Column('modified', sa.DateTime(), autoincrement=False, nullable=True), - sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False), - sa.Column('token_address', sa.VARCHAR(length=42), autoincrement=False, nullable=True), - sa.Column('issuer_address', sa.VARCHAR(length=42), autoincrement=False, nullable=True), - sa.Column('bond_name', sa.VARCHAR(length=200), autoincrement=False, nullable=False), - sa.Column('bond_description', sa.VARCHAR(length=1000), autoincrement=False, nullable=False), - sa.Column('bond_type', sa.VARCHAR(length=1000), autoincrement=False, nullable=False), - sa.Column('total_amount', sa.BIGINT(), autoincrement=False, nullable=False), - sa.Column('face_value', sa.INTEGER(), autoincrement=False, nullable=False), - sa.Column('payment_amount', sa.BIGINT(), autoincrement=False, nullable=True), - sa.Column('payment_date', sa.VARCHAR(length=8), autoincrement=False, nullable=True), - sa.Column('payment_status', sa.BOOLEAN(), autoincrement=False, nullable=False), - sa.Column('ledger_admin_headquarters', sa.VARCHAR(length=200), autoincrement=False, nullable=False), - sa.Column('ledger_admin_name', sa.VARCHAR(length=200), autoincrement=False, nullable=False), - sa.Column('ledger_admin_office_address', sa.VARCHAR(length=200), autoincrement=False, nullable=False), - sa.PrimaryKeyConstraint('id', name='corporate_bond_ledger_template_jpn_pkey') - , schema=get_db_schema()) - op.create_index('ix_corporate_bond_ledger_template_jpn_token_address', 'corporate_bond_ledger_template_jpn', ['token_address'], unique=False, schema=get_db_schema()) - op.create_index('ix_corporate_bond_ledger_template_jpn_issuer_address', 'corporate_bond_ledger_template_jpn', ['issuer_address'], unique=False, schema=get_db_schema()) - op.create_table('bond_ledger', - sa.Column('created', sa.DateTime(), autoincrement=False, nullable=True), - sa.Column('modified', sa.DateTime(), autoincrement=False, nullable=True), - sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False), - sa.Column('token_address', sa.VARCHAR(length=42), autoincrement=False, nullable=True), - sa.Column('ledger', sa.JSON(), autoincrement=False, nullable=True), - sa.Column('country_code', sa.VARCHAR(length=3), autoincrement=False, nullable=True), - sa.Column('bond_ledger_created', sa.DateTime(), autoincrement=False, nullable=False), - sa.PrimaryKeyConstraint('id', name='bond_ledger_pkey') - , schema=get_db_schema()) - op.drop_table('ledger_template', schema=get_db_schema()) - op.drop_table('ledger_details_template', schema=get_db_schema()) - op.drop_table('ledger_details_data', schema=get_db_schema()) - op.drop_table('ledger', schema=get_db_schema()) + op.create_table( + "corporate_bond_ledger_template_jpn", + sa.Column("created", sa.DateTime(), autoincrement=False, nullable=True), + sa.Column("modified", sa.DateTime(), autoincrement=False, nullable=True), + sa.Column("id", sa.INTEGER(), autoincrement=True, nullable=False), + sa.Column( + "token_address", sa.VARCHAR(length=42), autoincrement=False, nullable=True + ), + sa.Column( + "issuer_address", sa.VARCHAR(length=42), autoincrement=False, nullable=True + ), + sa.Column( + "bond_name", sa.VARCHAR(length=200), autoincrement=False, nullable=False + ), + sa.Column( + "bond_description", + sa.VARCHAR(length=1000), + autoincrement=False, + nullable=False, + ), + sa.Column( + "bond_type", sa.VARCHAR(length=1000), autoincrement=False, nullable=False + ), + sa.Column("total_amount", sa.BIGINT(), autoincrement=False, nullable=False), + sa.Column("face_value", sa.INTEGER(), autoincrement=False, nullable=False), + sa.Column("payment_amount", sa.BIGINT(), autoincrement=False, nullable=True), + sa.Column( + "payment_date", sa.VARCHAR(length=8), autoincrement=False, nullable=True + ), + sa.Column("payment_status", sa.BOOLEAN(), autoincrement=False, nullable=False), + sa.Column( + "ledger_admin_headquarters", + sa.VARCHAR(length=200), + autoincrement=False, + nullable=False, + ), + sa.Column( + "ledger_admin_name", + sa.VARCHAR(length=200), + autoincrement=False, + nullable=False, + ), + sa.Column( + "ledger_admin_office_address", + sa.VARCHAR(length=200), + autoincrement=False, + nullable=False, + ), + sa.PrimaryKeyConstraint("id", name="corporate_bond_ledger_template_jpn_pkey"), + schema=get_db_schema(), + ) + op.create_index( + "ix_corporate_bond_ledger_template_jpn_token_address", + "corporate_bond_ledger_template_jpn", + ["token_address"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + "ix_corporate_bond_ledger_template_jpn_issuer_address", + "corporate_bond_ledger_template_jpn", + ["issuer_address"], + unique=False, + schema=get_db_schema(), + ) + op.create_table( + "bond_ledger", + sa.Column("created", sa.DateTime(), autoincrement=False, nullable=True), + sa.Column("modified", sa.DateTime(), autoincrement=False, nullable=True), + sa.Column("id", sa.INTEGER(), autoincrement=True, nullable=False), + sa.Column( + "token_address", sa.VARCHAR(length=42), autoincrement=False, nullable=True + ), + sa.Column("ledger", sa.JSON(), autoincrement=False, nullable=True), + sa.Column( + "country_code", sa.VARCHAR(length=3), autoincrement=False, nullable=True + ), + sa.Column( + "bond_ledger_created", sa.DateTime(), autoincrement=False, nullable=False + ), + sa.PrimaryKeyConstraint("id", name="bond_ledger_pkey"), + schema=get_db_schema(), + ) + op.drop_table("ledger_template", schema=get_db_schema()) + op.drop_table("ledger_details_template", schema=get_db_schema()) + op.drop_table("ledger_details_data", schema=get_db_schema()) + op.drop_table("ledger", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/migrations/versions/bb5d903f97f2_v0_1_0_feature_56.py b/migrations/versions/bb5d903f97f2_v0_1_0_feature_56.py index 8c18690a..3a3731b9 100644 --- a/migrations/versions/bb5d903f97f2_v0_1_0_feature_56.py +++ b/migrations/versions/bb5d903f97f2_v0_1_0_feature_56.py @@ -5,32 +5,33 @@ Create Date: 2021-04-26 17:51:36.827771 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = 'bb5d903f97f2' -down_revision = 'fac5912d12bd' +revision = "bb5d903f97f2" +down_revision = "fac5912d12bd" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.create_table('node', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), - sa.Column('is_synced', sa.Boolean(), nullable=False), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) + op.create_table( + "node", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), + sa.Column("is_synced", sa.Boolean(), nullable=False), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_table('node', schema=get_db_schema()) + op.drop_table("node", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/migrations/versions/beccf439af5a_v0_1_0_feature_173.py b/migrations/versions/beccf439af5a_v0_1_0_feature_173.py index 54baa174..154203b9 100644 --- a/migrations/versions/beccf439af5a_v0_1_0_feature_173.py +++ b/migrations/versions/beccf439af5a_v0_1_0_feature_173.py @@ -5,25 +5,28 @@ Create Date: 2021-07-02 18:37:55.529209 """ -from alembic import op import sqlalchemy as sa +from alembic import op - -from app.database import get_db_schema, engine +from app.database import engine, get_db_schema # revision identifiers, used by Alembic. -revision = 'beccf439af5a' -down_revision = 'eb8557523406' +revision = "beccf439af5a" +down_revision = "eb8557523406" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.alter_column('utxo', 'account_address', - existing_type=sa.String(length=42), - nullable=False, schema=get_db_schema()) - op.drop_index('ix_utxo_account_address', table_name='utxo', schema=get_db_schema()) + op.alter_column( + "utxo", + "account_address", + existing_type=sa.String(length=42), + nullable=False, + schema=get_db_schema(), + ) + op.drop_index("ix_utxo_account_address", table_name="utxo", schema=get_db_schema()) # ### end Alembic commands ### if engine.name == "postgresql": schema = get_db_schema() @@ -31,7 +34,13 @@ def upgrade(): op.execute(f"ALTER TABLE {schema}utxo DROP CONSTRAINT utxo_pkey CASCADE") elif engine.name == "mysql": op.execute("ALTER TABLE utxo DROP PRIMARY KEY") - op.create_primary_key("utxo_pkey", "utxo", ["transaction_hash", "account_address"], schema=get_db_schema()) + op.create_primary_key( + "utxo_pkey", + "utxo", + ["transaction_hash", "account_address"], + schema=get_db_schema(), + ) + def downgrade(): if engine.name == "postgresql": @@ -40,10 +49,22 @@ def downgrade(): op.execute(f"ALTER TABLE {schema}utxo DROP CONSTRAINT utxo_pkey CASCADE") elif engine.name == "mysql": op.execute("ALTER TABLE utxo DROP PRIMARY KEY") - op.create_primary_key("utxo_pkey", "utxo", ["transaction_hash"], schema=get_db_schema()) + op.create_primary_key( + "utxo_pkey", "utxo", ["transaction_hash"], schema=get_db_schema() + ) # ### commands auto generated by Alembic - please adjust! ### - op.create_index('ix_utxo_account_address', 'utxo', ['account_address'], unique=False, schema=get_db_schema()) - op.alter_column('utxo', 'account_address', - existing_type=sa.String(length=42), - nullable=True, schema=get_db_schema()) + op.create_index( + "ix_utxo_account_address", + "utxo", + ["account_address"], + unique=False, + schema=get_db_schema(), + ) + op.alter_column( + "utxo", + "account_address", + existing_type=sa.String(length=42), + nullable=True, + schema=get_db_schema(), + ) # ### end Alembic commands ### diff --git a/migrations/versions/d5d96e880adb_v0_1_0_feature_143.py b/migrations/versions/d5d96e880adb_v0_1_0_feature_143.py index 3ac3161d..be4a6d2b 100644 --- a/migrations/versions/d5d96e880adb_v0_1_0_feature_143.py +++ b/migrations/versions/d5d96e880adb_v0_1_0_feature_143.py @@ -5,56 +5,63 @@ Create Date: 2021-06-09 16:46:51.634859 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = 'd5d96e880adb' -down_revision = '4884346fad46' +revision = "d5d96e880adb" +down_revision = "4884346fad46" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.create_table('idx_position_bond_block_number', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.BigInteger(), autoincrement=True, nullable=False), - sa.Column('latest_block_number', sa.BigInteger(), nullable=True), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) - op.create_table('idx_position_share_block_number', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.BigInteger(), autoincrement=True, nullable=False), - sa.Column('latest_block_number', sa.BigInteger(), nullable=True), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) - op.create_table('idx_transfer_approval_block_number', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.BigInteger(), autoincrement=True, nullable=False), - sa.Column('latest_block_number', sa.BigInteger(), nullable=True), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) - op.create_table('idx_transfer_block_number', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.BigInteger(), autoincrement=True, nullable=False), - sa.Column('latest_block_number', sa.BigInteger(), nullable=True), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) + op.create_table( + "idx_position_bond_block_number", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False), + sa.Column("latest_block_number", sa.BigInteger(), nullable=True), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) + op.create_table( + "idx_position_share_block_number", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False), + sa.Column("latest_block_number", sa.BigInteger(), nullable=True), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) + op.create_table( + "idx_transfer_approval_block_number", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False), + sa.Column("latest_block_number", sa.BigInteger(), nullable=True), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) + op.create_table( + "idx_transfer_block_number", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False), + sa.Column("latest_block_number", sa.BigInteger(), nullable=True), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_table('idx_transfer_block_number', schema=get_db_schema()) - op.drop_table('idx_transfer_approval_block_number', schema=get_db_schema()) - op.drop_table('idx_position_share_block_number', schema=get_db_schema()) - op.drop_table('idx_position_bond_block_number', schema=get_db_schema()) + op.drop_table("idx_transfer_block_number", schema=get_db_schema()) + op.drop_table("idx_transfer_approval_block_number", schema=get_db_schema()) + op.drop_table("idx_position_share_block_number", schema=get_db_schema()) + op.drop_table("idx_position_bond_block_number", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/migrations/versions/e17921783d89_v23_3_0_feature_448.py b/migrations/versions/e17921783d89_v23_3_0_feature_448.py index 8f7c525c..898bc801 100644 --- a/migrations/versions/e17921783d89_v23_3_0_feature_448.py +++ b/migrations/versions/e17921783d89_v23_3_0_feature_448.py @@ -5,34 +5,35 @@ Create Date: 2023-01-05 23:29:52.186466 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = 'e17921783d89' -down_revision = '102b3b000e56' +revision = "e17921783d89" +down_revision = "102b3b000e56" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.create_table('idx_locked_position', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('token_address', sa.String(length=42), nullable=False), - sa.Column('lock_address', sa.String(length=42), nullable=False), - sa.Column('account_address', sa.String(length=42), nullable=False), - sa.Column('value', sa.BigInteger(), nullable=False), - sa.PrimaryKeyConstraint('token_address', 'lock_address', 'account_address') - , schema=get_db_schema()) + op.create_table( + "idx_locked_position", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("token_address", sa.String(length=42), nullable=False), + sa.Column("lock_address", sa.String(length=42), nullable=False), + sa.Column("account_address", sa.String(length=42), nullable=False), + sa.Column("value", sa.BigInteger(), nullable=False), + sa.PrimaryKeyConstraint("token_address", "lock_address", "account_address"), + schema=get_db_schema(), + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_table('idx_locked_position', schema=get_db_schema()) + op.drop_table("idx_locked_position", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/migrations/versions/e91c3d19e99f_v0_1_0_feature_118.py b/migrations/versions/e91c3d19e99f_v0_1_0_feature_118.py index 7bf2e874..89ada972 100644 --- a/migrations/versions/e91c3d19e99f_v0_1_0_feature_118.py +++ b/migrations/versions/e91c3d19e99f_v0_1_0_feature_118.py @@ -5,37 +5,38 @@ Create Date: 2021-06-01 16:50:27.879184 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = 'e91c3d19e99f' -down_revision = 'b54c7dbe300d' +revision = "e91c3d19e99f" +down_revision = "b54c7dbe300d" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.create_table('notification', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), - sa.Column('notice_id', sa.String(length=36), nullable=True), - sa.Column('issuer_address', sa.String(length=42), nullable=True), - sa.Column('priority', sa.Integer(), nullable=True), - sa.Column('type', sa.String(length=50), nullable=True), - sa.Column('code', sa.Integer(), nullable=True), - sa.Column('metainfo', sa.JSON(), nullable=True), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) + op.create_table( + "notification", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), + sa.Column("notice_id", sa.String(length=36), nullable=True), + sa.Column("issuer_address", sa.String(length=42), nullable=True), + sa.Column("priority", sa.Integer(), nullable=True), + sa.Column("type", sa.String(length=50), nullable=True), + sa.Column("code", sa.Integer(), nullable=True), + sa.Column("metainfo", sa.JSON(), nullable=True), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_table('notification', schema=get_db_schema()) + op.drop_table("notification", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/migrations/versions/eb8557523406_v0_1_0_feature_159.py b/migrations/versions/eb8557523406_v0_1_0_feature_159.py index 5f82706f..f0463ad7 100644 --- a/migrations/versions/eb8557523406_v0_1_0_feature_159.py +++ b/migrations/versions/eb8557523406_v0_1_0_feature_159.py @@ -5,40 +5,51 @@ Create Date: 2021-06-28 20:20:58.229012 """ -from alembic import op import sqlalchemy as sa +from alembic import op - -from app.database import get_db_schema, engine +from app.database import engine, get_db_schema # revision identifiers, used by Alembic. -revision = 'eb8557523406' -down_revision = 'f6056503a291' +revision = "eb8557523406" +down_revision = "f6056503a291" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.alter_column('ledger_details_data', 'data_id', - existing_type=sa.String(length=42), - type_=sa.String(length=36), - existing_nullable=True, schema=get_db_schema()) + op.alter_column( + "ledger_details_data", + "data_id", + existing_type=sa.String(length=42), + type_=sa.String(length=36), + existing_nullable=True, + schema=get_db_schema(), + ) # ### end Alembic commands ### if engine.name == "postgresql": schema = get_db_schema() schema = f"{schema}." if schema is not None else "" - op.execute(f"ALTER INDEX {schema}ix_idx_transfer_from_to RENAME TO ix_idx_transfer_to_address") + op.execute( + f"ALTER INDEX {schema}ix_idx_transfer_from_to RENAME TO ix_idx_transfer_to_address" + ) def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.alter_column('ledger_details_data', 'data_id', - existing_type=sa.String(length=36), - type_=sa.String(length=42), - existing_nullable=True, schema=get_db_schema()) + op.alter_column( + "ledger_details_data", + "data_id", + existing_type=sa.String(length=36), + type_=sa.String(length=42), + existing_nullable=True, + schema=get_db_schema(), + ) # ### end Alembic commands ### if engine.name == "postgresql": schema = get_db_schema() schema = f"{schema}." if schema is not None else "" - op.execute(f"ALTER INDEX {schema}ix_idx_transfer_to_address RENAME TO ix_idx_transfer_from_to") + op.execute( + f"ALTER INDEX {schema}ix_idx_transfer_to_address RENAME TO ix_idx_transfer_from_to" + ) diff --git a/migrations/versions/ec0ac096e294_v22_3_0_feature_276.py b/migrations/versions/ec0ac096e294_v22_3_0_feature_276.py index dd94f756..6089acf8 100644 --- a/migrations/versions/ec0ac096e294_v22_3_0_feature_276.py +++ b/migrations/versions/ec0ac096e294_v22_3_0_feature_276.py @@ -5,81 +5,138 @@ Create Date: 2022-03-18 17:21:40.418155 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = 'ec0ac096e294' -down_revision = 'b1f9da1daeb3' +revision = "ec0ac096e294" +down_revision = "b1f9da1daeb3" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.create_table('e2e_messaging_account', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('account_address', sa.String(length=42), nullable=False), - sa.Column('keyfile', sa.JSON(), nullable=True), - sa.Column('eoa_password', sa.String(length=2000), nullable=True), - sa.Column('rsa_key_generate_interval', sa.Integer(), nullable=True), - sa.Column('rsa_generation', sa.Integer(), nullable=True), - sa.Column('is_deleted', sa.Boolean(), nullable=True), - sa.PrimaryKeyConstraint('account_address') - , schema=get_db_schema()) - op.create_table('e2e_messaging_account_rsa_key', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.BigInteger(), autoincrement=True, nullable=False), - sa.Column('transaction_hash', sa.String(length=66), nullable=True), - sa.Column('account_address', sa.String(length=42), nullable=True), - sa.Column('rsa_private_key', sa.String(length=4000), nullable=True), - sa.Column('rsa_public_key', sa.String(length=1000), nullable=True), - sa.Column('rsa_passphrase', sa.String(length=2000), nullable=True), - sa.Column('block_timestamp', sa.DateTime(), nullable=True), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) - op.create_index(op.f('ix_e2e_messaging_account_rsa_key_account_address'), 'e2e_messaging_account_rsa_key', ['account_address'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_e2e_messaging_account_rsa_key_transaction_hash'), 'e2e_messaging_account_rsa_key', ['transaction_hash'], unique=False, schema=get_db_schema()) - op.create_table('idx_e2e_messaging', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.BigInteger(), autoincrement=True, nullable=False), - sa.Column('transaction_hash', sa.String(length=66), nullable=True), - sa.Column('from_address', sa.String(length=42), nullable=True), - sa.Column('to_address', sa.String(length=42), nullable=True), - sa.Column('type', sa.String(length=50), nullable=False), - sa.Column('message', sa.String(length=5000), nullable=False), - sa.Column('send_timestamp', sa.DateTime(), nullable=True), - sa.Column('block_timestamp', sa.DateTime(), nullable=True), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) - op.create_index(op.f('ix_idx_e2e_messaging_from_address'), 'idx_e2e_messaging', ['from_address'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_idx_e2e_messaging_to_address'), 'idx_e2e_messaging', ['to_address'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_idx_e2e_messaging_transaction_hash'), 'idx_e2e_messaging', ['transaction_hash'], unique=False, schema=get_db_schema()) - op.create_table('idx_e2e_messaging_block_number', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.BigInteger(), autoincrement=True, nullable=False), - sa.Column('latest_block_number', sa.BigInteger(), nullable=True), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) + op.create_table( + "e2e_messaging_account", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("account_address", sa.String(length=42), nullable=False), + sa.Column("keyfile", sa.JSON(), nullable=True), + sa.Column("eoa_password", sa.String(length=2000), nullable=True), + sa.Column("rsa_key_generate_interval", sa.Integer(), nullable=True), + sa.Column("rsa_generation", sa.Integer(), nullable=True), + sa.Column("is_deleted", sa.Boolean(), nullable=True), + sa.PrimaryKeyConstraint("account_address"), + schema=get_db_schema(), + ) + op.create_table( + "e2e_messaging_account_rsa_key", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False), + sa.Column("transaction_hash", sa.String(length=66), nullable=True), + sa.Column("account_address", sa.String(length=42), nullable=True), + sa.Column("rsa_private_key", sa.String(length=4000), nullable=True), + sa.Column("rsa_public_key", sa.String(length=1000), nullable=True), + sa.Column("rsa_passphrase", sa.String(length=2000), nullable=True), + sa.Column("block_timestamp", sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_e2e_messaging_account_rsa_key_account_address"), + "e2e_messaging_account_rsa_key", + ["account_address"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_e2e_messaging_account_rsa_key_transaction_hash"), + "e2e_messaging_account_rsa_key", + ["transaction_hash"], + unique=False, + schema=get_db_schema(), + ) + op.create_table( + "idx_e2e_messaging", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False), + sa.Column("transaction_hash", sa.String(length=66), nullable=True), + sa.Column("from_address", sa.String(length=42), nullable=True), + sa.Column("to_address", sa.String(length=42), nullable=True), + sa.Column("type", sa.String(length=50), nullable=False), + sa.Column("message", sa.String(length=5000), nullable=False), + sa.Column("send_timestamp", sa.DateTime(), nullable=True), + sa.Column("block_timestamp", sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_idx_e2e_messaging_from_address"), + "idx_e2e_messaging", + ["from_address"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_idx_e2e_messaging_to_address"), + "idx_e2e_messaging", + ["to_address"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_idx_e2e_messaging_transaction_hash"), + "idx_e2e_messaging", + ["transaction_hash"], + unique=False, + schema=get_db_schema(), + ) + op.create_table( + "idx_e2e_messaging_block_number", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False), + sa.Column("latest_block_number", sa.BigInteger(), nullable=True), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_table('idx_e2e_messaging_block_number', schema=get_db_schema()) - op.drop_index(op.f('ix_idx_e2e_messaging_transaction_hash'), table_name='idx_e2e_messaging', schema=get_db_schema()) - op.drop_index(op.f('ix_idx_e2e_messaging_to_address'), table_name='idx_e2e_messaging', schema=get_db_schema()) - op.drop_index(op.f('ix_idx_e2e_messaging_from_address'), table_name='idx_e2e_messaging', schema=get_db_schema()) - op.drop_table('idx_e2e_messaging', schema=get_db_schema()) - op.drop_index(op.f('ix_e2e_messaging_account_rsa_key_transaction_hash'), table_name='e2e_messaging_account_rsa_key', schema=get_db_schema()) - op.drop_index(op.f('ix_e2e_messaging_account_rsa_key_account_address'), table_name='e2e_messaging_account_rsa_key', schema=get_db_schema()) - op.drop_table('e2e_messaging_account_rsa_key', schema=get_db_schema()) - op.drop_table('e2e_messaging_account', schema=get_db_schema()) + op.drop_table("idx_e2e_messaging_block_number", schema=get_db_schema()) + op.drop_index( + op.f("ix_idx_e2e_messaging_transaction_hash"), + table_name="idx_e2e_messaging", + schema=get_db_schema(), + ) + op.drop_index( + op.f("ix_idx_e2e_messaging_to_address"), + table_name="idx_e2e_messaging", + schema=get_db_schema(), + ) + op.drop_index( + op.f("ix_idx_e2e_messaging_from_address"), + table_name="idx_e2e_messaging", + schema=get_db_schema(), + ) + op.drop_table("idx_e2e_messaging", schema=get_db_schema()) + op.drop_index( + op.f("ix_e2e_messaging_account_rsa_key_transaction_hash"), + table_name="e2e_messaging_account_rsa_key", + schema=get_db_schema(), + ) + op.drop_index( + op.f("ix_e2e_messaging_account_rsa_key_account_address"), + table_name="e2e_messaging_account_rsa_key", + schema=get_db_schema(), + ) + op.drop_table("e2e_messaging_account_rsa_key", schema=get_db_schema()) + op.drop_table("e2e_messaging_account", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/migrations/versions/f22f8ac0a121_v22_3_0_feature_278.py b/migrations/versions/f22f8ac0a121_v22_3_0_feature_278.py index 48124b95..c2356676 100644 --- a/migrations/versions/f22f8ac0a121_v22_3_0_feature_278.py +++ b/migrations/versions/f22f8ac0a121_v22_3_0_feature_278.py @@ -5,26 +5,29 @@ Create Date: 2022-03-25 18:29:14.846619 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = 'f22f8ac0a121' -down_revision = 'ec0ac096e294' +revision = "f22f8ac0a121" +down_revision = "ec0ac096e294" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.add_column('upload_file', sa.Column('label', sa.String(length=200), nullable=True), schema=get_db_schema()) + op.add_column( + "upload_file", + sa.Column("label", sa.String(length=200), nullable=True), + schema=get_db_schema(), + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_column('upload_file', 'label', schema=get_db_schema()) + op.drop_column("upload_file", "label", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/migrations/versions/f6056503a291_v0_1_0_feature_157.py b/migrations/versions/f6056503a291_v0_1_0_feature_157.py index dcbacc49..89b3f2f4 100644 --- a/migrations/versions/f6056503a291_v0_1_0_feature_157.py +++ b/migrations/versions/f6056503a291_v0_1_0_feature_157.py @@ -5,15 +5,14 @@ Create Date: 2021-06-23 16:00:23.143197 """ -from alembic import op import sqlalchemy as sa +from alembic import op - -from app.database import get_db_schema, engine +from app.database import engine, get_db_schema # revision identifiers, used by Alembic. -revision = 'f6056503a291' -down_revision = '0d4133a5b0e3' +revision = "f6056503a291" +down_revision = "0d4133a5b0e3" branch_labels = None depends_on = None @@ -31,16 +30,36 @@ def upgrade(): op.drop_column('idx_transfer', 'transfer_to', schema=get_db_schema()) # ### end Alembic commands ### """ - op.alter_column('idx_transfer', 'transfer_from', new_column_name='from_address', existing_type=sa.String(length=42), schema=get_db_schema()) - op.alter_column('idx_transfer', 'transfer_to', new_column_name='to_address', existing_type=sa.String(length=42), schema=get_db_schema()) + op.alter_column( + "idx_transfer", + "transfer_from", + new_column_name="from_address", + existing_type=sa.String(length=42), + schema=get_db_schema(), + ) + op.alter_column( + "idx_transfer", + "transfer_to", + new_column_name="to_address", + existing_type=sa.String(length=42), + schema=get_db_schema(), + ) if engine.name == "postgresql": schema = get_db_schema() schema = f"{schema}." if schema is not None else "" - op.execute(f"ALTER INDEX {schema}ix_idx_transfer_transfer_from RENAME TO ix_idx_transfer_from_address") - op.execute(f"ALTER INDEX {schema}ix_idx_transfer_transfer_to RENAME TO ix_idx_transfer_from_to") + op.execute( + f"ALTER INDEX {schema}ix_idx_transfer_transfer_from RENAME TO ix_idx_transfer_from_address" + ) + op.execute( + f"ALTER INDEX {schema}ix_idx_transfer_transfer_to RENAME TO ix_idx_transfer_from_to" + ) elif engine.name == "mysql": - op.execute("ALTER TABLE idx_transfer RENAME INDEX ix_idx_transfer_transfer_from TO ix_idx_transfer_from_address") - op.execute("ALTER TABLE idx_transfer RENAME INDEX ix_idx_transfer_transfer_to TO ix_idx_transfer_to_address") + op.execute( + "ALTER TABLE idx_transfer RENAME INDEX ix_idx_transfer_transfer_from TO ix_idx_transfer_from_address" + ) + op.execute( + "ALTER TABLE idx_transfer RENAME INDEX ix_idx_transfer_transfer_to TO ix_idx_transfer_to_address" + ) def downgrade(): @@ -56,13 +75,33 @@ def downgrade(): op.drop_column('idx_transfer', 'from_address', schema=get_db_schema()) # ### end Alembic commands ### """ - op.alter_column('idx_transfer', 'from_address', new_column_name='transfer_from', existing_type=sa.String(length=42), schema=get_db_schema()) - op.alter_column('idx_transfer', 'to_address', new_column_name='transfer_to', existing_type=sa.String(length=42), schema=get_db_schema()) + op.alter_column( + "idx_transfer", + "from_address", + new_column_name="transfer_from", + existing_type=sa.String(length=42), + schema=get_db_schema(), + ) + op.alter_column( + "idx_transfer", + "to_address", + new_column_name="transfer_to", + existing_type=sa.String(length=42), + schema=get_db_schema(), + ) if engine.name == "postgresql": schema = get_db_schema() schema = f"{schema}." if schema is not None else "" - op.execute(f"ALTER INDEX {schema}ix_idx_transfer_from_address RENAME TO ix_idx_transfer_transfer_from") - op.execute(f"ALTER INDEX {schema}ix_idx_transfer_from_to RENAME TO ix_idx_transfer_transfer_to") + op.execute( + f"ALTER INDEX {schema}ix_idx_transfer_from_address RENAME TO ix_idx_transfer_transfer_from" + ) + op.execute( + f"ALTER INDEX {schema}ix_idx_transfer_from_to RENAME TO ix_idx_transfer_transfer_to" + ) elif engine.name == "mysql": - op.execute("ALTER TABLE idx_transfer RENAME INDEX ix_idx_transfer_from_address TO ix_idx_transfer_transfer_from") - op.execute("ALTER TABLE idx_transfer RENAME INDEX ix_idx_transfer_to_address TO ix_idx_transfer_transfer_to") + op.execute( + "ALTER TABLE idx_transfer RENAME INDEX ix_idx_transfer_from_address TO ix_idx_transfer_transfer_from" + ) + op.execute( + "ALTER TABLE idx_transfer RENAME INDEX ix_idx_transfer_to_address TO ix_idx_transfer_transfer_to" + ) diff --git a/migrations/versions/f770297833c5_v22_9_0_feature_367.py b/migrations/versions/f770297833c5_v22_9_0_feature_367.py index 6f79ddb5..8c73f305 100644 --- a/migrations/versions/f770297833c5_v22_9_0_feature_367.py +++ b/migrations/versions/f770297833c5_v22_9_0_feature_367.py @@ -5,72 +5,119 @@ Create Date: 2022-08-09 19:02:19.545853 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = 'f770297833c5' -down_revision = '47bf57b85b0a' +revision = "f770297833c5" +down_revision = "47bf57b85b0a" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.alter_column('batch_issue_redeem', 'amount', - existing_type=sa.INTEGER(), - type_=sa.BigInteger(), - existing_nullable=False, schema=get_db_schema()) - op.alter_column('bulk_transfer', 'amount', - existing_type=sa.INTEGER(), - type_=sa.BigInteger(), - existing_nullable=False, schema=get_db_schema()) - op.alter_column('ledger_details_data', 'amount', - existing_type=sa.INTEGER(), - type_=sa.BigInteger(), - existing_nullable=True, schema=get_db_schema()) - op.alter_column('ledger_details_data', 'balance', - existing_type=sa.INTEGER(), - type_=sa.BigInteger(), - existing_nullable=True, schema=get_db_schema()) - op.alter_column('ledger_details_data', 'price', - existing_type=sa.INTEGER(), - type_=sa.BigInteger(), - existing_nullable=True, schema=get_db_schema()) - op.alter_column('utxo', 'amount', - existing_type=sa.INTEGER(), - type_=sa.BigInteger(), - existing_nullable=True, schema=get_db_schema()) + op.alter_column( + "batch_issue_redeem", + "amount", + existing_type=sa.INTEGER(), + type_=sa.BigInteger(), + existing_nullable=False, + schema=get_db_schema(), + ) + op.alter_column( + "bulk_transfer", + "amount", + existing_type=sa.INTEGER(), + type_=sa.BigInteger(), + existing_nullable=False, + schema=get_db_schema(), + ) + op.alter_column( + "ledger_details_data", + "amount", + existing_type=sa.INTEGER(), + type_=sa.BigInteger(), + existing_nullable=True, + schema=get_db_schema(), + ) + op.alter_column( + "ledger_details_data", + "balance", + existing_type=sa.INTEGER(), + type_=sa.BigInteger(), + existing_nullable=True, + schema=get_db_schema(), + ) + op.alter_column( + "ledger_details_data", + "price", + existing_type=sa.INTEGER(), + type_=sa.BigInteger(), + existing_nullable=True, + schema=get_db_schema(), + ) + op.alter_column( + "utxo", + "amount", + existing_type=sa.INTEGER(), + type_=sa.BigInteger(), + existing_nullable=True, + schema=get_db_schema(), + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.alter_column('utxo', 'amount', - existing_type=sa.BigInteger(), - type_=sa.INTEGER(), - existing_nullable=True, schema=get_db_schema()) - op.alter_column('ledger_details_data', 'price', - existing_type=sa.BigInteger(), - type_=sa.INTEGER(), - existing_nullable=True, schema=get_db_schema()) - op.alter_column('ledger_details_data', 'balance', - existing_type=sa.BigInteger(), - type_=sa.INTEGER(), - existing_nullable=True, schema=get_db_schema()) - op.alter_column('ledger_details_data', 'amount', - existing_type=sa.BigInteger(), - type_=sa.INTEGER(), - existing_nullable=True, schema=get_db_schema()) - op.alter_column('bulk_transfer', 'amount', - existing_type=sa.BigInteger(), - type_=sa.INTEGER(), - existing_nullable=False, schema=get_db_schema()) - op.alter_column('batch_issue_redeem', 'amount', - existing_type=sa.BigInteger(), - type_=sa.INTEGER(), - existing_nullable=False, schema=get_db_schema()) + op.alter_column( + "utxo", + "amount", + existing_type=sa.BigInteger(), + type_=sa.INTEGER(), + existing_nullable=True, + schema=get_db_schema(), + ) + op.alter_column( + "ledger_details_data", + "price", + existing_type=sa.BigInteger(), + type_=sa.INTEGER(), + existing_nullable=True, + schema=get_db_schema(), + ) + op.alter_column( + "ledger_details_data", + "balance", + existing_type=sa.BigInteger(), + type_=sa.INTEGER(), + existing_nullable=True, + schema=get_db_schema(), + ) + op.alter_column( + "ledger_details_data", + "amount", + existing_type=sa.BigInteger(), + type_=sa.INTEGER(), + existing_nullable=True, + schema=get_db_schema(), + ) + op.alter_column( + "bulk_transfer", + "amount", + existing_type=sa.BigInteger(), + type_=sa.INTEGER(), + existing_nullable=False, + schema=get_db_schema(), + ) + op.alter_column( + "batch_issue_redeem", + "amount", + existing_type=sa.BigInteger(), + type_=sa.INTEGER(), + existing_nullable=False, + schema=get_db_schema(), + ) # ### end Alembic commands ### diff --git a/migrations/versions/fac5912d12bd_v0_1_0_feature_80.py b/migrations/versions/fac5912d12bd_v0_1_0_feature_80.py index dbdf5e63..79efeb2e 100644 --- a/migrations/versions/fac5912d12bd_v0_1_0_feature_80.py +++ b/migrations/versions/fac5912d12bd_v0_1_0_feature_80.py @@ -5,47 +5,72 @@ Create Date: 2021-04-22 13:21:29.426107 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = 'fac5912d12bd' -down_revision = '2eee006a38d5' +revision = "fac5912d12bd" +down_revision = "2eee006a38d5" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.create_table('idx_transfer_approval', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.BigInteger(), autoincrement=True, nullable=False), - sa.Column('token_address', sa.String(length=42), nullable=True), - sa.Column('application_id', sa.BigInteger(), nullable=True), - sa.Column('from_address', sa.String(length=42), nullable=True), - sa.Column('to_address', sa.String(length=42), nullable=True), - sa.Column('amount', sa.BigInteger(), nullable=True), - sa.Column('application_datetime', sa.DateTime(), nullable=True), - sa.Column('application_blocktimestamp', sa.DateTime(), nullable=True), - sa.Column('approval_datetime', sa.DateTime(), nullable=True), - sa.Column('approval_blocktimestamp', sa.DateTime(), nullable=True), - sa.Column('cancelled', sa.Boolean(), nullable=True), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) - op.create_index(op.f('ix_idx_transfer_approval_application_id'), 'idx_transfer_approval', ['application_id'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_idx_transfer_approval_token_address'), 'idx_transfer_approval', ['token_address'], unique=False, schema=get_db_schema()) - op.add_column('idx_position', sa.Column('pending_transfer', sa.BigInteger(), nullable=True), schema=get_db_schema()) + op.create_table( + "idx_transfer_approval", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False), + sa.Column("token_address", sa.String(length=42), nullable=True), + sa.Column("application_id", sa.BigInteger(), nullable=True), + sa.Column("from_address", sa.String(length=42), nullable=True), + sa.Column("to_address", sa.String(length=42), nullable=True), + sa.Column("amount", sa.BigInteger(), nullable=True), + sa.Column("application_datetime", sa.DateTime(), nullable=True), + sa.Column("application_blocktimestamp", sa.DateTime(), nullable=True), + sa.Column("approval_datetime", sa.DateTime(), nullable=True), + sa.Column("approval_blocktimestamp", sa.DateTime(), nullable=True), + sa.Column("cancelled", sa.Boolean(), nullable=True), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_idx_transfer_approval_application_id"), + "idx_transfer_approval", + ["application_id"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_idx_transfer_approval_token_address"), + "idx_transfer_approval", + ["token_address"], + unique=False, + schema=get_db_schema(), + ) + op.add_column( + "idx_position", + sa.Column("pending_transfer", sa.BigInteger(), nullable=True), + schema=get_db_schema(), + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_column('idx_position', 'pending_transfer', schema=get_db_schema()) - op.drop_index(op.f('ix_idx_transfer_approval_token_address'), table_name='idx_transfer_approval', schema=get_db_schema()) - op.drop_index(op.f('ix_idx_transfer_approval_application_id'), table_name='idx_transfer_approval', schema=get_db_schema()) - op.drop_table('idx_transfer_approval', schema=get_db_schema()) + op.drop_column("idx_position", "pending_transfer", schema=get_db_schema()) + op.drop_index( + op.f("ix_idx_transfer_approval_token_address"), + table_name="idx_transfer_approval", + schema=get_db_schema(), + ) + op.drop_index( + op.f("ix_idx_transfer_approval_application_id"), + table_name="idx_transfer_approval", + schema=get_db_schema(), + ) + op.drop_table("idx_transfer_approval", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/migrations/versions/fad6669cad84_v22_9_0_feature_331.py b/migrations/versions/fad6669cad84_v22_9_0_feature_331.py index 03717388..0b5a2d6b 100644 --- a/migrations/versions/fad6669cad84_v22_9_0_feature_331.py +++ b/migrations/versions/fad6669cad84_v22_9_0_feature_331.py @@ -5,55 +5,98 @@ Create Date: 2022-07-11 10:11:07.522758 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = 'fad6669cad84' -down_revision = '0fc0196253f8' +revision = "fad6669cad84" +down_revision = "0fc0196253f8" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.create_table('batch_issue_redeem', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), - sa.Column('upload_id', sa.String(length=36), nullable=True), - sa.Column('account_address', sa.String(length=42), nullable=False), - sa.Column('amount', sa.Integer(), nullable=False), - sa.Column('status', sa.Integer(), nullable=False), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) - op.create_index(op.f('ix_batch_issue_redeem_status'), 'batch_issue_redeem', ['status'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_batch_issue_redeem_upload_id'), 'batch_issue_redeem', ['upload_id'], unique=False, schema=get_db_schema()) - op.create_table('batch_issue_redeem_upload', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('upload_id', sa.String(length=36), nullable=False), - sa.Column('issuer_address', sa.String(length=42), nullable=False), - sa.Column('token_type', sa.String(length=40), nullable=False), - sa.Column('token_address', sa.String(length=42), nullable=False), - sa.Column('category', sa.String(length=20), nullable=False), - sa.Column('processed', sa.Boolean(), nullable=True), - sa.PrimaryKeyConstraint('upload_id') - , schema=get_db_schema()) - op.create_index(op.f('ix_batch_issue_redeem_upload_issuer_address'), 'batch_issue_redeem_upload', ['issuer_address'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_batch_issue_redeem_upload_processed'), 'batch_issue_redeem_upload', ['processed'], unique=False, schema=get_db_schema()) + op.create_table( + "batch_issue_redeem", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), + sa.Column("upload_id", sa.String(length=36), nullable=True), + sa.Column("account_address", sa.String(length=42), nullable=False), + sa.Column("amount", sa.Integer(), nullable=False), + sa.Column("status", sa.Integer(), nullable=False), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_batch_issue_redeem_status"), + "batch_issue_redeem", + ["status"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_batch_issue_redeem_upload_id"), + "batch_issue_redeem", + ["upload_id"], + unique=False, + schema=get_db_schema(), + ) + op.create_table( + "batch_issue_redeem_upload", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("upload_id", sa.String(length=36), nullable=False), + sa.Column("issuer_address", sa.String(length=42), nullable=False), + sa.Column("token_type", sa.String(length=40), nullable=False), + sa.Column("token_address", sa.String(length=42), nullable=False), + sa.Column("category", sa.String(length=20), nullable=False), + sa.Column("processed", sa.Boolean(), nullable=True), + sa.PrimaryKeyConstraint("upload_id"), + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_batch_issue_redeem_upload_issuer_address"), + "batch_issue_redeem_upload", + ["issuer_address"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_batch_issue_redeem_upload_processed"), + "batch_issue_redeem_upload", + ["processed"], + unique=False, + schema=get_db_schema(), + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_index(op.f('ix_batch_issue_redeem_upload_processed'), table_name='batch_issue_redeem_upload', schema=get_db_schema()) - op.drop_index(op.f('ix_batch_issue_redeem_upload_issuer_address'), table_name='batch_issue_redeem_upload', schema=get_db_schema()) - op.drop_table('batch_issue_redeem_upload', schema=get_db_schema()) - op.drop_index(op.f('ix_batch_issue_redeem_upload_id'), table_name='batch_issue_redeem', schema=get_db_schema()) - op.drop_index(op.f('ix_batch_issue_redeem_status'), table_name='batch_issue_redeem', schema=get_db_schema()) - op.drop_table('batch_issue_redeem', schema=get_db_schema()) + op.drop_index( + op.f("ix_batch_issue_redeem_upload_processed"), + table_name="batch_issue_redeem_upload", + schema=get_db_schema(), + ) + op.drop_index( + op.f("ix_batch_issue_redeem_upload_issuer_address"), + table_name="batch_issue_redeem_upload", + schema=get_db_schema(), + ) + op.drop_table("batch_issue_redeem_upload", schema=get_db_schema()) + op.drop_index( + op.f("ix_batch_issue_redeem_upload_id"), + table_name="batch_issue_redeem", + schema=get_db_schema(), + ) + op.drop_index( + op.f("ix_batch_issue_redeem_status"), + table_name="batch_issue_redeem", + schema=get_db_schema(), + ) + op.drop_table("batch_issue_redeem", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/migrations/versions/fe0437ec5e6d_v0_1_0_feature_6.py b/migrations/versions/fe0437ec5e6d_v0_1_0_feature_6.py index b5412c0f..30ebdf7f 100644 --- a/migrations/versions/fe0437ec5e6d_v0_1_0_feature_6.py +++ b/migrations/versions/fe0437ec5e6d_v0_1_0_feature_6.py @@ -5,83 +5,126 @@ Create Date: 2021-03-26 19:19:25.752952 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = 'fe0437ec5e6d' -down_revision = '9ff331ab950b' +revision = "fe0437ec5e6d" +down_revision = "9ff331ab950b" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.create_table('bond_ledger', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), - sa.Column('token_address', sa.String(length=42), nullable=True), - sa.Column('ledger', sa.JSON(), nullable=True), - sa.Column('country_code', sa.String(length=3), nullable=True), - sa.Column('bond_ledger_created', sa.DateTime(), nullable=False), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) - op.create_table('corporate_bond_ledger_template_jpn', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), - sa.Column('token_address', sa.String(length=42), nullable=True), - sa.Column('issuer_address', sa.String(length=42), nullable=True), - sa.Column('bond_name', sa.String(length=200), nullable=False), - sa.Column('bond_description', sa.String(length=1000), nullable=False), - sa.Column('bond_type', sa.String(length=1000), nullable=False), - sa.Column('total_amount', sa.BigInteger(), nullable=False), - sa.Column('face_value', sa.Integer(), nullable=False), - sa.Column('payment_amount', sa.BigInteger(), nullable=True), - sa.Column('payment_date', sa.String(length=8), nullable=True), - sa.Column('payment_status', sa.Boolean(), nullable=False), - sa.Column('hq_name', sa.String(length=200), nullable=False), - sa.Column('hq_address', sa.String(length=200), nullable=False), - sa.Column('hq_office_address', sa.String(length=200), nullable=False), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) - op.create_index(op.f('ix_corporate_bond_ledger_template_jpn_issuer_address'), 'corporate_bond_ledger_template_jpn', ['issuer_address'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_corporate_bond_ledger_template_jpn_token_address'), 'corporate_bond_ledger_template_jpn', ['token_address'], unique=False, schema=get_db_schema()) - op.create_table('utxo', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('transaction_hash', sa.String(length=66), nullable=False), - sa.Column('account_address', sa.String(length=42), nullable=True), - sa.Column('token_address', sa.String(length=42), nullable=True), - sa.Column('amount', sa.Integer(), nullable=True), - sa.Column('block_number', sa.BigInteger(), nullable=True), - sa.Column('block_timestamp', sa.DateTime(), nullable=True), - sa.PrimaryKeyConstraint('transaction_hash') - , schema=get_db_schema()) - op.create_index(op.f('ix_utxo_account_address'), 'utxo', ['account_address'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_utxo_token_address'), 'utxo', ['token_address'], unique=False, schema=get_db_schema()) - op.create_table('utxo_block_number', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.BigInteger(), autoincrement=True, nullable=False), - sa.Column('latest_block_number', sa.BigInteger(), nullable=True), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) + op.create_table( + "bond_ledger", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), + sa.Column("token_address", sa.String(length=42), nullable=True), + sa.Column("ledger", sa.JSON(), nullable=True), + sa.Column("country_code", sa.String(length=3), nullable=True), + sa.Column("bond_ledger_created", sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) + op.create_table( + "corporate_bond_ledger_template_jpn", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), + sa.Column("token_address", sa.String(length=42), nullable=True), + sa.Column("issuer_address", sa.String(length=42), nullable=True), + sa.Column("bond_name", sa.String(length=200), nullable=False), + sa.Column("bond_description", sa.String(length=1000), nullable=False), + sa.Column("bond_type", sa.String(length=1000), nullable=False), + sa.Column("total_amount", sa.BigInteger(), nullable=False), + sa.Column("face_value", sa.Integer(), nullable=False), + sa.Column("payment_amount", sa.BigInteger(), nullable=True), + sa.Column("payment_date", sa.String(length=8), nullable=True), + sa.Column("payment_status", sa.Boolean(), nullable=False), + sa.Column("hq_name", sa.String(length=200), nullable=False), + sa.Column("hq_address", sa.String(length=200), nullable=False), + sa.Column("hq_office_address", sa.String(length=200), nullable=False), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_corporate_bond_ledger_template_jpn_issuer_address"), + "corporate_bond_ledger_template_jpn", + ["issuer_address"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_corporate_bond_ledger_template_jpn_token_address"), + "corporate_bond_ledger_template_jpn", + ["token_address"], + unique=False, + schema=get_db_schema(), + ) + op.create_table( + "utxo", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("transaction_hash", sa.String(length=66), nullable=False), + sa.Column("account_address", sa.String(length=42), nullable=True), + sa.Column("token_address", sa.String(length=42), nullable=True), + sa.Column("amount", sa.Integer(), nullable=True), + sa.Column("block_number", sa.BigInteger(), nullable=True), + sa.Column("block_timestamp", sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint("transaction_hash"), + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_utxo_account_address"), + "utxo", + ["account_address"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_utxo_token_address"), + "utxo", + ["token_address"], + unique=False, + schema=get_db_schema(), + ) + op.create_table( + "utxo_block_number", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False), + sa.Column("latest_block_number", sa.BigInteger(), nullable=True), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_table('utxo_block_number', schema=get_db_schema()) - op.drop_index(op.f('ix_utxo_token_address'), table_name='utxo', schema=get_db_schema()) - op.drop_index(op.f('ix_utxo_account_address'), table_name='utxo', schema=get_db_schema()) - op.drop_table('utxo', schema=get_db_schema()) - op.drop_index(op.f('ix_corporate_bond_ledger_template_jpn_token_address'), table_name='corporate_bond_ledger_template_jpn', schema=get_db_schema()) - op.drop_index(op.f('ix_corporate_bond_ledger_template_jpn_issuer_address'), table_name='corporate_bond_ledger_template_jpn', schema=get_db_schema()) - op.drop_table('corporate_bond_ledger_template_jpn', schema=get_db_schema()) - op.drop_table('bond_ledger', schema=get_db_schema()) + op.drop_table("utxo_block_number", schema=get_db_schema()) + op.drop_index( + op.f("ix_utxo_token_address"), table_name="utxo", schema=get_db_schema() + ) + op.drop_index( + op.f("ix_utxo_account_address"), table_name="utxo", schema=get_db_schema() + ) + op.drop_table("utxo", schema=get_db_schema()) + op.drop_index( + op.f("ix_corporate_bond_ledger_template_jpn_token_address"), + table_name="corporate_bond_ledger_template_jpn", + schema=get_db_schema(), + ) + op.drop_index( + op.f("ix_corporate_bond_ledger_template_jpn_issuer_address"), + table_name="corporate_bond_ledger_template_jpn", + schema=get_db_schema(), + ) + op.drop_table("corporate_bond_ledger_template_jpn", schema=get_db_schema()) + op.drop_table("bond_ledger", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/migrations/versions/ff1cb5a4411c_v0_1_0_feature_69.py b/migrations/versions/ff1cb5a4411c_v0_1_0_feature_69.py index 936dcc05..2735b3da 100644 --- a/migrations/versions/ff1cb5a4411c_v0_1_0_feature_69.py +++ b/migrations/versions/ff1cb5a4411c_v0_1_0_feature_69.py @@ -5,38 +5,59 @@ Create Date: 2021-05-07 14:59:37.921527 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = 'ff1cb5a4411c' -down_revision = 'bb5d903f97f2' +revision = "ff1cb5a4411c" +down_revision = "bb5d903f97f2" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.create_table('transfer_approval_history', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('id', sa.BigInteger(), autoincrement=True, nullable=False), - sa.Column('token_address', sa.String(length=42), nullable=True), - sa.Column('application_id', sa.BigInteger(), nullable=True), - sa.Column('result', sa.Integer(), nullable=True), - sa.PrimaryKeyConstraint('id') - , schema=get_db_schema()) - op.create_index(op.f('ix_transfer_approval_history_application_id'), 'transfer_approval_history', ['application_id'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_transfer_approval_history_token_address'), 'transfer_approval_history', ['token_address'], unique=False, schema=get_db_schema()) + op.create_table( + "transfer_approval_history", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False), + sa.Column("token_address", sa.String(length=42), nullable=True), + sa.Column("application_id", sa.BigInteger(), nullable=True), + sa.Column("result", sa.Integer(), nullable=True), + sa.PrimaryKeyConstraint("id"), + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_transfer_approval_history_application_id"), + "transfer_approval_history", + ["application_id"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_transfer_approval_history_token_address"), + "transfer_approval_history", + ["token_address"], + unique=False, + schema=get_db_schema(), + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_index(op.f('ix_transfer_approval_history_token_address'), table_name='transfer_approval_history', schema=get_db_schema()) - op.drop_index(op.f('ix_transfer_approval_history_application_id'), table_name='transfer_approval_history', schema=get_db_schema()) - op.drop_table('transfer_approval_history', schema=get_db_schema()) + op.drop_index( + op.f("ix_transfer_approval_history_token_address"), + table_name="transfer_approval_history", + schema=get_db_schema(), + ) + op.drop_index( + op.f("ix_transfer_approval_history_application_id"), + table_name="transfer_approval_history", + schema=get_db_schema(), + ) + op.drop_table("transfer_approval_history", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/migrations/versions/ff1d28df9f37_v22_12_0_feature_432.py b/migrations/versions/ff1d28df9f37_v22_12_0_feature_432.py index 838b76e0..2d9e4997 100644 --- a/migrations/versions/ff1d28df9f37_v22_12_0_feature_432.py +++ b/migrations/versions/ff1d28df9f37_v22_12_0_feature_432.py @@ -5,83 +5,128 @@ Create Date: 2022-12-08 21:46:44.906723 """ -from alembic import op import sqlalchemy as sa - +from alembic import op from app.database import get_db_schema # revision identifiers, used by Alembic. -revision = 'ff1d28df9f37' -down_revision = '1dddc4e2d4e6' +revision = "ff1d28df9f37" +down_revision = "1dddc4e2d4e6" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.create_table('block_data', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('number', sa.BigInteger(), autoincrement=False, nullable=False), - sa.Column('parent_hash', sa.String(length=66), nullable=False), - sa.Column('sha3_uncles', sa.String(length=66), nullable=True), - sa.Column('miner', sa.String(length=42), nullable=True), - sa.Column('state_root', sa.String(length=66), nullable=True), - sa.Column('transactions_root', sa.String(length=66), nullable=True), - sa.Column('receipts_root', sa.String(length=66), nullable=True), - sa.Column('logs_bloom', sa.String(length=514), nullable=True), - sa.Column('difficulty', sa.BigInteger(), nullable=True), - sa.Column('gas_limit', sa.Integer(), nullable=True), - sa.Column('gas_used', sa.Integer(), nullable=True), - sa.Column('timestamp', sa.Integer(), nullable=False), - sa.Column('proof_of_authority_data', sa.Text(), nullable=True), - sa.Column('mix_hash', sa.String(length=66), nullable=True), - sa.Column('nonce', sa.String(length=18), nullable=True), - sa.Column('hash', sa.String(length=66), nullable=False), - sa.Column('size', sa.Integer(), nullable=True), - sa.Column('transactions', sa.JSON(), nullable=True), - sa.PrimaryKeyConstraint('number') - , schema=get_db_schema()) - op.create_index(op.f('ix_block_data_hash'), 'block_data', ['hash'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_block_data_timestamp'), 'block_data', ['timestamp'], unique=False, schema=get_db_schema()) - op.create_table('idx_block_data_block_number', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('chain_id', sa.String(length=10), nullable=False), - sa.Column('latest_block_number', sa.BigInteger(), nullable=True), - sa.PrimaryKeyConstraint('chain_id') - , schema=get_db_schema()) - op.create_table('tx_data', - sa.Column('created', sa.DateTime(), nullable=True), - sa.Column('modified', sa.DateTime(), nullable=True), - sa.Column('hash', sa.String(length=66), nullable=False), - sa.Column('block_hash', sa.String(length=66), nullable=True), - sa.Column('block_number', sa.BigInteger(), nullable=True), - sa.Column('transaction_index', sa.Integer(), nullable=True), - sa.Column('from_address', sa.String(length=42), nullable=True), - sa.Column('to_address', sa.String(length=42), nullable=True), - sa.Column('input', sa.Text(), nullable=True), - sa.Column('gas', sa.Integer(), nullable=True), - sa.Column('gas_price', sa.BigInteger(), nullable=True), - sa.Column('value', sa.BigInteger(), nullable=True), - sa.Column('nonce', sa.Integer(), nullable=True), - sa.PrimaryKeyConstraint('hash') - , schema=get_db_schema()) - op.create_index(op.f('ix_tx_data_block_number'), 'tx_data', ['block_number'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_tx_data_from_address'), 'tx_data', ['from_address'], unique=False, schema=get_db_schema()) - op.create_index(op.f('ix_tx_data_to_address'), 'tx_data', ['to_address'], unique=False, schema=get_db_schema()) + op.create_table( + "block_data", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("number", sa.BigInteger(), autoincrement=False, nullable=False), + sa.Column("parent_hash", sa.String(length=66), nullable=False), + sa.Column("sha3_uncles", sa.String(length=66), nullable=True), + sa.Column("miner", sa.String(length=42), nullable=True), + sa.Column("state_root", sa.String(length=66), nullable=True), + sa.Column("transactions_root", sa.String(length=66), nullable=True), + sa.Column("receipts_root", sa.String(length=66), nullable=True), + sa.Column("logs_bloom", sa.String(length=514), nullable=True), + sa.Column("difficulty", sa.BigInteger(), nullable=True), + sa.Column("gas_limit", sa.Integer(), nullable=True), + sa.Column("gas_used", sa.Integer(), nullable=True), + sa.Column("timestamp", sa.Integer(), nullable=False), + sa.Column("proof_of_authority_data", sa.Text(), nullable=True), + sa.Column("mix_hash", sa.String(length=66), nullable=True), + sa.Column("nonce", sa.String(length=18), nullable=True), + sa.Column("hash", sa.String(length=66), nullable=False), + sa.Column("size", sa.Integer(), nullable=True), + sa.Column("transactions", sa.JSON(), nullable=True), + sa.PrimaryKeyConstraint("number"), + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_block_data_hash"), + "block_data", + ["hash"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_block_data_timestamp"), + "block_data", + ["timestamp"], + unique=False, + schema=get_db_schema(), + ) + op.create_table( + "idx_block_data_block_number", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("chain_id", sa.String(length=10), nullable=False), + sa.Column("latest_block_number", sa.BigInteger(), nullable=True), + sa.PrimaryKeyConstraint("chain_id"), + schema=get_db_schema(), + ) + op.create_table( + "tx_data", + sa.Column("created", sa.DateTime(), nullable=True), + sa.Column("modified", sa.DateTime(), nullable=True), + sa.Column("hash", sa.String(length=66), nullable=False), + sa.Column("block_hash", sa.String(length=66), nullable=True), + sa.Column("block_number", sa.BigInteger(), nullable=True), + sa.Column("transaction_index", sa.Integer(), nullable=True), + sa.Column("from_address", sa.String(length=42), nullable=True), + sa.Column("to_address", sa.String(length=42), nullable=True), + sa.Column("input", sa.Text(), nullable=True), + sa.Column("gas", sa.Integer(), nullable=True), + sa.Column("gas_price", sa.BigInteger(), nullable=True), + sa.Column("value", sa.BigInteger(), nullable=True), + sa.Column("nonce", sa.Integer(), nullable=True), + sa.PrimaryKeyConstraint("hash"), + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_tx_data_block_number"), + "tx_data", + ["block_number"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_tx_data_from_address"), + "tx_data", + ["from_address"], + unique=False, + schema=get_db_schema(), + ) + op.create_index( + op.f("ix_tx_data_to_address"), + "tx_data", + ["to_address"], + unique=False, + schema=get_db_schema(), + ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_index(op.f('ix_tx_data_to_address'), table_name='tx_data', schema=get_db_schema()) - op.drop_index(op.f('ix_tx_data_from_address'), table_name='tx_data', schema=get_db_schema()) - op.drop_index(op.f('ix_tx_data_block_number'), table_name='tx_data', schema=get_db_schema()) - op.drop_table('tx_data', schema=get_db_schema()) - op.drop_table('idx_block_data_block_number', schema=get_db_schema()) - op.drop_index(op.f('ix_block_data_timestamp'), table_name='block_data', schema=get_db_schema()) - op.drop_index(op.f('ix_block_data_hash'), table_name='block_data', schema=get_db_schema()) - op.drop_table('block_data', schema=get_db_schema()) + op.drop_index( + op.f("ix_tx_data_to_address"), table_name="tx_data", schema=get_db_schema() + ) + op.drop_index( + op.f("ix_tx_data_from_address"), table_name="tx_data", schema=get_db_schema() + ) + op.drop_index( + op.f("ix_tx_data_block_number"), table_name="tx_data", schema=get_db_schema() + ) + op.drop_table("tx_data", schema=get_db_schema()) + op.drop_table("idx_block_data_block_number", schema=get_db_schema()) + op.drop_index( + op.f("ix_block_data_timestamp"), table_name="block_data", schema=get_db_schema() + ) + op.drop_index( + op.f("ix_block_data_hash"), table_name="block_data", schema=get_db_schema() + ) + op.drop_table("block_data", schema=get_db_schema()) # ### end Alembic commands ### diff --git a/poetry.lock b/poetry.lock index de5b5a70..058e6da0 100644 --- a/poetry.lock +++ b/poetry.lock @@ -330,20 +330,69 @@ files = [ {file = "bitarray-2.7.3.tar.gz", hash = "sha256:f71256a32609b036adad932e1228b66a6b4e2cae6be397e588ddc0babd9a78b9"}, ] +[[package]] +name = "black" +version = "23.1.0" +description = "The uncompromising code formatter." +category = "dev" +optional = false +python-versions = ">=3.7" +files = [ + {file = "black-23.1.0-cp310-cp310-macosx_10_16_arm64.whl", hash = "sha256:b6a92a41ee34b883b359998f0c8e6eb8e99803aa8bf3123bf2b2e6fec505a221"}, + {file = "black-23.1.0-cp310-cp310-macosx_10_16_universal2.whl", hash = "sha256:57c18c5165c1dbe291d5306e53fb3988122890e57bd9b3dcb75f967f13411a26"}, + {file = "black-23.1.0-cp310-cp310-macosx_10_16_x86_64.whl", hash = "sha256:9880d7d419bb7e709b37e28deb5e68a49227713b623c72b2b931028ea65f619b"}, + {file = "black-23.1.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e6663f91b6feca5d06f2ccd49a10f254f9298cc1f7f49c46e498a0771b507104"}, + {file = "black-23.1.0-cp310-cp310-win_amd64.whl", hash = "sha256:9afd3f493666a0cd8f8df9a0200c6359ac53940cbde049dcb1a7eb6ee2dd7074"}, + {file = "black-23.1.0-cp311-cp311-macosx_10_16_arm64.whl", hash = "sha256:bfffba28dc52a58f04492181392ee380e95262af14ee01d4bc7bb1b1c6ca8d27"}, + {file = "black-23.1.0-cp311-cp311-macosx_10_16_universal2.whl", hash = "sha256:c1c476bc7b7d021321e7d93dc2cbd78ce103b84d5a4cf97ed535fbc0d6660648"}, + {file = "black-23.1.0-cp311-cp311-macosx_10_16_x86_64.whl", hash = "sha256:382998821f58e5c8238d3166c492139573325287820963d2f7de4d518bd76958"}, + {file = "black-23.1.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2bf649fda611c8550ca9d7592b69f0637218c2369b7744694c5e4902873b2f3a"}, + {file = "black-23.1.0-cp311-cp311-win_amd64.whl", hash = "sha256:121ca7f10b4a01fd99951234abdbd97728e1240be89fde18480ffac16503d481"}, + {file = "black-23.1.0-cp37-cp37m-macosx_10_16_x86_64.whl", hash = "sha256:a8471939da5e824b891b25751955be52ee7f8a30a916d570a5ba8e0f2eb2ecad"}, + {file = "black-23.1.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8178318cb74f98bc571eef19068f6ab5613b3e59d4f47771582f04e175570ed8"}, + {file = "black-23.1.0-cp37-cp37m-win_amd64.whl", hash = "sha256:a436e7881d33acaf2536c46a454bb964a50eff59b21b51c6ccf5a40601fbef24"}, + {file = "black-23.1.0-cp38-cp38-macosx_10_16_arm64.whl", hash = "sha256:a59db0a2094d2259c554676403fa2fac3473ccf1354c1c63eccf7ae65aac8ab6"}, + {file = "black-23.1.0-cp38-cp38-macosx_10_16_universal2.whl", hash = "sha256:0052dba51dec07ed029ed61b18183942043e00008ec65d5028814afaab9a22fd"}, + {file = "black-23.1.0-cp38-cp38-macosx_10_16_x86_64.whl", hash = "sha256:49f7b39e30f326a34b5c9a4213213a6b221d7ae9d58ec70df1c4a307cf2a1580"}, + {file = "black-23.1.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:162e37d49e93bd6eb6f1afc3e17a3d23a823042530c37c3c42eeeaf026f38468"}, + {file = "black-23.1.0-cp38-cp38-win_amd64.whl", hash = "sha256:8b70eb40a78dfac24842458476135f9b99ab952dd3f2dab738c1881a9b38b753"}, + {file = "black-23.1.0-cp39-cp39-macosx_10_16_arm64.whl", hash = "sha256:a29650759a6a0944e7cca036674655c2f0f63806ddecc45ed40b7b8aa314b651"}, + {file = "black-23.1.0-cp39-cp39-macosx_10_16_universal2.whl", hash = "sha256:bb460c8561c8c1bec7824ecbc3ce085eb50005883a6203dcfb0122e95797ee06"}, + {file = "black-23.1.0-cp39-cp39-macosx_10_16_x86_64.whl", hash = "sha256:c91dfc2c2a4e50df0026f88d2215e166616e0c80e86004d0003ece0488db2739"}, + {file = "black-23.1.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2a951cc83ab535d248c89f300eccbd625e80ab880fbcfb5ac8afb5f01a258ac9"}, + {file = "black-23.1.0-cp39-cp39-win_amd64.whl", hash = "sha256:0680d4380db3719ebcfb2613f34e86c8e6d15ffeabcf8ec59355c5e7b85bb555"}, + {file = "black-23.1.0-py3-none-any.whl", hash = "sha256:7a0f701d314cfa0896b9001df70a530eb2472babb76086344e688829efd97d32"}, + {file = "black-23.1.0.tar.gz", hash = "sha256:b0bd97bea8903f5a2ba7219257a44e3f1f9d00073d6cc1add68f0beec69692ac"}, +] + +[package.dependencies] +click = ">=8.0.0" +mypy-extensions = ">=0.4.3" +packaging = ">=22.0" +pathspec = ">=0.9.0" +platformdirs = ">=2" +tomli = {version = ">=1.1.0", markers = "python_version < \"3.11\""} + +[package.extras] +colorama = ["colorama (>=0.4.3)"] +d = ["aiohttp (>=3.7.4)"] +jupyter = ["ipython (>=7.8.0)", "tokenize-rt (>=3.2.0)"] +uvloop = ["uvloop (>=0.15.2)"] + [[package]] name = "boto3" -version = "1.26.83" +version = "1.26.85" description = "The AWS SDK for Python" category = "main" optional = false python-versions = ">= 3.7" files = [ - {file = "boto3-1.26.83-py3-none-any.whl", hash = "sha256:c07ed643aa72940f92b2c807591e1ba803c1b79d20ca129a6f8cccf846c40ff8"}, - {file = "boto3-1.26.83.tar.gz", hash = "sha256:df81bfa4f8dfb3a645c43b7fd317f48df3e7fa402115ef21fc2f6430d73a1821"}, + {file = "boto3-1.26.85-py3-none-any.whl", hash = "sha256:9afe405c71bfd13fa958637caec9dc91f7009b221a7d87d4b067fa6f262aab67"}, + {file = "boto3-1.26.85.tar.gz", hash = "sha256:ae106bdc5ac6e693100a2dba5ea1c9cfa6e556f6f39944fa8b3af6b104eeccf3"}, ] [package.dependencies] -botocore = ">=1.29.83,<1.30.0" +botocore = ">=1.29.85,<1.30.0" jmespath = ">=0.7.1,<2.0.0" s3transfer = ">=0.6.0,<0.7.0" @@ -352,14 +401,14 @@ crt = ["botocore[crt] (>=1.21.0,<2.0a0)"] [[package]] name = "botocore" -version = "1.29.83" +version = "1.29.85" description = "Low-level, data-driven core of boto 3." category = "main" optional = false python-versions = ">= 3.7" files = [ - {file = "botocore-1.29.83-py3-none-any.whl", hash = "sha256:b7df2a1413f32992f350dd66bc5c8747b7211b776cf6500f64aebba7eddbe4f0"}, - {file = "botocore-1.29.83.tar.gz", hash = "sha256:2e3d215b94df4e4c0ce3da250db43fb39ef7834f8f8fd19e5b223b35edb4d073"}, + {file = "botocore-1.29.85-py3-none-any.whl", hash = "sha256:1f2d1f7e3b41f8c9cc5576be16d86552a46724fd5d15f38a50c002a957ac43ff"}, + {file = "botocore-1.29.85.tar.gz", hash = "sha256:cb7e7e88a09ba807956643849b3a9b4e343a2c117838c0be1ca660052f69bcd2"}, ] [package.dependencies] @@ -459,102 +508,101 @@ files = [ [package.dependencies] pycparser = "*" +[[package]] +name = "cfgv" +version = "3.3.1" +description = "Validate configuration and produce human readable error messages." +category = "dev" +optional = false +python-versions = ">=3.6.1" +files = [ + {file = "cfgv-3.3.1-py2.py3-none-any.whl", hash = "sha256:c6a0883f3917a037485059700b9e75da2464e6c27051014ad85ba6aaa5884426"}, + {file = "cfgv-3.3.1.tar.gz", hash = "sha256:f5a830efb9ce7a445376bb66ec94c638a9787422f96264c98edc6bdeed8ab736"}, +] + [[package]] name = "charset-normalizer" -version = "3.0.1" +version = "3.1.0" description = "The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet." category = "main" optional = false -python-versions = "*" +python-versions = ">=3.7.0" files = [ - {file = "charset-normalizer-3.0.1.tar.gz", hash = "sha256:ebea339af930f8ca5d7a699b921106c6e29c617fe9606fa7baa043c1cdae326f"}, - {file = "charset_normalizer-3.0.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:88600c72ef7587fe1708fd242b385b6ed4b8904976d5da0893e31df8b3480cb6"}, - {file = "charset_normalizer-3.0.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:c75ffc45f25324e68ab238cb4b5c0a38cd1c3d7f1fb1f72b5541de469e2247db"}, - {file = "charset_normalizer-3.0.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:db72b07027db150f468fbada4d85b3b2729a3db39178abf5c543b784c1254539"}, - {file = "charset_normalizer-3.0.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:62595ab75873d50d57323a91dd03e6966eb79c41fa834b7a1661ed043b2d404d"}, - {file = "charset_normalizer-3.0.1-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ff6f3db31555657f3163b15a6b7c6938d08df7adbfc9dd13d9d19edad678f1e8"}, - {file = "charset_normalizer-3.0.1-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:772b87914ff1152b92a197ef4ea40efe27a378606c39446ded52c8f80f79702e"}, - {file = "charset_normalizer-3.0.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:70990b9c51340e4044cfc394a81f614f3f90d41397104d226f21e66de668730d"}, - {file = "charset_normalizer-3.0.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:292d5e8ba896bbfd6334b096e34bffb56161c81408d6d036a7dfa6929cff8783"}, - {file = "charset_normalizer-3.0.1-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:2edb64ee7bf1ed524a1da60cdcd2e1f6e2b4f66ef7c077680739f1641f62f555"}, - {file = "charset_normalizer-3.0.1-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:31a9ddf4718d10ae04d9b18801bd776693487cbb57d74cc3458a7673f6f34639"}, - {file = "charset_normalizer-3.0.1-cp310-cp310-musllinux_1_1_ppc64le.whl", hash = "sha256:44ba614de5361b3e5278e1241fda3dc1838deed864b50a10d7ce92983797fa76"}, - {file = "charset_normalizer-3.0.1-cp310-cp310-musllinux_1_1_s390x.whl", hash = "sha256:12db3b2c533c23ab812c2b25934f60383361f8a376ae272665f8e48b88e8e1c6"}, - {file = "charset_normalizer-3.0.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:c512accbd6ff0270939b9ac214b84fb5ada5f0409c44298361b2f5e13f9aed9e"}, - {file = "charset_normalizer-3.0.1-cp310-cp310-win32.whl", hash = "sha256:502218f52498a36d6bf5ea77081844017bf7982cdbe521ad85e64cabee1b608b"}, - {file = "charset_normalizer-3.0.1-cp310-cp310-win_amd64.whl", hash = "sha256:601f36512f9e28f029d9481bdaf8e89e5148ac5d89cffd3b05cd533eeb423b59"}, - {file = "charset_normalizer-3.0.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:0298eafff88c99982a4cf66ba2efa1128e4ddaca0b05eec4c456bbc7db691d8d"}, - {file = "charset_normalizer-3.0.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:a8d0fc946c784ff7f7c3742310cc8a57c5c6dc31631269876a88b809dbeff3d3"}, - {file = "charset_normalizer-3.0.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:87701167f2a5c930b403e9756fab1d31d4d4da52856143b609e30a1ce7160f3c"}, - {file = "charset_normalizer-3.0.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:14e76c0f23218b8f46c4d87018ca2e441535aed3632ca134b10239dfb6dadd6b"}, - {file = "charset_normalizer-3.0.1-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:0c0a590235ccd933d9892c627dec5bc7511ce6ad6c1011fdf5b11363022746c1"}, - {file = "charset_normalizer-3.0.1-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8c7fe7afa480e3e82eed58e0ca89f751cd14d767638e2550c77a92a9e749c317"}, - {file = "charset_normalizer-3.0.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:79909e27e8e4fcc9db4addea88aa63f6423ebb171db091fb4373e3312cb6d603"}, - {file = "charset_normalizer-3.0.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:8ac7b6a045b814cf0c47f3623d21ebd88b3e8cf216a14790b455ea7ff0135d18"}, - {file = "charset_normalizer-3.0.1-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:72966d1b297c741541ca8cf1223ff262a6febe52481af742036a0b296e35fa5a"}, - {file = "charset_normalizer-3.0.1-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:f9d0c5c045a3ca9bedfc35dca8526798eb91a07aa7a2c0fee134c6c6f321cbd7"}, - {file = "charset_normalizer-3.0.1-cp311-cp311-musllinux_1_1_ppc64le.whl", hash = "sha256:5995f0164fa7df59db4746112fec3f49c461dd6b31b841873443bdb077c13cfc"}, - {file = "charset_normalizer-3.0.1-cp311-cp311-musllinux_1_1_s390x.whl", hash = "sha256:4a8fcf28c05c1f6d7e177a9a46a1c52798bfe2ad80681d275b10dcf317deaf0b"}, - {file = "charset_normalizer-3.0.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:761e8904c07ad053d285670f36dd94e1b6ab7f16ce62b9805c475b7aa1cffde6"}, - {file = "charset_normalizer-3.0.1-cp311-cp311-win32.whl", hash = "sha256:71140351489970dfe5e60fc621ada3e0f41104a5eddaca47a7acb3c1b851d6d3"}, - {file = "charset_normalizer-3.0.1-cp311-cp311-win_amd64.whl", hash = "sha256:9ab77acb98eba3fd2a85cd160851816bfce6871d944d885febf012713f06659c"}, - {file = "charset_normalizer-3.0.1-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:84c3990934bae40ea69a82034912ffe5a62c60bbf6ec5bc9691419641d7d5c9a"}, - {file = "charset_normalizer-3.0.1-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:74292fc76c905c0ef095fe11e188a32ebd03bc38f3f3e9bcb85e4e6db177b7ea"}, - {file = "charset_normalizer-3.0.1-cp36-cp36m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c95a03c79bbe30eec3ec2b7f076074f4281526724c8685a42872974ef4d36b72"}, - {file = "charset_normalizer-3.0.1-cp36-cp36m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f4c39b0e3eac288fedc2b43055cfc2ca7a60362d0e5e87a637beac5d801ef478"}, - {file = "charset_normalizer-3.0.1-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:df2c707231459e8a4028eabcd3cfc827befd635b3ef72eada84ab13b52e1574d"}, - {file = "charset_normalizer-3.0.1-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:93ad6d87ac18e2a90b0fe89df7c65263b9a99a0eb98f0a3d2e079f12a0735837"}, - {file = "charset_normalizer-3.0.1-cp36-cp36m-musllinux_1_1_aarch64.whl", hash = "sha256:59e5686dd847347e55dffcc191a96622f016bc0ad89105e24c14e0d6305acbc6"}, - {file = "charset_normalizer-3.0.1-cp36-cp36m-musllinux_1_1_i686.whl", hash = "sha256:cd6056167405314a4dc3c173943f11249fa0f1b204f8b51ed4bde1a9cd1834dc"}, - {file = "charset_normalizer-3.0.1-cp36-cp36m-musllinux_1_1_ppc64le.whl", hash = "sha256:083c8d17153ecb403e5e1eb76a7ef4babfc2c48d58899c98fcaa04833e7a2f9a"}, - {file = "charset_normalizer-3.0.1-cp36-cp36m-musllinux_1_1_s390x.whl", hash = "sha256:f5057856d21e7586765171eac8b9fc3f7d44ef39425f85dbcccb13b3ebea806c"}, - {file = "charset_normalizer-3.0.1-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:7eb33a30d75562222b64f569c642ff3dc6689e09adda43a082208397f016c39a"}, - {file = "charset_normalizer-3.0.1-cp36-cp36m-win32.whl", hash = "sha256:95dea361dd73757c6f1c0a1480ac499952c16ac83f7f5f4f84f0658a01b8ef41"}, - {file = "charset_normalizer-3.0.1-cp36-cp36m-win_amd64.whl", hash = "sha256:eaa379fcd227ca235d04152ca6704c7cb55564116f8bc52545ff357628e10602"}, - {file = "charset_normalizer-3.0.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:3e45867f1f2ab0711d60c6c71746ac53537f1684baa699f4f668d4c6f6ce8e14"}, - {file = "charset_normalizer-3.0.1-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cadaeaba78750d58d3cc6ac4d1fd867da6fc73c88156b7a3212a3cd4819d679d"}, - {file = "charset_normalizer-3.0.1-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:911d8a40b2bef5b8bbae2e36a0b103f142ac53557ab421dc16ac4aafee6f53dc"}, - {file = "charset_normalizer-3.0.1-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:503e65837c71b875ecdd733877d852adbc465bd82c768a067badd953bf1bc5a3"}, - {file = "charset_normalizer-3.0.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a60332922359f920193b1d4826953c507a877b523b2395ad7bc716ddd386d866"}, - {file = "charset_normalizer-3.0.1-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:16a8663d6e281208d78806dbe14ee9903715361cf81f6d4309944e4d1e59ac5b"}, - {file = "charset_normalizer-3.0.1-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:a16418ecf1329f71df119e8a65f3aa68004a3f9383821edcb20f0702934d8087"}, - {file = "charset_normalizer-3.0.1-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:9d9153257a3f70d5f69edf2325357251ed20f772b12e593f3b3377b5f78e7ef8"}, - {file = "charset_normalizer-3.0.1-cp37-cp37m-musllinux_1_1_ppc64le.whl", hash = "sha256:02a51034802cbf38db3f89c66fb5d2ec57e6fe7ef2f4a44d070a593c3688667b"}, - {file = "charset_normalizer-3.0.1-cp37-cp37m-musllinux_1_1_s390x.whl", hash = "sha256:2e396d70bc4ef5325b72b593a72c8979999aa52fb8bcf03f701c1b03e1166918"}, - {file = "charset_normalizer-3.0.1-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:11b53acf2411c3b09e6af37e4b9005cba376c872503c8f28218c7243582df45d"}, - {file = "charset_normalizer-3.0.1-cp37-cp37m-win32.whl", hash = "sha256:0bf2dae5291758b6f84cf923bfaa285632816007db0330002fa1de38bfcb7154"}, - {file = "charset_normalizer-3.0.1-cp37-cp37m-win_amd64.whl", hash = "sha256:2c03cc56021a4bd59be889c2b9257dae13bf55041a3372d3295416f86b295fb5"}, - {file = "charset_normalizer-3.0.1-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:024e606be3ed92216e2b6952ed859d86b4cfa52cd5bc5f050e7dc28f9b43ec42"}, - {file = "charset_normalizer-3.0.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:4b0d02d7102dd0f997580b51edc4cebcf2ab6397a7edf89f1c73b586c614272c"}, - {file = "charset_normalizer-3.0.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:358a7c4cb8ba9b46c453b1dd8d9e431452d5249072e4f56cfda3149f6ab1405e"}, - {file = "charset_normalizer-3.0.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:81d6741ab457d14fdedc215516665050f3822d3e56508921cc7239f8c8e66a58"}, - {file = "charset_normalizer-3.0.1-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8b8af03d2e37866d023ad0ddea594edefc31e827fee64f8de5611a1dbc373174"}, - {file = "charset_normalizer-3.0.1-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9cf4e8ad252f7c38dd1f676b46514f92dc0ebeb0db5552f5f403509705e24753"}, - {file = "charset_normalizer-3.0.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e696f0dd336161fca9adbb846875d40752e6eba585843c768935ba5c9960722b"}, - {file = "charset_normalizer-3.0.1-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c22d3fe05ce11d3671297dc8973267daa0f938b93ec716e12e0f6dee81591dc1"}, - {file = "charset_normalizer-3.0.1-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:109487860ef6a328f3eec66f2bf78b0b72400280d8f8ea05f69c51644ba6521a"}, - {file = "charset_normalizer-3.0.1-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:37f8febc8ec50c14f3ec9637505f28e58d4f66752207ea177c1d67df25da5aed"}, - {file = "charset_normalizer-3.0.1-cp38-cp38-musllinux_1_1_ppc64le.whl", hash = "sha256:f97e83fa6c25693c7a35de154681fcc257c1c41b38beb0304b9c4d2d9e164479"}, - {file = "charset_normalizer-3.0.1-cp38-cp38-musllinux_1_1_s390x.whl", hash = "sha256:a152f5f33d64a6be73f1d30c9cc82dfc73cec6477ec268e7c6e4c7d23c2d2291"}, - {file = "charset_normalizer-3.0.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:39049da0ffb96c8cbb65cbf5c5f3ca3168990adf3551bd1dee10c48fce8ae820"}, - {file = "charset_normalizer-3.0.1-cp38-cp38-win32.whl", hash = "sha256:4457ea6774b5611f4bed5eaa5df55f70abde42364d498c5134b7ef4c6958e20e"}, - {file = "charset_normalizer-3.0.1-cp38-cp38-win_amd64.whl", hash = "sha256:e62164b50f84e20601c1ff8eb55620d2ad25fb81b59e3cd776a1902527a788af"}, - {file = "charset_normalizer-3.0.1-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:8eade758719add78ec36dc13201483f8e9b5d940329285edcd5f70c0a9edbd7f"}, - {file = "charset_normalizer-3.0.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:8499ca8f4502af841f68135133d8258f7b32a53a1d594aa98cc52013fff55678"}, - {file = "charset_normalizer-3.0.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:3fc1c4a2ffd64890aebdb3f97e1278b0cc72579a08ca4de8cd2c04799a3a22be"}, - {file = "charset_normalizer-3.0.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:00d3ffdaafe92a5dc603cb9bd5111aaa36dfa187c8285c543be562e61b755f6b"}, - {file = "charset_normalizer-3.0.1-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c2ac1b08635a8cd4e0cbeaf6f5e922085908d48eb05d44c5ae9eabab148512ca"}, - {file = "charset_normalizer-3.0.1-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f6f45710b4459401609ebebdbcfb34515da4fc2aa886f95107f556ac69a9147e"}, - {file = "charset_normalizer-3.0.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3ae1de54a77dc0d6d5fcf623290af4266412a7c4be0b1ff7444394f03f5c54e3"}, - {file = "charset_normalizer-3.0.1-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:3b590df687e3c5ee0deef9fc8c547d81986d9a1b56073d82de008744452d6541"}, - {file = "charset_normalizer-3.0.1-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:ab5de034a886f616a5668aa5d098af2b5385ed70142090e2a31bcbd0af0fdb3d"}, - {file = "charset_normalizer-3.0.1-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:9cb3032517f1627cc012dbc80a8ec976ae76d93ea2b5feaa9d2a5b8882597579"}, - {file = "charset_normalizer-3.0.1-cp39-cp39-musllinux_1_1_ppc64le.whl", hash = "sha256:608862a7bf6957f2333fc54ab4399e405baad0163dc9f8d99cb236816db169d4"}, - {file = "charset_normalizer-3.0.1-cp39-cp39-musllinux_1_1_s390x.whl", hash = "sha256:0f438ae3532723fb6ead77e7c604be7c8374094ef4ee2c5e03a3a17f1fca256c"}, - {file = "charset_normalizer-3.0.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:356541bf4381fa35856dafa6a965916e54bed415ad8a24ee6de6e37deccf2786"}, - {file = "charset_normalizer-3.0.1-cp39-cp39-win32.whl", hash = "sha256:39cf9ed17fe3b1bc81f33c9ceb6ce67683ee7526e65fde1447c772afc54a1bb8"}, - {file = "charset_normalizer-3.0.1-cp39-cp39-win_amd64.whl", hash = "sha256:0a11e971ed097d24c534c037d298ad32c6ce81a45736d31e0ff0ad37ab437d59"}, - {file = "charset_normalizer-3.0.1-py3-none-any.whl", hash = "sha256:7e189e2e1d3ed2f4aebabd2d5b0f931e883676e51c7624826e0a4e5fe8a0bf24"}, + {file = "charset-normalizer-3.1.0.tar.gz", hash = "sha256:34e0a2f9c370eb95597aae63bf85eb5e96826d81e3dcf88b8886012906f509b5"}, + {file = "charset_normalizer-3.1.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:e0ac8959c929593fee38da1c2b64ee9778733cdf03c482c9ff1d508b6b593b2b"}, + {file = "charset_normalizer-3.1.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:d7fc3fca01da18fbabe4625d64bb612b533533ed10045a2ac3dd194bfa656b60"}, + {file = "charset_normalizer-3.1.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:04eefcee095f58eaabe6dc3cc2262f3bcd776d2c67005880894f447b3f2cb9c1"}, + {file = "charset_normalizer-3.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:20064ead0717cf9a73a6d1e779b23d149b53daf971169289ed2ed43a71e8d3b0"}, + {file = "charset_normalizer-3.1.0-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1435ae15108b1cb6fffbcea2af3d468683b7afed0169ad718451f8db5d1aff6f"}, + {file = "charset_normalizer-3.1.0-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:c84132a54c750fda57729d1e2599bb598f5fa0344085dbde5003ba429a4798c0"}, + {file = "charset_normalizer-3.1.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:75f2568b4189dda1c567339b48cba4ac7384accb9c2a7ed655cd86b04055c795"}, + {file = "charset_normalizer-3.1.0-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:11d3bcb7be35e7b1bba2c23beedac81ee893ac9871d0ba79effc7fc01167db6c"}, + {file = "charset_normalizer-3.1.0-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:891cf9b48776b5c61c700b55a598621fdb7b1e301a550365571e9624f270c203"}, + {file = "charset_normalizer-3.1.0-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:5f008525e02908b20e04707a4f704cd286d94718f48bb33edddc7d7b584dddc1"}, + {file = "charset_normalizer-3.1.0-cp310-cp310-musllinux_1_1_ppc64le.whl", hash = "sha256:b06f0d3bf045158d2fb8837c5785fe9ff9b8c93358be64461a1089f5da983137"}, + {file = "charset_normalizer-3.1.0-cp310-cp310-musllinux_1_1_s390x.whl", hash = "sha256:49919f8400b5e49e961f320c735388ee686a62327e773fa5b3ce6721f7e785ce"}, + {file = "charset_normalizer-3.1.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:22908891a380d50738e1f978667536f6c6b526a2064156203d418f4856d6e86a"}, + {file = "charset_normalizer-3.1.0-cp310-cp310-win32.whl", hash = "sha256:12d1a39aa6b8c6f6248bb54550efcc1c38ce0d8096a146638fd4738e42284448"}, + {file = "charset_normalizer-3.1.0-cp310-cp310-win_amd64.whl", hash = "sha256:65ed923f84a6844de5fd29726b888e58c62820e0769b76565480e1fdc3d062f8"}, + {file = "charset_normalizer-3.1.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:9a3267620866c9d17b959a84dd0bd2d45719b817245e49371ead79ed4f710d19"}, + {file = "charset_normalizer-3.1.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:6734e606355834f13445b6adc38b53c0fd45f1a56a9ba06c2058f86893ae8017"}, + {file = "charset_normalizer-3.1.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:f8303414c7b03f794347ad062c0516cee0e15f7a612abd0ce1e25caf6ceb47df"}, + {file = "charset_normalizer-3.1.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:aaf53a6cebad0eae578f062c7d462155eada9c172bd8c4d250b8c1d8eb7f916a"}, + {file = "charset_normalizer-3.1.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3dc5b6a8ecfdc5748a7e429782598e4f17ef378e3e272eeb1340ea57c9109f41"}, + {file = "charset_normalizer-3.1.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e1b25e3ad6c909f398df8921780d6a3d120d8c09466720226fc621605b6f92b1"}, + {file = "charset_normalizer-3.1.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0ca564606d2caafb0abe6d1b5311c2649e8071eb241b2d64e75a0d0065107e62"}, + {file = "charset_normalizer-3.1.0-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b82fab78e0b1329e183a65260581de4375f619167478dddab510c6c6fb04d9b6"}, + {file = "charset_normalizer-3.1.0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:bd7163182133c0c7701b25e604cf1611c0d87712e56e88e7ee5d72deab3e76b5"}, + {file = "charset_normalizer-3.1.0-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:11d117e6c63e8f495412d37e7dc2e2fff09c34b2d09dbe2bee3c6229577818be"}, + {file = "charset_normalizer-3.1.0-cp311-cp311-musllinux_1_1_ppc64le.whl", hash = "sha256:cf6511efa4801b9b38dc5546d7547d5b5c6ef4b081c60b23e4d941d0eba9cbeb"}, + {file = "charset_normalizer-3.1.0-cp311-cp311-musllinux_1_1_s390x.whl", hash = "sha256:abc1185d79f47c0a7aaf7e2412a0eb2c03b724581139193d2d82b3ad8cbb00ac"}, + {file = "charset_normalizer-3.1.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:cb7b2ab0188829593b9de646545175547a70d9a6e2b63bf2cd87a0a391599324"}, + {file = "charset_normalizer-3.1.0-cp311-cp311-win32.whl", hash = "sha256:c36bcbc0d5174a80d6cccf43a0ecaca44e81d25be4b7f90f0ed7bcfbb5a00909"}, + {file = "charset_normalizer-3.1.0-cp311-cp311-win_amd64.whl", hash = "sha256:cca4def576f47a09a943666b8f829606bcb17e2bc2d5911a46c8f8da45f56755"}, + {file = "charset_normalizer-3.1.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:0c95f12b74681e9ae127728f7e5409cbbef9cd914d5896ef238cc779b8152373"}, + {file = "charset_normalizer-3.1.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:fca62a8301b605b954ad2e9c3666f9d97f63872aa4efcae5492baca2056b74ab"}, + {file = "charset_normalizer-3.1.0-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ac0aa6cd53ab9a31d397f8303f92c42f534693528fafbdb997c82bae6e477ad9"}, + {file = "charset_normalizer-3.1.0-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:c3af8e0f07399d3176b179f2e2634c3ce9c1301379a6b8c9c9aeecd481da494f"}, + {file = "charset_normalizer-3.1.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3a5fc78f9e3f501a1614a98f7c54d3969f3ad9bba8ba3d9b438c3bc5d047dd28"}, + {file = "charset_normalizer-3.1.0-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:628c985afb2c7d27a4800bfb609e03985aaecb42f955049957814e0491d4006d"}, + {file = "charset_normalizer-3.1.0-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:74db0052d985cf37fa111828d0dd230776ac99c740e1a758ad99094be4f1803d"}, + {file = "charset_normalizer-3.1.0-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:1e8fcdd8f672a1c4fc8d0bd3a2b576b152d2a349782d1eb0f6b8e52e9954731d"}, + {file = "charset_normalizer-3.1.0-cp37-cp37m-musllinux_1_1_ppc64le.whl", hash = "sha256:04afa6387e2b282cf78ff3dbce20f0cc071c12dc8f685bd40960cc68644cfea6"}, + {file = "charset_normalizer-3.1.0-cp37-cp37m-musllinux_1_1_s390x.whl", hash = "sha256:dd5653e67b149503c68c4018bf07e42eeed6b4e956b24c00ccdf93ac79cdff84"}, + {file = "charset_normalizer-3.1.0-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:d2686f91611f9e17f4548dbf050e75b079bbc2a82be565832bc8ea9047b61c8c"}, + {file = "charset_normalizer-3.1.0-cp37-cp37m-win32.whl", hash = "sha256:4155b51ae05ed47199dc5b2a4e62abccb274cee6b01da5b895099b61b1982974"}, + {file = "charset_normalizer-3.1.0-cp37-cp37m-win_amd64.whl", hash = "sha256:322102cdf1ab682ecc7d9b1c5eed4ec59657a65e1c146a0da342b78f4112db23"}, + {file = "charset_normalizer-3.1.0-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:e633940f28c1e913615fd624fcdd72fdba807bf53ea6925d6a588e84e1151531"}, + {file = "charset_normalizer-3.1.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:3a06f32c9634a8705f4ca9946d667609f52cf130d5548881401f1eb2c39b1e2c"}, + {file = "charset_normalizer-3.1.0-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:7381c66e0561c5757ffe616af869b916c8b4e42b367ab29fedc98481d1e74e14"}, + {file = "charset_normalizer-3.1.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3573d376454d956553c356df45bb824262c397c6e26ce43e8203c4c540ee0acb"}, + {file = "charset_normalizer-3.1.0-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e89df2958e5159b811af9ff0f92614dabf4ff617c03a4c1c6ff53bf1c399e0e1"}, + {file = "charset_normalizer-3.1.0-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:78cacd03e79d009d95635e7d6ff12c21eb89b894c354bd2b2ed0b4763373693b"}, + {file = "charset_normalizer-3.1.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:de5695a6f1d8340b12a5d6d4484290ee74d61e467c39ff03b39e30df62cf83a0"}, + {file = "charset_normalizer-3.1.0-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1c60b9c202d00052183c9be85e5eaf18a4ada0a47d188a83c8f5c5b23252f649"}, + {file = "charset_normalizer-3.1.0-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:f645caaf0008bacf349875a974220f1f1da349c5dbe7c4ec93048cdc785a3326"}, + {file = "charset_normalizer-3.1.0-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:ea9f9c6034ea2d93d9147818f17c2a0860d41b71c38b9ce4d55f21b6f9165a11"}, + {file = "charset_normalizer-3.1.0-cp38-cp38-musllinux_1_1_ppc64le.whl", hash = "sha256:80d1543d58bd3d6c271b66abf454d437a438dff01c3e62fdbcd68f2a11310d4b"}, + {file = "charset_normalizer-3.1.0-cp38-cp38-musllinux_1_1_s390x.whl", hash = "sha256:73dc03a6a7e30b7edc5b01b601e53e7fc924b04e1835e8e407c12c037e81adbd"}, + {file = "charset_normalizer-3.1.0-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:6f5c2e7bc8a4bf7c426599765b1bd33217ec84023033672c1e9a8b35eaeaaaf8"}, + {file = "charset_normalizer-3.1.0-cp38-cp38-win32.whl", hash = "sha256:12a2b561af122e3d94cdb97fe6fb2bb2b82cef0cdca131646fdb940a1eda04f0"}, + {file = "charset_normalizer-3.1.0-cp38-cp38-win_amd64.whl", hash = "sha256:3160a0fd9754aab7d47f95a6b63ab355388d890163eb03b2d2b87ab0a30cfa59"}, + {file = "charset_normalizer-3.1.0-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:38e812a197bf8e71a59fe55b757a84c1f946d0ac114acafaafaf21667a7e169e"}, + {file = "charset_normalizer-3.1.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:6baf0baf0d5d265fa7944feb9f7451cc316bfe30e8df1a61b1bb08577c554f31"}, + {file = "charset_normalizer-3.1.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:8f25e17ab3039b05f762b0a55ae0b3632b2e073d9c8fc88e89aca31a6198e88f"}, + {file = "charset_normalizer-3.1.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3747443b6a904001473370d7810aa19c3a180ccd52a7157aacc264a5ac79265e"}, + {file = "charset_normalizer-3.1.0-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:b116502087ce8a6b7a5f1814568ccbd0e9f6cfd99948aa59b0e241dc57cf739f"}, + {file = "charset_normalizer-3.1.0-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:d16fd5252f883eb074ca55cb622bc0bee49b979ae4e8639fff6ca3ff44f9f854"}, + {file = "charset_normalizer-3.1.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:21fa558996782fc226b529fdd2ed7866c2c6ec91cee82735c98a197fae39f706"}, + {file = "charset_normalizer-3.1.0-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6f6c7a8a57e9405cad7485f4c9d3172ae486cfef1344b5ddd8e5239582d7355e"}, + {file = "charset_normalizer-3.1.0-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:ac3775e3311661d4adace3697a52ac0bab17edd166087d493b52d4f4f553f9f0"}, + {file = "charset_normalizer-3.1.0-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:10c93628d7497c81686e8e5e557aafa78f230cd9e77dd0c40032ef90c18f2230"}, + {file = "charset_normalizer-3.1.0-cp39-cp39-musllinux_1_1_ppc64le.whl", hash = "sha256:6f4f4668e1831850ebcc2fd0b1cd11721947b6dc7c00bf1c6bd3c929ae14f2c7"}, + {file = "charset_normalizer-3.1.0-cp39-cp39-musllinux_1_1_s390x.whl", hash = "sha256:0be65ccf618c1e7ac9b849c315cc2e8a8751d9cfdaa43027d4f6624bd587ab7e"}, + {file = "charset_normalizer-3.1.0-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:53d0a3fa5f8af98a1e261de6a3943ca631c526635eb5817a87a59d9a57ebf48f"}, + {file = "charset_normalizer-3.1.0-cp39-cp39-win32.whl", hash = "sha256:a04f86f41a8916fe45ac5024ec477f41f886b3c435da2d4e3d2709b22ab02af1"}, + {file = "charset_normalizer-3.1.0-cp39-cp39-win_amd64.whl", hash = "sha256:830d2948a5ec37c386d3170c483063798d7879037492540f10a475e3fd6f244b"}, + {file = "charset_normalizer-3.1.0-py3-none-any.whl", hash = "sha256:3d9098b479e78c85080c98e1e35ff40b4a31d8953102bb0fd7d1b6f8a2111a3d"}, ] [[package]] @@ -821,6 +869,18 @@ toolz = ">=0.8.0" [package.extras] cython = ["cython"] +[[package]] +name = "distlib" +version = "0.3.6" +description = "Distribution utilities" +category = "dev" +optional = false +python-versions = "*" +files = [ + {file = "distlib-0.3.6-py2.py3-none-any.whl", hash = "sha256:f35c4b692542ca110de7ef0bea44d73981caeb34ca0b9b6b2e6d7790dda8f80e"}, + {file = "distlib-0.3.6.tar.gz", hash = "sha256:14bad2d9b04d3a36127ac97f30b12a19268f211063d8f8ee4f47108896e11b46"}, +] + [[package]] name = "eth-abi" version = "2.2.0" @@ -1039,6 +1099,22 @@ dev = ["pre-commit (>=2.17.0,<3.0.0)", "ruff (==0.0.138)", "uvicorn[standard] (> doc = ["mdx-include (>=1.4.1,<2.0.0)", "mkdocs (>=1.1.2,<2.0.0)", "mkdocs-markdownextradata-plugin (>=0.1.7,<0.3.0)", "mkdocs-material (>=8.1.4,<9.0.0)", "pyyaml (>=5.3.1,<7.0.0)", "typer[all] (>=0.6.1,<0.8.0)"] test = ["anyio[trio] (>=3.2.1,<4.0.0)", "black (==22.10.0)", "coverage[toml] (>=6.5.0,<8.0)", "databases[sqlite] (>=0.3.2,<0.7.0)", "email-validator (>=1.1.1,<2.0.0)", "flask (>=1.1.2,<3.0.0)", "httpx (>=0.23.0,<0.24.0)", "isort (>=5.0.6,<6.0.0)", "mypy (==0.982)", "orjson (>=3.2.1,<4.0.0)", "passlib[bcrypt] (>=1.7.2,<2.0.0)", "peewee (>=3.13.3,<4.0.0)", "pytest (>=7.1.3,<8.0.0)", "python-jose[cryptography] (>=3.3.0,<4.0.0)", "python-multipart (>=0.0.5,<0.0.6)", "pyyaml (>=5.3.1,<7.0.0)", "ruff (==0.0.138)", "sqlalchemy (>=1.3.18,<1.4.43)", "types-orjson (==3.6.2)", "types-ujson (==5.6.0.0)", "ujson (>=4.0.1,!=4.0.2,!=4.1.0,!=4.2.0,!=4.3.0,!=5.0.0,!=5.1.0,<6.0.0)"] +[[package]] +name = "filelock" +version = "3.9.0" +description = "A platform independent file lock." +category = "dev" +optional = false +python-versions = ">=3.7" +files = [ + {file = "filelock-3.9.0-py3-none-any.whl", hash = "sha256:f58d535af89bb9ad5cd4df046f741f8553a418c01a7856bf0d173bbc9f6bd16d"}, + {file = "filelock-3.9.0.tar.gz", hash = "sha256:7b319f24340b51f55a2bf7a12ac0755a9b03e718311dac567a0f4f7fabd2f5de"}, +] + +[package.extras] +docs = ["furo (>=2022.12.7)", "sphinx (>=5.3)", "sphinx-autodoc-typehints (>=1.19.5)"] +testing = ["covdefaults (>=2.2.2)", "coverage (>=7.0.1)", "pytest (>=7.2)", "pytest-cov (>=4)", "pytest-timeout (>=2.1)"] + [[package]] name = "freezegun" version = "1.2.2" @@ -1323,6 +1399,21 @@ develop = true type = "directory" url = "cmd/explorer" +[[package]] +name = "identify" +version = "2.5.18" +description = "File identification library for Python" +category = "dev" +optional = false +python-versions = ">=3.7" +files = [ + {file = "identify-2.5.18-py2.py3-none-any.whl", hash = "sha256:93aac7ecf2f6abf879b8f29a8002d3c6de7086b8c28d88e1ad15045a15ab63f9"}, + {file = "identify-2.5.18.tar.gz", hash = "sha256:89e144fa560cc4cffb6ef2ab5e9fb18ed9f9b3cb054384bab4b95c12f6c309fe"}, +] + +[package.extras] +license = ["ukkonen"] + [[package]] name = "idna" version = "3.4" @@ -1383,6 +1474,24 @@ files = [ multiaddr = ">=0.0.7" requests = ">=2.11" +[[package]] +name = "isort" +version = "5.12.0" +description = "A Python utility / library to sort Python imports." +category = "dev" +optional = false +python-versions = ">=3.8.0" +files = [ + {file = "isort-5.12.0-py3-none-any.whl", hash = "sha256:f84c2818376e66cf843d497486ea8fed8700b340f308f076c6fb1229dff318b6"}, + {file = "isort-5.12.0.tar.gz", hash = "sha256:8bef7dde241278824a6d83f44a544709b065191b95b6e50894bdc722fcba0504"}, +] + +[package.extras] +colors = ["colorama (>=0.4.3)"] +pipfile-deprecated-finder = ["pip-shims (>=0.5.2)", "pipreqs", "requirementslib"] +plugins = ["setuptools"] +requirements-deprecated-finder = ["pip-api", "pipreqs"] + [[package]] name = "jmespath" version = "1.0.1" @@ -1695,6 +1804,18 @@ files = [ {file = "multidict-6.0.4.tar.gz", hash = "sha256:3666906492efb76453c0e7b97f2cf459b0682e7402c0489a95484965dbc1da49"}, ] +[[package]] +name = "mypy-extensions" +version = "1.0.0" +description = "Type system extensions for programs checked with the mypy type checker." +category = "dev" +optional = false +python-versions = ">=3.5" +files = [ + {file = "mypy_extensions-1.0.0-py3-none-any.whl", hash = "sha256:4392f6c0eb8a5668a69e23d168ffa70f0be9ccfd32b5cc2d26a34ae5b844552d"}, + {file = "mypy_extensions-1.0.0.tar.gz", hash = "sha256:75dbf8955dc00442a438fc4d0666508a9a97b6bd41aa2f0ffe9d2f2725af0782"}, +] + [[package]] name = "nanoid" version = "2.0.0" @@ -1719,6 +1840,21 @@ files = [ {file = "netaddr-0.8.0.tar.gz", hash = "sha256:d6cc57c7a07b1d9d2e917aa8b36ae8ce61c35ba3fcd1b83ca31c5a0ee2b5a243"}, ] +[[package]] +name = "nodeenv" +version = "1.7.0" +description = "Node.js virtual environment builder" +category = "dev" +optional = false +python-versions = ">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*" +files = [ + {file = "nodeenv-1.7.0-py2.py3-none-any.whl", hash = "sha256:27083a7b96a25f2f5e1d8cb4b6317ee8aeda3bdd121394e5ac54e498028a042e"}, + {file = "nodeenv-1.7.0.tar.gz", hash = "sha256:e0e7f7dfb85fc5394c6fe1e8fa98131a2473e04311a45afb6508f7cf1836fa2b"}, +] + +[package.dependencies] +setuptools = "*" + [[package]] name = "orjson" version = "3.8.7" @@ -1799,6 +1935,34 @@ files = [ [package.dependencies] six = ">=1.9.0" +[[package]] +name = "pathspec" +version = "0.11.0" +description = "Utility library for gitignore style pattern matching of file paths." +category = "dev" +optional = false +python-versions = ">=3.7" +files = [ + {file = "pathspec-0.11.0-py3-none-any.whl", hash = "sha256:3a66eb970cbac598f9e5ccb5b2cf58930cd8e3ed86d393d541eaf2d8b1705229"}, + {file = "pathspec-0.11.0.tar.gz", hash = "sha256:64d338d4e0914e91c1792321e6907b5a593f1ab1851de7fc269557a21b30ebbc"}, +] + +[[package]] +name = "platformdirs" +version = "3.1.0" +description = "A small Python package for determining appropriate platform-specific dirs, e.g. a \"user data dir\"." +category = "dev" +optional = false +python-versions = ">=3.7" +files = [ + {file = "platformdirs-3.1.0-py3-none-any.whl", hash = "sha256:13b08a53ed71021350c9e300d4ea8668438fb0046ab3937ac9a29913a1a1350a"}, + {file = "platformdirs-3.1.0.tar.gz", hash = "sha256:accc3665857288317f32c7bebb5a8e482ba717b474f3fc1d18ca7f9214be0cef"}, +] + +[package.extras] +docs = ["furo (>=2022.12.7)", "proselint (>=0.13)", "sphinx (>=6.1.3)", "sphinx-autodoc-typehints (>=1.22,!=1.23.4)"] +test = ["appdirs (==1.4.4)", "covdefaults (>=2.2.2)", "pytest (>=7.2.1)", "pytest-cov (>=4)", "pytest-mock (>=3.10)"] + [[package]] name = "pluggy" version = "1.0.0" @@ -1815,6 +1979,25 @@ files = [ dev = ["pre-commit", "tox"] testing = ["pytest", "pytest-benchmark"] +[[package]] +name = "pre-commit" +version = "3.1.1" +description = "A framework for managing and maintaining multi-language pre-commit hooks." +category = "dev" +optional = false +python-versions = ">=3.8" +files = [ + {file = "pre_commit-3.1.1-py2.py3-none-any.whl", hash = "sha256:b80254e60668e1dd1f5c03a1c9e0413941d61f568a57d745add265945f65bfe8"}, + {file = "pre_commit-3.1.1.tar.gz", hash = "sha256:d63e6537f9252d99f65755ae5b79c989b462d511ebbc481b561db6a297e1e865"}, +] + +[package.dependencies] +cfgv = ">=2.0.0" +identify = ">=1.0.0" +nodeenv = ">=0.11.1" +pyyaml = ">=5.1" +virtualenv = ">=20.10.0" + [[package]] name = "protobuf" version = "3.19.5" @@ -2101,14 +2284,14 @@ files = [ [[package]] name = "pytest" -version = "7.2.1" +version = "7.2.2" description = "pytest: simple powerful testing with Python" category = "dev" optional = false python-versions = ">=3.7" files = [ - {file = "pytest-7.2.1-py3-none-any.whl", hash = "sha256:c7c6ca206e93355074ae32f7403e8ea12163b1163c976fee7d4d84027c162be5"}, - {file = "pytest-7.2.1.tar.gz", hash = "sha256:d45e0952f3727241918b8fd0f376f5ff6b301cc0777c6f9a556935c92d8a7d42"}, + {file = "pytest-7.2.2-py3-none-any.whl", hash = "sha256:130328f552dcfac0b1cec75c12e3f005619dc5f874f0a06e8ff7263f0ee6225e"}, + {file = "pytest-7.2.2.tar.gz", hash = "sha256:c99ab0c73aceb050f68929bc93af19ab6db0558791c6a0715723abe9d0ade9d4"}, ] [package.dependencies] @@ -2301,19 +2484,19 @@ idna2008 = ["idna"] [[package]] name = "rich" -version = "13.3.1" +version = "13.3.2" description = "Render rich text, tables, progress bars, syntax highlighting, markdown and more to the terminal" category = "main" optional = true python-versions = ">=3.7.0" files = [ - {file = "rich-13.3.1-py3-none-any.whl", hash = "sha256:8aa57747f3fc3e977684f0176a88e789be314a99f99b43b75d1e9cb5dc6db9e9"}, - {file = "rich-13.3.1.tar.gz", hash = "sha256:125d96d20c92b946b983d0d392b84ff945461e5a06d3867e9f9e575f8697b67f"}, + {file = "rich-13.3.2-py3-none-any.whl", hash = "sha256:a104f37270bf677148d8acb07d33be1569eeee87e2d1beb286a4e9113caf6f2f"}, + {file = "rich-13.3.2.tar.gz", hash = "sha256:91954fe80cfb7985727a467ca98a7618e5dd15178cc2da10f553b36a93859001"}, ] [package.dependencies] -markdown-it-py = ">=2.1.0,<3.0.0" -pygments = ">=2.14.0,<3.0.0" +markdown-it-py = ">=2.2.0,<3.0.0" +pygments = ">=2.13.0,<3.0.0" [package.extras] jupyter = ["ipywidgets (>=7.5.1,<9)"] @@ -2360,14 +2543,14 @@ crt = ["botocore[crt] (>=1.20.29,<2.0a.0)"] [[package]] name = "setuptools" -version = "67.4.0" +version = "67.5.1" description = "Easily download, build, install, upgrade, and uninstall Python packages" category = "main" optional = false python-versions = ">=3.7" files = [ - {file = "setuptools-67.4.0-py3-none-any.whl", hash = "sha256:f106dee1b506dee5102cc3f3e9e68137bbad6d47b616be7991714b0c62204251"}, - {file = "setuptools-67.4.0.tar.gz", hash = "sha256:e5fd0a713141a4a105412233c63dc4e17ba0090c8e8334594ac790ec97792330"}, + {file = "setuptools-67.5.1-py3-none-any.whl", hash = "sha256:1c39d42bda4cb89f7fdcad52b6762e3c309ec8f8715b27c684176b7d71283242"}, + {file = "setuptools-67.5.1.tar.gz", hash = "sha256:15136a251127da2d2e77ac7a1bc231eb504654f7e3346d93613a13f2e2787535"}, ] [package.extras] @@ -2418,53 +2601,43 @@ files = [ [[package]] name = "sqlalchemy" -version = "2.0.4" +version = "2.0.5.post1" description = "Database Abstraction Library" category = "main" optional = false python-versions = ">=3.7" files = [ - {file = "SQLAlchemy-2.0.4-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:b67d6e626caa571fb53accaac2fba003ef4f7317cb3481e9ab99dad6e89a70d6"}, - {file = "SQLAlchemy-2.0.4-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:b01dce097cf6f145da131a53d4cce7f42e0bfa9ae161dd171a423f7970d296d0"}, - {file = "SQLAlchemy-2.0.4-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:738c80705e11c1268827dbe22c01162a9cdc98fc6f7901b429a1459db2593060"}, - {file = "SQLAlchemy-2.0.4-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6363697c938b9a13e07f1bc2cd433502a7aa07efd55b946b31d25b9449890621"}, - {file = "SQLAlchemy-2.0.4-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:a42e6831e82dfa6d16b45f0c98c69e7b0defc64d76213173456355034450c414"}, - {file = "SQLAlchemy-2.0.4-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:011ef3c33f30bae5637c575f30647e0add98686642d237f0c3a1e3d9b35747fa"}, - {file = "SQLAlchemy-2.0.4-cp310-cp310-win32.whl", hash = "sha256:c1e8edc49b32483cd5d2d015f343e16be7dfab89f4aaf66b0fa6827ab356880d"}, - {file = "SQLAlchemy-2.0.4-cp310-cp310-win_amd64.whl", hash = "sha256:77a380bf8721b416782c763e0ff66f80f3b05aee83db33ddfc0eac20bcb6791f"}, - {file = "SQLAlchemy-2.0.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:2a2f9120eb32190bdba31d1022181ef08f257aed4f984f3368aa4e838de72bc0"}, - {file = "SQLAlchemy-2.0.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:679b9bd10bb32b8d3befed4aad4356799b6ec1bdddc0f930a79e41ba5b084124"}, - {file = "SQLAlchemy-2.0.4-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:582053571125895d008d4b8d9687d12d4bd209c076cdbab3504da307e2a0a2bd"}, - {file = "SQLAlchemy-2.0.4-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2c82395e2925639e6d320592943608070678e7157bd1db2672a63be9c7889434"}, - {file = "SQLAlchemy-2.0.4-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:25e4e54575f9d2af1eab82d3a470fca27062191c48ee57b6386fe09a3c0a6a33"}, - {file = "SQLAlchemy-2.0.4-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:9946ee503962859f1a9e1ad17dff0859269b0cb453686747fe87f00b0e030b34"}, - {file = "SQLAlchemy-2.0.4-cp311-cp311-win32.whl", hash = "sha256:c621f05859caed5c0aab032888a3d3bde2cae3988ca151113cbecf262adad976"}, - {file = "SQLAlchemy-2.0.4-cp311-cp311-win_amd64.whl", hash = "sha256:662a79e80f3e9fe33b7861c19fedf3d8389fab2413c04bba787e3f1139c22188"}, - {file = "SQLAlchemy-2.0.4-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:3f927340b37fe65ec42e19af7ce15260a73e11c6b456febb59009bfdfec29a35"}, - {file = "SQLAlchemy-2.0.4-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:67901b91bf5821482fcbe9da988cb16897809624ddf0fde339cd62365cc50032"}, - {file = "SQLAlchemy-2.0.4-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1644c603558590f465b3fa16e4557d87d3962bc2c81fd7ea85b582ecf4676b31"}, - {file = "SQLAlchemy-2.0.4-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:9a7ecaf90fe9ec8e45c86828f4f183564b33c9514e08667ca59e526fea63893a"}, - {file = "SQLAlchemy-2.0.4-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:8a88b32ce5b69d18507ffc9f10401833934ebc353c7b30d1e056023c64f0a736"}, - {file = "SQLAlchemy-2.0.4-cp37-cp37m-win32.whl", hash = "sha256:2267c004e78e291bba0dc766a9711c389649cf3e662cd46eec2bc2c238c637bd"}, - {file = "SQLAlchemy-2.0.4-cp37-cp37m-win_amd64.whl", hash = "sha256:59cf0cdb29baec4e074c7520d7226646a8a8f856b87d8300f3e4494901d55235"}, - {file = "SQLAlchemy-2.0.4-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:dd801375f19a6e1f021dabd8b1714f2fdb91cbc835cd13b5dd0bd7e9860392d7"}, - {file = "SQLAlchemy-2.0.4-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:d8efdda920988bcade542f53a2890751ff680474d548f32df919a35a21404e3f"}, - {file = "SQLAlchemy-2.0.4-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:918c2b553e3c78268b187f70983c9bc6f91e451a4f934827e9c919e03d258bd7"}, - {file = "SQLAlchemy-2.0.4-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:77d05773d5c79f2d3371d81697d54ee1b2c32085ad434ce9de4482e457ecb018"}, - {file = "SQLAlchemy-2.0.4-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:fdb2686eb01f670cdc6c43f092e333ff08c1cf0b646da5256c1237dc4ceef4ae"}, - {file = "SQLAlchemy-2.0.4-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:8ff0a7c669ec7cdb899eae7e622211c2dd8725b82655db2b41740d39e3cda466"}, - {file = "SQLAlchemy-2.0.4-cp38-cp38-win32.whl", hash = "sha256:57dcd9eed52413f7270b22797aa83c71b698db153d1541c1e83d45ecdf8e95e7"}, - {file = "SQLAlchemy-2.0.4-cp38-cp38-win_amd64.whl", hash = "sha256:54aa9f40d88728dd058e951eeb5ecc55241831ba4011e60c641738c1da0146b7"}, - {file = "SQLAlchemy-2.0.4-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:817aab80f7e8fe581696dae7aaeb2ceb0b7ea70ad03c95483c9115970d2a9b00"}, - {file = "SQLAlchemy-2.0.4-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:dc7b9f55c2f72c13b2328b8a870ff585c993ba1b5c155ece5c9d3216fa4b18f6"}, - {file = "SQLAlchemy-2.0.4-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f696828784ab2c07b127bfd2f2d513f47ec58924c29cff5b19806ac37acee31c"}, - {file = "SQLAlchemy-2.0.4-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ce54965a94673a0ebda25e7c3a05bf1aa74fd78cc452a1a710b704bf73fb8402"}, - {file = "SQLAlchemy-2.0.4-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:f342057422d6bcfdd4996e34cd5c7f78f7e500112f64b113f334cdfc6a0c593d"}, - {file = "SQLAlchemy-2.0.4-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:b5deafb4901618b3f98e8df7099cd11edd0d1e6856912647e28968b803de0dae"}, - {file = "SQLAlchemy-2.0.4-cp39-cp39-win32.whl", hash = "sha256:81f1ea264278fcbe113b9a5840f13a356cb0186e55b52168334124f1cd1bc495"}, - {file = "SQLAlchemy-2.0.4-cp39-cp39-win_amd64.whl", hash = "sha256:954f1ad73b78ea5ba5a35c89c4a5dfd0f3a06c17926503de19510eb9b3857bde"}, - {file = "SQLAlchemy-2.0.4-py3-none-any.whl", hash = "sha256:0adca8a3ca77234a142c5afed29322fb501921f13d1d5e9fa4253450d786c160"}, - {file = "SQLAlchemy-2.0.4.tar.gz", hash = "sha256:95a18e1a6af2114dbd9ee4f168ad33070d6317e11bafa28d983cc7b585fe900b"}, + {file = "SQLAlchemy-2.0.5.post1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:7fe933831e17f93947b4e3db4e4a7470dae24340f269baf06cdfcc0538c8d1cb"}, + {file = "SQLAlchemy-2.0.5.post1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:5c00d2b3607f9ae5c0827ebb2d01020c26cfce4064aa664db21d1fd6a47f8f60"}, + {file = "SQLAlchemy-2.0.5.post1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a7e55659740e768a1bf1257275b565137a3d28839789c85193dd6a1e642b3cc9"}, + {file = "SQLAlchemy-2.0.5.post1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:50b15fce441b8eb13bfd06df1088aa52c9a3d72d4894e3456040857d48a622da"}, + {file = "SQLAlchemy-2.0.5.post1-cp310-cp310-win32.whl", hash = "sha256:ffda70373ddfe8ec733d518e4e41eb5599480d48e8496c44bb0cac0e37b281c0"}, + {file = "SQLAlchemy-2.0.5.post1-cp310-cp310-win_amd64.whl", hash = "sha256:e40c39cfcbe416a7722a226ecd98fad0e08f8ae33e8f94b0858afe094583bfbc"}, + {file = "SQLAlchemy-2.0.5.post1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:22f60d214899b573edc8aeb9ba84f7e832505511ce68974636e6da4a27c957a3"}, + {file = "SQLAlchemy-2.0.5.post1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:4756878d0ceb6e0e9c6cfcfaa9df81adbfcca8cc4b9ec37934918008c0f20507"}, + {file = "SQLAlchemy-2.0.5.post1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1012c0440108c360b94f43667525365c43516e8c7f1f7de8dfb73471181055df"}, + {file = "SQLAlchemy-2.0.5.post1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:8e7d5766fb99743eb70126daaff45f43bee3f4b79ba6047a0749912e8538f0ff"}, + {file = "SQLAlchemy-2.0.5.post1-cp311-cp311-win32.whl", hash = "sha256:c2c41bf05b4cf4ffead35896affa3b457c17755d0fd83b1ba72f7f55abb3a3f1"}, + {file = "SQLAlchemy-2.0.5.post1-cp311-cp311-win_amd64.whl", hash = "sha256:56d38c3638965df5257ac4648ba2887aaf1e3409397192dd85ddfe7b96dc7680"}, + {file = "SQLAlchemy-2.0.5.post1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:68c4c5ab13997fa7af37d5780da11ddc184d4e88fb2d8a26525044c233f03bc7"}, + {file = "SQLAlchemy-2.0.5.post1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d6cb241c5c1af422c0fa742bd09a8eaf158da1433617ded1ffcbb56de6ff8047"}, + {file = "SQLAlchemy-2.0.5.post1-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:2c3869a7bdd5bb76fb50976abe339e30cce8e9f7c778a50811d310ec82cdf51a"}, + {file = "SQLAlchemy-2.0.5.post1-cp37-cp37m-win32.whl", hash = "sha256:1edb6621782f9a3e80750ba1859580b778a424242d4e6b9bcd46fa6beca75c12"}, + {file = "SQLAlchemy-2.0.5.post1-cp37-cp37m-win_amd64.whl", hash = "sha256:3c4e673da09af37b7a5c13b947fdb387c3800d43dcd86c1d553e3c70369e4749"}, + {file = "SQLAlchemy-2.0.5.post1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:ac12d8bef707d02ef179f0586c848db2954668dca2b72c69df950e08dc8cddb4"}, + {file = "SQLAlchemy-2.0.5.post1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:e13cea675937125417953fd011138f13cf979051567f48074fffb3bb0b64b917"}, + {file = "SQLAlchemy-2.0.5.post1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:03cd5709839fc376538f102c58f632d48bd0b92715bd290c3b2c066e0dd0f214"}, + {file = "SQLAlchemy-2.0.5.post1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:059ddd4ddbfb8f1c872d601b168273dfaab0eae458736c7c754187b9a8e92ad5"}, + {file = "SQLAlchemy-2.0.5.post1-cp38-cp38-win32.whl", hash = "sha256:9a4d9a7e9b344bf8ce2ed699baa8a43d9fbdad3aecff259f1d0daf6bb2e7e0c0"}, + {file = "SQLAlchemy-2.0.5.post1-cp38-cp38-win_amd64.whl", hash = "sha256:b52be78c5e86ade646c82a10b2be4b6ed8f623052b4405b26681880df1a15d5a"}, + {file = "SQLAlchemy-2.0.5.post1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:7e33867e09820c98630f7faec535a8cc4116fd362787404b41883d373437290b"}, + {file = "SQLAlchemy-2.0.5.post1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:0433abeb650c72c872e31010bff8536907fb05f6fa29a9b880046570c03383ca"}, + {file = "SQLAlchemy-2.0.5.post1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d811b97f58d99e5948752087903cb414fd77a60a5e09293be16c924219178c3b"}, + {file = "SQLAlchemy-2.0.5.post1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:f53542654124d30a3c3ebff9f99e5749add75e4cf28895a2ca6cd1458039bd8f"}, + {file = "SQLAlchemy-2.0.5.post1-cp39-cp39-win32.whl", hash = "sha256:b21694c8543becc2bc4f05f8d07970860e6ad005024712b7195abb1f4e0daf47"}, + {file = "SQLAlchemy-2.0.5.post1-cp39-cp39-win_amd64.whl", hash = "sha256:72e8d65b20147df71297d863981d8e56e429a8ae2bb835bd5e89efd7ef849866"}, + {file = "SQLAlchemy-2.0.5.post1-py3-none-any.whl", hash = "sha256:621e92ace804e19da2e472e349736d7ba5e2e4a14d41c4de9e2474e5f40a11ed"}, + {file = "SQLAlchemy-2.0.5.post1.tar.gz", hash = "sha256:13eb2a5882cfd9f4eedaaec14a5603a096f0125f7c3cb48611b3bfa3c253f25d"}, ] [package.dependencies] @@ -2648,6 +2821,27 @@ files = [ {file = "varint-1.0.2.tar.gz", hash = "sha256:a6ecc02377ac5ee9d65a6a8ad45c9ff1dac8ccee19400a5950fb51d594214ca5"}, ] +[[package]] +name = "virtualenv" +version = "20.20.0" +description = "Virtual Python Environment builder" +category = "dev" +optional = false +python-versions = ">=3.7" +files = [ + {file = "virtualenv-20.20.0-py3-none-any.whl", hash = "sha256:3c22fa5a7c7aa106ced59934d2c20a2ecb7f49b4130b8bf444178a16b880fa45"}, + {file = "virtualenv-20.20.0.tar.gz", hash = "sha256:a8a4b8ca1e28f864b7514a253f98c1d62b64e31e77325ba279248c65fb4fcef4"}, +] + +[package.dependencies] +distlib = ">=0.3.6,<1" +filelock = ">=3.4.1,<4" +platformdirs = ">=2.4,<4" + +[package.extras] +docs = ["furo (>=2022.12.7)", "proselint (>=0.13)", "sphinx (>=6.1.3)", "sphinx-argparse (>=0.4)", "sphinxcontrib-towncrier (>=0.2.1a0)", "towncrier (>=22.12)"] +test = ["covdefaults (>=2.2.2)", "coverage (>=7.1)", "coverage-enable-subprocess (>=1)", "flaky (>=3.7)", "packaging (>=23)", "pytest (>=7.2.1)", "pytest-env (>=0.8.1)", "pytest-freezegun (>=0.4.2)", "pytest-mock (>=3.10)", "pytest-randomly (>=3.12)", "pytest-timeout (>=2.1)"] + [[package]] name = "web3" version = "5.31.3" @@ -2836,4 +3030,4 @@ ibet-explorer = ["aiohttp", "async-cache", "ibet-prime-explorer", "textual", "ty [metadata] lock-version = "2.0" python-versions = "3.10.4" -content-hash = "d30919603cf774a6bbd285bccf971369efaa9d52177e2740a93ddfedac49005d" +content-hash = "8c4046c5be4ad54baa649a1b28d5e8afe92d56e53c250d31dc68f1e2907ee0ee" diff --git a/pyproject.toml b/pyproject.toml index b587d73a..e7cc969e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -38,6 +38,9 @@ pytest = "^7.2.1" pytest-cov = "^4.0.0" pyyaml = "^6.0" pytest-freezegun = "^0.4.2" +pre-commit = "^3.1.1" +isort = "^5.12.0" +black = "^23.1.0" [tool.poetry.extras] ibet-explorer = [ diff --git a/server.py b/server.py index b188415f..4eb23827 100644 --- a/server.py +++ b/server.py @@ -26,8 +26,11 @@ __import__("app.utils.cache_utils") # uvicorn parameters -WORKER_CONNECTIONS = int(os.environ.get('WORKER_CONNECTIONS')) \ - if os.environ.get('WORKER_CONNECTIONS') else 100 +WORKER_CONNECTIONS = ( + int(os.environ.get("WORKER_CONNECTIONS")) + if os.environ.get("WORKER_CONNECTIONS") + else 100 +) # Worker class to load by gunicorn when server run @@ -36,5 +39,5 @@ class AppUvicornWorker(UvicornWorker): "loop": "asyncio", "http": "h11", # NOTE: gunicorn don't support '--worker-connections' to uvicorn - "limit_concurrency": WORKER_CONNECTIONS + "limit_concurrency": WORKER_CONNECTIONS, } diff --git a/tests/account_config.py b/tests/account_config.py index 283f1635..1ee1e625 100644 --- a/tests/account_config.py +++ b/tests/account_config.py @@ -17,8 +17,8 @@ SPDX-License-Identifier: Apache-2.0 """ import json -import yaml +import yaml from web3 import Web3 from web3.middleware import geth_poa_middleware @@ -31,5 +31,7 @@ # Account Address(from local config) def config_eth_account(name): account_config = yaml.safe_load(open(f"tests/data/account_config.yml", "r")) - account_config[name]["keyfile_json"] = json.loads(account_config[name]["keyfile_json"]) + account_config[name]["keyfile_json"] = json.loads( + account_config[name]["keyfile_json"] + ) return account_config[name] diff --git a/tests/conftest.py b/tests/conftest.py index 6b2b1f58..495ebcf5 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -18,45 +18,37 @@ """ import os import sys -import pytest -from fastapi.testclient import TestClient +import pytest from eth_keyfile import decode_keyfile_json +from fastapi.testclient import TestClient path = os.path.join(os.path.dirname(__file__), "../") sys.path.append(path) path = os.path.join(os.path.dirname(__file__), "../batch") sys.path.append(path) -from app.main import app -from app.database import ( - SessionLocal, - engine, - db_session -) -from app.utils.contract_utils import ContractUtils -from config import ( - CHAIN_ID, - TX_GAS_LIMIT, - WEB3_HTTP_PROVIDER -) - -from tests.account_config import config_eth_account from web3 import Web3 from web3.middleware import geth_poa_middleware from web3.types import RPCEndpoint +from app.database import SessionLocal, db_session, engine +from app.main import app +from app.utils.contract_utils import ContractUtils +from config import CHAIN_ID, TX_GAS_LIMIT, WEB3_HTTP_PROVIDER +from tests.account_config import config_eth_account + web3 = Web3(Web3.HTTPProvider(WEB3_HTTP_PROVIDER)) web3.middleware_onion.inject(geth_poa_middleware, layer=0) -@pytest.fixture(scope='session') +@pytest.fixture(scope="session") def client(): client = TestClient(app) return client -@pytest.fixture(scope='function') +@pytest.fixture(scope="function") def db(): # Create DB session db = SessionLocal() @@ -69,6 +61,7 @@ def override_inject_db_session(): # Create DB tables from app.model.db import Base + Base.metadata.create_all(engine) yield db @@ -81,157 +74,178 @@ def override_inject_db_session(): app.dependency_overrides[db_session] = db_session -@pytest.fixture(scope='function', autouse=True) +@pytest.fixture(scope="function", autouse=True) def block_number(request): # save blockchain state before function starts evm_snapshot = web3.provider.make_request(RPCEndpoint("evm_snapshot"), []) def teardown(): # revert blockchain state after function starts - web3.provider.make_request(RPCEndpoint("evm_revert"), [int(evm_snapshot['result'], 16), ]) + web3.provider.make_request( + RPCEndpoint("evm_revert"), + [ + int(evm_snapshot["result"], 16), + ], + ) request.addfinalizer(teardown) -@pytest.fixture(scope='function') +@pytest.fixture(scope="function") def personal_info_contract(): user_1 = config_eth_account("user1") deployer_address = user_1["address"] deployer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Deploy personal info contract - contract_address, _, _ = ContractUtils.deploy_contract("PersonalInfo", [], deployer_address, deployer_private_key) + contract_address, _, _ = ContractUtils.deploy_contract( + "PersonalInfo", [], deployer_address, deployer_private_key + ) return ContractUtils.get_contract("PersonalInfo", contract_address) -@pytest.fixture(scope='function') +@pytest.fixture(scope="function") def ibet_exchange_contract(): user_1 = config_eth_account("user1") deployer_address = user_1["address"] deployer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Deploy payment gateway contract - payment_gateway_contract_address, _, _ = ContractUtils.deploy_contract("PaymentGateway", - [], - deployer_address, - deployer_private_key) - payment_gateway_contract = ContractUtils.get_contract("PaymentGateway", payment_gateway_contract_address) - tx = payment_gateway_contract.functions.addAgent(deployer_address).build_transaction({ - "chainId": CHAIN_ID, - "from": deployer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + payment_gateway_contract_address, _, _ = ContractUtils.deploy_contract( + "PaymentGateway", [], deployer_address, deployer_private_key + ) + payment_gateway_contract = ContractUtils.get_contract( + "PaymentGateway", payment_gateway_contract_address + ) + tx = payment_gateway_contract.functions.addAgent( + deployer_address + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": deployer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, deployer_private_key) # Deploy storage contract - storage_contract_address, _, _ = ContractUtils.deploy_contract("ExchangeStorage", - [], - deployer_address, - deployer_private_key) + storage_contract_address, _, _ = ContractUtils.deploy_contract( + "ExchangeStorage", [], deployer_address, deployer_private_key + ) # Deploy exchange contract - contract_address, _, _ = ContractUtils.deploy_contract("IbetExchange", - [payment_gateway_contract_address, storage_contract_address], - deployer_address, - deployer_private_key) + contract_address, _, _ = ContractUtils.deploy_contract( + "IbetExchange", + [payment_gateway_contract_address, storage_contract_address], + deployer_address, + deployer_private_key, + ) # Upgrade version - storage_contract = ContractUtils.get_contract("ExchangeStorage", storage_contract_address) - tx = storage_contract.functions.upgradeVersion(contract_address).build_transaction({ - "chainId": CHAIN_ID, - "from": deployer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + storage_contract = ContractUtils.get_contract( + "ExchangeStorage", storage_contract_address + ) + tx = storage_contract.functions.upgradeVersion(contract_address).build_transaction( + { + "chainId": CHAIN_ID, + "from": deployer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, deployer_private_key) return ContractUtils.get_contract("IbetExchange", contract_address) -@pytest.fixture(scope='function') +@pytest.fixture(scope="function") def ibet_escrow_contract(): user_1 = config_eth_account("user1") deployer_address = user_1["address"] deployer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Deploy storage contract - storage_contract_address, _, _ = ContractUtils.deploy_contract("EscrowStorage", - [], - deployer_address, - deployer_private_key) + storage_contract_address, _, _ = ContractUtils.deploy_contract( + "EscrowStorage", [], deployer_address, deployer_private_key + ) # Deploy escrow contract - contract_address, _, _ = ContractUtils.deploy_contract("IbetEscrow", - [storage_contract_address], - deployer_address, - deployer_private_key) + contract_address, _, _ = ContractUtils.deploy_contract( + "IbetEscrow", [storage_contract_address], deployer_address, deployer_private_key + ) # Upgrade version - storage_contract = ContractUtils.get_contract("EscrowStorage", storage_contract_address) - tx = storage_contract.functions.upgradeVersion(contract_address).build_transaction({ - "chainId": CHAIN_ID, - "from": deployer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + storage_contract = ContractUtils.get_contract( + "EscrowStorage", storage_contract_address + ) + tx = storage_contract.functions.upgradeVersion(contract_address).build_transaction( + { + "chainId": CHAIN_ID, + "from": deployer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, deployer_private_key) return ContractUtils.get_contract("IbetEscrow", contract_address) -@pytest.fixture(scope='function') +@pytest.fixture(scope="function") def ibet_security_token_escrow_contract(): user_1 = config_eth_account("user1") deployer_address = user_1["address"] deployer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Deploy storage contract - storage_contract_address, _, _ = ContractUtils.deploy_contract("EscrowStorage", - [], - deployer_address, - deployer_private_key) + storage_contract_address, _, _ = ContractUtils.deploy_contract( + "EscrowStorage", [], deployer_address, deployer_private_key + ) # Deploy security token escrow contract - contract_address, _, _ = ContractUtils.deploy_contract("IbetSecurityTokenEscrow", - [storage_contract_address], - deployer_address, - deployer_private_key) + contract_address, _, _ = ContractUtils.deploy_contract( + "IbetSecurityTokenEscrow", + [storage_contract_address], + deployer_address, + deployer_private_key, + ) # Upgrade version - storage_contract = ContractUtils.get_contract("EscrowStorage", storage_contract_address) - tx = storage_contract.functions.upgradeVersion(contract_address).build_transaction({ - "chainId": CHAIN_ID, - "from": deployer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + storage_contract = ContractUtils.get_contract( + "EscrowStorage", storage_contract_address + ) + tx = storage_contract.functions.upgradeVersion(contract_address).build_transaction( + { + "chainId": CHAIN_ID, + "from": deployer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, deployer_private_key) return ContractUtils.get_contract("IbetSecurityTokenEscrow", contract_address) -@pytest.fixture(scope='function') +@pytest.fixture(scope="function") def e2e_messaging_contract(): user_1 = config_eth_account("user1") deployer_address = user_1["address"] deployer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Deploy e2e messaging contract - contract_address, _, _ = ContractUtils.deploy_contract("E2EMessaging", [], deployer_address, deployer_private_key) + contract_address, _, _ = ContractUtils.deploy_contract( + "E2EMessaging", [], deployer_address, deployer_private_key + ) return ContractUtils.get_contract("E2EMessaging", contract_address) diff --git a/tests/model/blockchain/test_E2EMessaging.py b/tests/model/blockchain/test_E2EMessaging.py index 05cb66e1..74d53956 100644 --- a/tests/model/blockchain/test_E2EMessaging.py +++ b/tests/model/blockchain/test_E2EMessaging.py @@ -16,29 +16,25 @@ SPDX-License-Identifier: Apache-2.0 """ -import pytest import base64 import json import os from unittest import mock from unittest.mock import MagicMock -from Crypto.Cipher import ( - AES, - PKCS1_OAEP -) +import pytest +from Crypto.Cipher import AES, PKCS1_OAEP from Crypto.PublicKey import RSA from Crypto.Util.Padding import unpad from eth_keyfile import decode_keyfile_json from web3 import Web3 -from web3.middleware import geth_poa_middleware from web3.exceptions import TimeExhausted +from web3.middleware import geth_poa_middleware +from app.exceptions import SendTransactionError from app.model.blockchain import E2EMessaging from app.utils.contract_utils import ContractUtils from config import WEB3_HTTP_PROVIDER -from app.exceptions import SendTransactionError - from tests.account_config import config_eth_account web3 = Web3(Web3.HTTPProvider(WEB3_HTTP_PROVIDER)) @@ -46,7 +42,6 @@ class TestSendMessage: - ########################################################################### # Normal Case ########################################################################### @@ -56,8 +51,7 @@ def test_normal_1(self, db, e2e_messaging_contract): user_1 = config_eth_account("user1") user_address_1 = user_1["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_2 = user_2["address"] @@ -68,13 +62,15 @@ def test_normal_1(self, db, e2e_messaging_contract): to_address=user_address_2, message=message, tx_from=user_address_1, - private_key=user_private_key_1 + private_key=user_private_key_1, ) # Assertion assert isinstance(tx_hash, str) assert tx_receipt["status"] == 1 - last_message = e2e_messaging_contract.functions.getLastMessage(user_address_2).call() + last_message = e2e_messaging_contract.functions.getLastMessage( + user_address_2 + ).call() block = ContractUtils.get_block_by_transaction_hash(tx_hash) assert last_message[0] == user_address_1 assert last_message[1] == message @@ -90,22 +86,23 @@ def test_error_1(self, db, e2e_messaging_contract): user_1 = config_eth_account("user1") user_address_1 = user_1["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_2 = user_2["address"] message = "test message" with pytest.raises(SendTransactionError) as exc_info: - with mock.patch("app.utils.contract_utils.ContractUtils.send_transaction", - MagicMock(side_effect=Exception("tx error"))): + with mock.patch( + "app.utils.contract_utils.ContractUtils.send_transaction", + MagicMock(side_effect=Exception("tx error")), + ): # Run Test E2EMessaging(e2e_messaging_contract.address).send_message( to_address=user_address_2, message=message, tx_from=user_address_1, - private_key=user_private_key_1 + private_key=user_private_key_1, ) # Assertion @@ -119,22 +116,23 @@ def test_error_2(self, db, e2e_messaging_contract): user_1 = config_eth_account("user1") user_address_1 = user_1["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_2 = user_2["address"] message = "test message" with pytest.raises(SendTransactionError) as exc_info: - with mock.patch("app.utils.contract_utils.ContractUtils.send_transaction", - MagicMock(side_effect=TimeExhausted("Timeout Error test"))): + with mock.patch( + "app.utils.contract_utils.ContractUtils.send_transaction", + MagicMock(side_effect=TimeExhausted("Timeout Error test")), + ): # Run Test E2EMessaging(e2e_messaging_contract.address).send_message( to_address=user_address_2, message=message, tx_from=user_address_1, - private_key=user_private_key_1 + private_key=user_private_key_1, ) # Assertion @@ -223,8 +221,7 @@ def test_normal_1(self, db, e2e_messaging_contract): user_1 = config_eth_account("user1") user_address_1 = user_1["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_2 = user_2["address"] @@ -232,19 +229,23 @@ def test_normal_1(self, db, e2e_messaging_contract): _type = "test_type" # Run Test - tx_hash, tx_receipt = E2EMessaging(e2e_messaging_contract.address).send_message_external( + tx_hash, tx_receipt = E2EMessaging( + e2e_messaging_contract.address + ).send_message_external( to_address=user_address_2, _type=_type, message_org=message_org, to_rsa_public_key=self.rsa_public_key, tx_from=user_address_1, - private_key=user_private_key_1 + private_key=user_private_key_1, ) # Assertion assert isinstance(tx_hash, str) assert tx_receipt["status"] == 1 - last_message = e2e_messaging_contract.functions.getLastMessage(user_address_2).call() + last_message = e2e_messaging_contract.functions.getLastMessage( + user_address_2 + ).call() block = ContractUtils.get_block_by_transaction_hash(tx_hash) assert last_message[0] == user_address_1 message_dict = json.loads(last_message[1]) @@ -255,23 +256,24 @@ def test_normal_1(self, db, e2e_messaging_contract): aes_key = rsa_cipher.decrypt(base64.decodebytes(cipher_key.encode("utf-8"))) assert len(aes_key) == AES.block_size * 2 encrypt_message = base64.b64decode(message_dict["text"]["message"]) - aes_iv = encrypt_message[:AES.block_size] + aes_iv = encrypt_message[: AES.block_size] aes_cipher = AES.new(aes_key, AES.MODE_CBC, aes_iv) - pad_message = aes_cipher.decrypt(encrypt_message[AES.block_size:]) + pad_message = aes_cipher.decrypt(encrypt_message[AES.block_size :]) decrypt_message = unpad(pad_message, AES.block_size).decode() assert decrypt_message == message_org assert last_message[2] == block["timestamp"] # # use AWS KMS - @mock.patch("app.model.blockchain.e2e_messaging.AWS_KMS_GENERATE_RANDOM_ENABLED", True) + @mock.patch( + "app.model.blockchain.e2e_messaging.AWS_KMS_GENERATE_RANDOM_ENABLED", True + ) @mock.patch("boto3.client") def test_normal_2(self, boto3_mock, db, e2e_messaging_contract): user_1 = config_eth_account("user1") user_address_1 = user_1["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_2 = user_2["address"] @@ -290,28 +292,28 @@ def generate_random(self, NumberOfBytes): assert NumberOfBytes == 16 random_byte = os.urandom(NumberOfBytes) self.call_cnt += 1 - return { - "Plaintext": random_byte - } + return {"Plaintext": random_byte} - boto3_mock.side_effect = [ - KMSClientMock() - ] + boto3_mock.side_effect = [KMSClientMock()] # Run Test - tx_hash, tx_receipt = E2EMessaging(e2e_messaging_contract.address).send_message_external( + tx_hash, tx_receipt = E2EMessaging( + e2e_messaging_contract.address + ).send_message_external( to_address=user_address_2, _type=_type, message_org=message_org, to_rsa_public_key=self.rsa_public_key, tx_from=user_address_1, - private_key=user_private_key_1 + private_key=user_private_key_1, ) # Assertion assert isinstance(tx_hash, str) assert tx_receipt["status"] == 1 - last_message = e2e_messaging_contract.functions.getLastMessage(user_address_2).call() + last_message = e2e_messaging_contract.functions.getLastMessage( + user_address_2 + ).call() block = ContractUtils.get_block_by_transaction_hash(tx_hash) assert last_message[0] == user_address_1 message_dict = json.loads(last_message[1]) @@ -322,9 +324,9 @@ def generate_random(self, NumberOfBytes): aes_key = rsa_cipher.decrypt(base64.decodebytes(cipher_key.encode("utf-8"))) assert len(aes_key) == AES.block_size * 2 encrypt_message = base64.b64decode(message_dict["text"]["message"]) - aes_iv = encrypt_message[:AES.block_size] + aes_iv = encrypt_message[: AES.block_size] aes_cipher = AES.new(aes_key, AES.MODE_CBC, aes_iv) - pad_message = aes_cipher.decrypt(encrypt_message[AES.block_size:]) + pad_message = aes_cipher.decrypt(encrypt_message[AES.block_size :]) decrypt_message = unpad(pad_message, AES.block_size).decode() assert decrypt_message == message_org assert last_message[2] == block["timestamp"] @@ -339,8 +341,7 @@ def test_error_1(self, db, e2e_messaging_contract): user_1 = config_eth_account("user1") user_address_1 = user_1["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_2 = user_2["address"] @@ -349,8 +350,10 @@ def test_error_1(self, db, e2e_messaging_contract): # Run Test with pytest.raises(SendTransactionError) as exc_info: - with mock.patch("app.utils.contract_utils.ContractUtils.send_transaction", - MagicMock(side_effect=Exception("tx error"))): + with mock.patch( + "app.utils.contract_utils.ContractUtils.send_transaction", + MagicMock(side_effect=Exception("tx error")), + ): # Run Test E2EMessaging(e2e_messaging_contract.address).send_message_external( to_address=user_address_2, @@ -358,7 +361,7 @@ def test_error_1(self, db, e2e_messaging_contract): message_org=message_org, to_rsa_public_key=self.rsa_public_key, tx_from=user_address_1, - private_key=user_private_key_1 + private_key=user_private_key_1, ) # Assertion @@ -372,8 +375,7 @@ def test_error_2(self, db, e2e_messaging_contract): user_1 = config_eth_account("user1") user_address_1 = user_1["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_2 = user_2["address"] @@ -381,8 +383,10 @@ def test_error_2(self, db, e2e_messaging_contract): _type = "test_type" with pytest.raises(SendTransactionError) as exc_info: - with mock.patch("app.utils.contract_utils.ContractUtils.send_transaction", - MagicMock(side_effect=TimeExhausted("Timeout Error test"))): + with mock.patch( + "app.utils.contract_utils.ContractUtils.send_transaction", + MagicMock(side_effect=TimeExhausted("Timeout Error test")), + ): # Run Test E2EMessaging(e2e_messaging_contract.address).send_message_external( to_address=user_address_2, @@ -390,7 +394,7 @@ def test_error_2(self, db, e2e_messaging_contract): message_org=message_org, to_rsa_public_key=self.rsa_public_key, tx_from=user_address_1, - private_key=user_private_key_1 + private_key=user_private_key_1, ) # Assertion @@ -425,23 +429,26 @@ def test_normal_1(self, db, e2e_messaging_contract): user_1 = config_eth_account("user1") user_address_1 = user_1["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) key_type = "RSA4098" # Run Test - tx_hash, tx_receipt = E2EMessaging(e2e_messaging_contract.address).set_public_key( + tx_hash, tx_receipt = E2EMessaging( + e2e_messaging_contract.address + ).set_public_key( public_key=self.rsa_public_key, key_type=key_type, tx_from=user_address_1, - private_key=user_private_key_1 + private_key=user_private_key_1, ) # Assertion assert isinstance(tx_hash, str) assert tx_receipt["status"] == 1 - public_key = e2e_messaging_contract.functions.getPublicKey(user_address_1).call() + public_key = e2e_messaging_contract.functions.getPublicKey( + user_address_1 + ).call() assert public_key[0] == self.rsa_public_key assert public_key[1] == key_type @@ -455,21 +462,22 @@ def test_error_1(self, db, e2e_messaging_contract): user_1 = config_eth_account("user1") user_address_1 = user_1["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) key_type = "RSA4098" # Run Test with pytest.raises(SendTransactionError) as exc_info: - with mock.patch("app.utils.contract_utils.ContractUtils.send_transaction", - MagicMock(side_effect=Exception("tx error"))): + with mock.patch( + "app.utils.contract_utils.ContractUtils.send_transaction", + MagicMock(side_effect=Exception("tx error")), + ): # Run Test E2EMessaging(e2e_messaging_contract.address).set_public_key( public_key=self.rsa_public_key, key_type=key_type, tx_from=user_address_1, - private_key=user_private_key_1 + private_key=user_private_key_1, ) # Assertion @@ -483,20 +491,21 @@ def test_error_2(self, db, e2e_messaging_contract): user_1 = config_eth_account("user1") user_address_1 = user_1["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) key_type = "RSA4098" with pytest.raises(SendTransactionError) as exc_info: - with mock.patch("app.utils.contract_utils.ContractUtils.send_transaction", - MagicMock(side_effect=TimeExhausted("Timeout Error test"))): + with mock.patch( + "app.utils.contract_utils.ContractUtils.send_transaction", + MagicMock(side_effect=TimeExhausted("Timeout Error test")), + ): # Run Test E2EMessaging(e2e_messaging_contract.address).set_public_key( public_key=self.rsa_public_key, key_type=key_type, tx_from=user_address_1, - private_key=user_private_key_1 + private_key=user_private_key_1, ) # Assertion diff --git a/tests/model/blockchain/test_PersonalInfo.py b/tests/model/blockchain/test_PersonalInfo.py index 065f22aa..32316772 100644 --- a/tests/model/blockchain/test_PersonalInfo.py +++ b/tests/model/blockchain/test_PersonalInfo.py @@ -16,26 +16,25 @@ SPDX-License-Identifier: Apache-2.0 """ -import pytest import base64 import json +from unittest import mock +from unittest.mock import MagicMock +import pytest from Crypto.Cipher import PKCS1_OAEP from Crypto.PublicKey import RSA from eth_keyfile import decode_keyfile_json from web3 import Web3 +from web3.exceptions import ContractLogicError, TimeExhausted from web3.middleware import geth_poa_middleware -from web3.exceptions import TimeExhausted, ContractLogicError -from unittest.mock import MagicMock -from unittest import mock -from config import WEB3_HTTP_PROVIDER, TX_GAS_LIMIT, CHAIN_ID +from app.exceptions import ContractRevertError, SendTransactionError from app.model.blockchain import PersonalInfoContract -from app.utils.contract_utils import ContractUtils -from app.exceptions import SendTransactionError, ContractRevertError from app.model.db import Account +from app.utils.contract_utils import ContractUtils from app.utils.e2ee_utils import E2EEUtils - +from config import CHAIN_ID, TX_GAS_LIMIT, WEB3_HTTP_PROVIDER from tests.account_config import config_eth_account web3 = Web3(Web3.HTTPProvider(WEB3_HTTP_PROVIDER)) @@ -56,17 +55,19 @@ def initialize(issuer, db): db.commit() private_key = decode_keyfile_json( - raw_keyfile_json=issuer["keyfile_json"], - password=eoa_password.encode("utf-8") + raw_keyfile_json=issuer["keyfile_json"], password=eoa_password.encode("utf-8") + ) + contract_address, _, _ = ContractUtils.deploy_contract( + "PersonalInfo", [], issuer["address"], private_key ) - contract_address, _, _ = ContractUtils.deploy_contract("PersonalInfo", [], issuer["address"], private_key) - personal_info_contract = PersonalInfoContract(db, issuer["address"], contract_address) + personal_info_contract = PersonalInfoContract( + db, issuer["address"], contract_address + ) return personal_info_contract class TestGetInfo: - ########################################################################### # Normal Case ########################################################################### @@ -79,7 +80,9 @@ def test_normal_1(self, db): # Set personal information data setting_user = config_eth_account("user2") rsa_password = "password" - rsa = RSA.importKey(personal_info_contract.issuer.rsa_public_key, passphrase=rsa_password) + rsa = RSA.importKey( + personal_info_contract.issuer.rsa_public_key, passphrase=rsa_password + ) cipher = PKCS1_OAEP.new(rsa) data = { "key_manager": "1234567890", @@ -89,21 +92,27 @@ def test_normal_1(self, db): "email": "sample@test.test", "birth": "19801231", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } - ciphertext = base64.encodebytes(cipher.encrypt(json.dumps(data).encode('utf-8'))) + ciphertext = base64.encodebytes( + cipher.encrypt(json.dumps(data).encode("utf-8")) + ) contract = personal_info_contract.personal_info_contract - tx = contract.functions.register(issuer["address"], ciphertext).build_transaction({ - "nonce": web3.eth.get_transaction_count(setting_user["address"]), - "from": setting_user["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0, - "chainId": CHAIN_ID - }) + tx = contract.functions.register( + issuer["address"], ciphertext + ).build_transaction( + { + "nonce": web3.eth.get_transaction_count(setting_user["address"]), + "from": setting_user["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + "chainId": CHAIN_ID, + } + ) eoa_password = "password" private_key = decode_keyfile_json( raw_keyfile_json=setting_user["keyfile_json"], - password=eoa_password.encode("utf-8") + password=eoa_password.encode("utf-8"), ) ContractUtils.send_transaction(tx, private_key) @@ -121,22 +130,26 @@ def test_normal_2(self, db): # Set personal information data setting_user = config_eth_account("user2") contract = personal_info_contract.personal_info_contract - tx = contract.functions.register(issuer["address"], "").build_transaction({ - "nonce": web3.eth.get_transaction_count(setting_user["address"]), - "from": setting_user["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0, - "chainId": CHAIN_ID - }) + tx = contract.functions.register(issuer["address"], "").build_transaction( + { + "nonce": web3.eth.get_transaction_count(setting_user["address"]), + "from": setting_user["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + "chainId": CHAIN_ID, + } + ) eoa_password = "password" private_key = decode_keyfile_json( raw_keyfile_json=setting_user["keyfile_json"], - password=eoa_password.encode("utf-8") + password=eoa_password.encode("utf-8"), ) ContractUtils.send_transaction(tx, private_key) # Run Test - get_info = personal_info_contract.get_info(setting_user["address"], default_value="test") + get_info = personal_info_contract.get_info( + setting_user["address"], default_value="test" + ) assert get_info == { "key_manager": "test", @@ -146,7 +159,7 @@ def test_normal_2(self, db): "email": "test", "birth": "test", "is_corporate": "test", - "tax_category": "test" + "tax_category": "test", } ########################################################################### @@ -162,7 +175,9 @@ def test_error_1(self, db): # Set personal information data setting_user = config_eth_account("user2") rsa_password = "password" - rsa = RSA.importKey(personal_info_contract.issuer.rsa_public_key, passphrase=rsa_password) + rsa = RSA.importKey( + personal_info_contract.issuer.rsa_public_key, passphrase=rsa_password + ) cipher = PKCS1_OAEP.new(rsa) data = { "key_manager": "1234567890", @@ -172,21 +187,27 @@ def test_error_1(self, db): "email": "sample@test.test", "birth": "19801231", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } - ciphertext = base64.encodebytes(cipher.encrypt(json.dumps(data).encode('utf-8'))) + ciphertext = base64.encodebytes( + cipher.encrypt(json.dumps(data).encode("utf-8")) + ) contract = personal_info_contract.personal_info_contract - tx = contract.functions.register(issuer["address"], ciphertext).build_transaction({ - "nonce": web3.eth.get_transaction_count(setting_user["address"]), - "from": setting_user["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0, - "chainId": CHAIN_ID - }) + tx = contract.functions.register( + issuer["address"], ciphertext + ).build_transaction( + { + "nonce": web3.eth.get_transaction_count(setting_user["address"]), + "from": setting_user["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + "chainId": CHAIN_ID, + } + ) eoa_password = "password" private_key = decode_keyfile_json( raw_keyfile_json=setting_user["keyfile_json"], - password=eoa_password.encode("utf-8") + password=eoa_password.encode("utf-8"), ) ContractUtils.send_transaction(tx, private_key) @@ -194,7 +215,9 @@ def test_error_1(self, db): personal_info_contract.issuer.rsa_private_key = "testtest" # Run Test - get_info = personal_info_contract.get_info(setting_user["address"], default_value="test") + get_info = personal_info_contract.get_info( + setting_user["address"], default_value="test" + ) assert get_info == { "key_manager": "test", @@ -204,7 +227,7 @@ def test_error_1(self, db): "email": "test", "birth": "test", "is_corporate": "test", - "tax_category": "test" + "tax_category": "test", } # @@ -216,23 +239,28 @@ def test_error_2(self, db): # Set personal information data setting_user = config_eth_account("user2") contract = personal_info_contract.personal_info_contract - tx = contract.functions.register(issuer["address"], "testtest").build_transaction({ - "nonce": web3.eth.get_transaction_count(setting_user["address"]), - "from": setting_user["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0, - "chainId": CHAIN_ID - - }) + tx = contract.functions.register( + issuer["address"], "testtest" + ).build_transaction( + { + "nonce": web3.eth.get_transaction_count(setting_user["address"]), + "from": setting_user["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + "chainId": CHAIN_ID, + } + ) eoa_password = "password" private_key = decode_keyfile_json( raw_keyfile_json=setting_user["keyfile_json"], - password=eoa_password.encode("utf-8") + password=eoa_password.encode("utf-8"), ) ContractUtils.send_transaction(tx, private_key) # Run Test - get_info = personal_info_contract.get_info(setting_user["address"], default_value="test") + get_info = personal_info_contract.get_info( + setting_user["address"], default_value="test" + ) assert get_info == { "key_manager": "test", @@ -242,12 +270,11 @@ def test_error_2(self, db): "email": "test", "birth": "test", "is_corporate": "test", - "tax_category": "test" + "tax_category": "test", } class TestRegisterInfo: - ########################################################################### # Normal Case ########################################################################### @@ -268,7 +295,7 @@ def test_normal_1(self, db): "email": "sample@test.test2", "birth": "19800101", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } personal_info_contract.register_info(setting_user["address"], register_data) @@ -285,7 +312,9 @@ def test_normal_2(self, db): # Set personal information data setting_user = config_eth_account("user2") rsa_password = "password" - rsa = RSA.importKey(personal_info_contract.issuer.rsa_public_key, passphrase=rsa_password) + rsa = RSA.importKey( + personal_info_contract.issuer.rsa_public_key, passphrase=rsa_password + ) cipher = PKCS1_OAEP.new(rsa) data = { "key_manager": "1234567890", @@ -295,21 +324,27 @@ def test_normal_2(self, db): "email": "sample@test.test", "birth": "19801231", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } - ciphertext = base64.encodebytes(cipher.encrypt(json.dumps(data).encode('utf-8'))) + ciphertext = base64.encodebytes( + cipher.encrypt(json.dumps(data).encode("utf-8")) + ) contract = personal_info_contract.personal_info_contract - tx = contract.functions.register(issuer["address"], ciphertext).build_transaction({ - "nonce": web3.eth.get_transaction_count(setting_user["address"]), - "from": setting_user["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0, - "chainId": CHAIN_ID - }) + tx = contract.functions.register( + issuer["address"], ciphertext + ).build_transaction( + { + "nonce": web3.eth.get_transaction_count(setting_user["address"]), + "from": setting_user["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + "chainId": CHAIN_ID, + } + ) eoa_password = "password" private_key = decode_keyfile_json( raw_keyfile_json=setting_user["keyfile_json"], - password=eoa_password.encode("utf-8") + password=eoa_password.encode("utf-8"), ) ContractUtils.send_transaction(tx, private_key) @@ -322,7 +357,7 @@ def test_normal_2(self, db): "email": "sample@test.test2", "birth": "19800101", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } personal_info_contract.register_info(setting_user["address"], update_data) @@ -350,11 +385,16 @@ def test_error_1(self, db): "email": "sample@test.test2", "birth": "19800101", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } - with mock.patch("web3.eth.Eth.wait_for_transaction_receipt", MagicMock(side_effect=TimeExhausted())): + with mock.patch( + "web3.eth.Eth.wait_for_transaction_receipt", + MagicMock(side_effect=TimeExhausted()), + ): with pytest.raises(SendTransactionError): - personal_info_contract.register_info(setting_user["address"], register_data) + personal_info_contract.register_info( + setting_user["address"], register_data + ) # # SendTransactionError(Other Error) @@ -372,11 +412,16 @@ def test_error_2(self, db): "email": "sample@test.test2", "birth": "19800101", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } - with mock.patch("web3.eth.Eth.wait_for_transaction_receipt", MagicMock(side_effect=TypeError())): + with mock.patch( + "web3.eth.Eth.wait_for_transaction_receipt", + MagicMock(side_effect=TypeError()), + ): with pytest.raises(SendTransactionError): - personal_info_contract.register_info(setting_user["address"], register_data) + personal_info_contract.register_info( + setting_user["address"], register_data + ) # # Transaction REVERT @@ -386,7 +431,6 @@ def test_error_3(self, db): class TestModifyInfo: - ########################################################################### # Normal Case ########################################################################### @@ -399,7 +443,9 @@ def test_normal_1(self, db): # Set personal information data setting_user = config_eth_account("user2") rsa_password = "password" - rsa = RSA.importKey(personal_info_contract.issuer.rsa_public_key, passphrase=rsa_password) + rsa = RSA.importKey( + personal_info_contract.issuer.rsa_public_key, passphrase=rsa_password + ) cipher = PKCS1_OAEP.new(rsa) data = { "key_manager": "1234567890", @@ -409,21 +455,27 @@ def test_normal_1(self, db): "email": "sample@test.test", "birth": "19801231", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } - ciphertext = base64.encodebytes(cipher.encrypt(json.dumps(data).encode('utf-8'))) + ciphertext = base64.encodebytes( + cipher.encrypt(json.dumps(data).encode("utf-8")) + ) contract = personal_info_contract.personal_info_contract - tx = contract.functions.register(issuer["address"], ciphertext).build_transaction({ - "nonce": web3.eth.get_transaction_count(setting_user["address"]), - "from": setting_user["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0, - "chainId": CHAIN_ID - }) + tx = contract.functions.register( + issuer["address"], ciphertext + ).build_transaction( + { + "nonce": web3.eth.get_transaction_count(setting_user["address"]), + "from": setting_user["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + "chainId": CHAIN_ID, + } + ) eoa_password = "password" private_key = decode_keyfile_json( raw_keyfile_json=setting_user["keyfile_json"], - password=eoa_password.encode("utf-8") + password=eoa_password.encode("utf-8"), ) ContractUtils.send_transaction(tx, private_key) @@ -436,7 +488,7 @@ def test_normal_1(self, db): "email": "sample@test.test2", "birth": "19800101", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } personal_info_contract.modify_info(setting_user["address"], update_data) @@ -457,7 +509,9 @@ def test_error_1(self, db): # Set personal information data setting_user = config_eth_account("user2") rsa_password = "password" - rsa = RSA.importKey(personal_info_contract.issuer.rsa_public_key, passphrase=rsa_password) + rsa = RSA.importKey( + personal_info_contract.issuer.rsa_public_key, passphrase=rsa_password + ) cipher = PKCS1_OAEP.new(rsa) data = { "key_manager": "1234567890", @@ -467,21 +521,27 @@ def test_error_1(self, db): "email": "sample@test.test", "birth": "19801231", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } - ciphertext = base64.encodebytes(cipher.encrypt(json.dumps(data).encode('utf-8'))) + ciphertext = base64.encodebytes( + cipher.encrypt(json.dumps(data).encode("utf-8")) + ) contract = personal_info_contract.personal_info_contract - tx = contract.functions.register(issuer["address"], ciphertext).build_transaction({ - "nonce": web3.eth.get_transaction_count(setting_user["address"]), - "from": setting_user["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0, - "chainId": CHAIN_ID - }) + tx = contract.functions.register( + issuer["address"], ciphertext + ).build_transaction( + { + "nonce": web3.eth.get_transaction_count(setting_user["address"]), + "from": setting_user["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + "chainId": CHAIN_ID, + } + ) eoa_password = "password" private_key = decode_keyfile_json( raw_keyfile_json=setting_user["keyfile_json"], - password=eoa_password.encode("utf-8") + password=eoa_password.encode("utf-8"), ) ContractUtils.send_transaction(tx, private_key) @@ -494,9 +554,12 @@ def test_error_1(self, db): "email": "sample@test.test2", "birth": "19800101", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } - with mock.patch("web3.eth.Eth.wait_for_transaction_receipt", MagicMock(side_effect=TimeExhausted())): + with mock.patch( + "web3.eth.Eth.wait_for_transaction_receipt", + MagicMock(side_effect=TimeExhausted()), + ): with pytest.raises(SendTransactionError): personal_info_contract.modify_info(setting_user["address"], update_data) @@ -509,7 +572,9 @@ def test_error_2(self, db): # Set personal information data setting_user = config_eth_account("user2") rsa_password = "password" - rsa = RSA.importKey(personal_info_contract.issuer.rsa_public_key, passphrase=rsa_password) + rsa = RSA.importKey( + personal_info_contract.issuer.rsa_public_key, passphrase=rsa_password + ) cipher = PKCS1_OAEP.new(rsa) data = { "key_manager": "1234567890", @@ -519,21 +584,27 @@ def test_error_2(self, db): "email": "sample@test.test", "birth": "19801231", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } - ciphertext = base64.encodebytes(cipher.encrypt(json.dumps(data).encode('utf-8'))) + ciphertext = base64.encodebytes( + cipher.encrypt(json.dumps(data).encode("utf-8")) + ) contract = personal_info_contract.personal_info_contract - tx = contract.functions.register(issuer["address"], ciphertext).build_transaction({ - "nonce": web3.eth.get_transaction_count(setting_user["address"]), - "from": setting_user["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0, - "chainId": CHAIN_ID - }) + tx = contract.functions.register( + issuer["address"], ciphertext + ).build_transaction( + { + "nonce": web3.eth.get_transaction_count(setting_user["address"]), + "from": setting_user["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + "chainId": CHAIN_ID, + } + ) eoa_password = "password" private_key = decode_keyfile_json( raw_keyfile_json=setting_user["keyfile_json"], - password=eoa_password.encode("utf-8") + password=eoa_password.encode("utf-8"), ) ContractUtils.send_transaction(tx, private_key) @@ -546,9 +617,12 @@ def test_error_2(self, db): "email": "sample@test.test2", "birth": "19800101", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } - with mock.patch("web3.eth.Eth.wait_for_transaction_receipt", MagicMock(side_effect=TypeError())): + with mock.patch( + "web3.eth.Eth.wait_for_transaction_receipt", + MagicMock(side_effect=TypeError()), + ): with pytest.raises(SendTransactionError): personal_info_contract.modify_info(setting_user["address"], update_data) @@ -570,7 +644,7 @@ def test_error_3(self, db): "email": "sample@test.test2", "birth": "19800101", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } # mock @@ -579,7 +653,7 @@ def test_error_3(self, db): # geth: ContractLogicError("execution reverted") InspectionMock = mock.patch( "web3.eth.Eth.call", - MagicMock(side_effect=ContractLogicError("execution reverted")) + MagicMock(side_effect=ContractLogicError("execution reverted")), ) # test IbetSecurityTokenEscrow.approve_transfer with InspectionMock, pytest.raises(ContractRevertError) as exc_info: @@ -589,7 +663,6 @@ def test_error_3(self, db): class TestGetRegisterEvent: - ########################################################################### # Normal Case ########################################################################### @@ -604,7 +677,9 @@ def test_normal_1(self, db): # Set personal information data(Register) setting_user = config_eth_account("user2") rsa_password = "password" - rsa = RSA.importKey(personal_info_contract.issuer.rsa_public_key, passphrase=rsa_password) + rsa = RSA.importKey( + personal_info_contract.issuer.rsa_public_key, passphrase=rsa_password + ) cipher = PKCS1_OAEP.new(rsa) data = { "key_manager": "1234567890", @@ -614,27 +689,35 @@ def test_normal_1(self, db): "email": "sample@test.test", "birth": "19801231", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } - ciphertext = base64.encodebytes(cipher.encrypt(json.dumps(data).encode('utf-8'))) + ciphertext = base64.encodebytes( + cipher.encrypt(json.dumps(data).encode("utf-8")) + ) contract = personal_info_contract.personal_info_contract - tx = contract.functions.register(issuer["address"], ciphertext).build_transaction({ - "nonce": web3.eth.get_transaction_count(setting_user["address"]), - "from": setting_user["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0, - "chainId": CHAIN_ID - }) + tx = contract.functions.register( + issuer["address"], ciphertext + ).build_transaction( + { + "nonce": web3.eth.get_transaction_count(setting_user["address"]), + "from": setting_user["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + "chainId": CHAIN_ID, + } + ) eoa_password = "password" private_key = decode_keyfile_json( raw_keyfile_json=setting_user["keyfile_json"], - password=eoa_password.encode("utf-8") + password=eoa_password.encode("utf-8"), ) ContractUtils.send_transaction(tx, private_key) block_number_after = web3.eth.block_number - events = personal_info_contract.get_register_event(block_number_before, block_number_after) + events = personal_info_contract.get_register_event( + block_number_before, block_number_after + ) args = events[0]["args"] assert args["account_address"] == setting_user["address"] @@ -642,7 +725,6 @@ def test_normal_1(self, db): class TestGetModifyEvent: - ########################################################################### # Normal Case ########################################################################### @@ -655,7 +737,9 @@ def test_normal_1(self, db): # Set personal information data setting_user = config_eth_account("user2") rsa_password = "password" - rsa = RSA.importKey(personal_info_contract.issuer.rsa_public_key, passphrase=rsa_password) + rsa = RSA.importKey( + personal_info_contract.issuer.rsa_public_key, passphrase=rsa_password + ) cipher = PKCS1_OAEP.new(rsa) data = { "key_manager": "1234567890", @@ -665,21 +749,27 @@ def test_normal_1(self, db): "email": "sample@test.test", "birth": "19801231", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } - ciphertext = base64.encodebytes(cipher.encrypt(json.dumps(data).encode('utf-8'))) + ciphertext = base64.encodebytes( + cipher.encrypt(json.dumps(data).encode("utf-8")) + ) contract = personal_info_contract.personal_info_contract - tx = contract.functions.register(issuer["address"], ciphertext).build_transaction({ - "nonce": web3.eth.get_transaction_count(setting_user["address"]), - "from": setting_user["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0, - "chainId": CHAIN_ID - }) + tx = contract.functions.register( + issuer["address"], ciphertext + ).build_transaction( + { + "nonce": web3.eth.get_transaction_count(setting_user["address"]), + "from": setting_user["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + "chainId": CHAIN_ID, + } + ) eoa_password = "password" private_key = decode_keyfile_json( raw_keyfile_json=setting_user["keyfile_json"], - password=eoa_password.encode("utf-8") + password=eoa_password.encode("utf-8"), ) ContractUtils.send_transaction(tx, private_key) @@ -694,26 +784,34 @@ def test_normal_1(self, db): "email": "sample@test.test2", "birth": "19800101", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } - ciphertext = base64.encodebytes(cipher.encrypt(json.dumps(update_data).encode('utf-8'))) + ciphertext = base64.encodebytes( + cipher.encrypt(json.dumps(update_data).encode("utf-8")) + ) contract = personal_info_contract.personal_info_contract - tx = contract.functions.modify(setting_user["address"], ciphertext).build_transaction({ - "nonce": web3.eth.get_transaction_count(issuer["address"]), - "from": issuer["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0, - "chainId": CHAIN_ID - }) + tx = contract.functions.modify( + setting_user["address"], ciphertext + ).build_transaction( + { + "nonce": web3.eth.get_transaction_count(issuer["address"]), + "from": issuer["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + "chainId": CHAIN_ID, + } + ) private_key = decode_keyfile_json( raw_keyfile_json=issuer["keyfile_json"], - password=eoa_password.encode("utf-8") + password=eoa_password.encode("utf-8"), ) ContractUtils.send_transaction(tx, private_key) block_number_after = web3.eth.block_number - events = personal_info_contract.get_modify_event(block_number_before, block_number_after) + events = personal_info_contract.get_modify_event( + block_number_before, block_number_after + ) args = events[0]["args"] assert args["account_address"] == setting_user["address"] diff --git a/tests/model/blockchain/test_exchange_IbetExchangeInterface.py b/tests/model/blockchain/test_exchange_IbetExchangeInterface.py index 9a4eb4e6..790aa981 100644 --- a/tests/model/blockchain/test_exchange_IbetExchangeInterface.py +++ b/tests/model/blockchain/test_exchange_IbetExchangeInterface.py @@ -20,18 +20,9 @@ from web3 import Web3 from web3.middleware import geth_poa_middleware -from app.model.blockchain import ( - IbetStraightBondContract, - IbetExchangeInterface -) +from app.model.blockchain import IbetExchangeInterface, IbetStraightBondContract from app.utils.contract_utils import ContractUtils -from config import ( - CHAIN_ID, - TX_GAS_LIMIT, - WEB3_HTTP_PROVIDER, - ZERO_ADDRESS -) - +from config import CHAIN_ID, TX_GAS_LIMIT, WEB3_HTTP_PROVIDER, ZERO_ADDRESS from tests.account_config import config_eth_account web3 = Web3(Web3.HTTPProvider(WEB3_HTTP_PROVIDER)) @@ -42,7 +33,7 @@ def deploy_escrow_contract(): deployer = config_eth_account("user1") private_key = decode_keyfile_json( raw_keyfile_json=deployer["keyfile_json"], - password=deployer["password"].encode("utf-8") + password=deployer["password"].encode("utf-8"), ) # deploy @@ -50,37 +41,34 @@ def deploy_escrow_contract(): contract_name="EscrowStorage", args=[], deployer=deployer["address"], - private_key=private_key + private_key=private_key, ) escrow_contract_address, _, _ = ContractUtils.deploy_contract( contract_name="IbetEscrow", args=[escrow_storage_address], deployer=deployer["address"], - private_key=private_key + private_key=private_key, ) escrow_contract = ContractUtils.get_contract( - contract_name="IbetEscrow", - contract_address=escrow_contract_address + contract_name="IbetEscrow", contract_address=escrow_contract_address ) # update storage storage_contract = ContractUtils.get_contract( - contract_name="EscrowStorage", - contract_address=escrow_storage_address + contract_name="EscrowStorage", contract_address=escrow_storage_address ) tx = storage_contract.functions.upgradeVersion( escrow_contract_address - ).build_transaction({ - "chainId": CHAIN_ID, - "from": deployer["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) - ContractUtils.send_transaction( - transaction=tx, - private_key=private_key + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": deployer["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } ) + ContractUtils.send_transaction(transaction=tx, private_key=private_key) return escrow_contract @@ -89,62 +77,54 @@ def issue_bond_token(issuer: dict, exchange_address: str): issuer_address = issuer["address"] issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) # deploy token arguments = [ "テスト債券", "TEST", - 2 ** 256 - 1, + 2**256 - 1, 10000, "20211231", 10000, "20211231", "リターン内容", - "発行目的" + "発行目的", ] token_contract_address, abi, tx_hash = IbetStraightBondContract().create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) token_contract = ContractUtils.get_contract( - contract_name="IbetStraightBond", - contract_address=token_contract_address + contract_name="IbetStraightBond", contract_address=token_contract_address ) - tx = token_contract.functions.setTransferable( - True - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) - ContractUtils.send_transaction( - transaction=tx, - private_key=issuer_pk + tx = token_contract.functions.setTransferable(True).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } ) + ContractUtils.send_transaction(transaction=tx, private_key=issuer_pk) # set tradable exchange address tx = token_contract.functions.setTradableExchange( exchange_address - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) - ContractUtils.send_transaction( - transaction=tx, - private_key=issuer_pk + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } ) + ContractUtils.send_transaction(transaction=tx, private_key=issuer_pk) return token_contract class TestGetAccountBalance: - ########################################################################### # Normal Case ########################################################################### @@ -158,15 +138,14 @@ def test_normal_1(self, db): # deploy contract exchange_contract = deploy_escrow_contract() token_contract = issue_bond_token( - issuer=user1_account, - exchange_address=exchange_contract.address + issuer=user1_account, exchange_address=exchange_contract.address ) # test IbetExchangeInterface.get_account_balance exchange_interface = IbetExchangeInterface(exchange_contract.address) exchange_balance = exchange_interface.get_account_balance( account_address=user1_account["address"], - token_address=token_contract.address + token_address=token_contract.address, ) # assertion @@ -178,31 +157,28 @@ def test_normal_2(self, db): user1_account = config_eth_account("user1") user1_account_pk = decode_keyfile_json( raw_keyfile_json=user1_account["keyfile_json"], - password=user1_account["password"].encode("utf-8") + password=user1_account["password"].encode("utf-8"), ) user2_account = config_eth_account("user2") # deploy contract exchange_contract = deploy_escrow_contract() token_contract = issue_bond_token( - issuer=user1_account, - exchange_address=exchange_contract.address + issuer=user1_account, exchange_address=exchange_contract.address ) # transfer -> create balance tx = token_contract.functions.transfer( - exchange_contract.address, - 100 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": user1_account["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) - ContractUtils.send_transaction( - transaction=tx, - private_key=user1_account_pk + exchange_contract.address, 100 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": user1_account["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } ) + ContractUtils.send_transaction(transaction=tx, private_key=user1_account_pk) # create commitment tx = exchange_contract.functions.createEscrow( @@ -210,23 +186,22 @@ def test_normal_2(self, db): user2_account["address"], 30, user1_account["address"], - "test_data" - ).build_transaction({ - "chainId": CHAIN_ID, - "from": user1_account["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) - ContractUtils.send_transaction( - transaction=tx, - private_key=user1_account_pk + "test_data", + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": user1_account["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } ) + ContractUtils.send_transaction(transaction=tx, private_key=user1_account_pk) # test IbetExchangeInterface.get_account_balance exchange_interface = IbetExchangeInterface(exchange_contract.address) exchange_balance = exchange_interface.get_account_balance( account_address=user1_account["address"], - token_address=token_contract.address + token_address=token_contract.address, ) # assertion @@ -241,8 +216,7 @@ def test_normal_3(self, db): # test IbetExchangeInterface.get_account_balance exchange_interface = IbetExchangeInterface(ZERO_ADDRESS) exchange_balance = exchange_interface.get_account_balance( - account_address=user1_account["address"], - token_address=ZERO_ADDRESS + account_address=user1_account["address"], token_address=ZERO_ADDRESS ) # assertion diff --git a/tests/model/blockchain/test_exchange_IbetSecurityTokenEscrow.py b/tests/model/blockchain/test_exchange_IbetSecurityTokenEscrow.py index b44d704b..8c2d610b 100644 --- a/tests/model/blockchain/test_exchange_IbetSecurityTokenEscrow.py +++ b/tests/model/blockchain/test_exchange_IbetSecurityTokenEscrow.py @@ -16,30 +16,22 @@ SPDX-License-Identifier: Apache-2.0 """ -import pytest from unittest import mock from unittest.mock import MagicMock +import pytest from eth_keyfile import decode_keyfile_json from web3 import Web3 +from web3.exceptions import ContractLogicError, TimeExhausted from web3.middleware import geth_poa_middleware -from web3.exceptions import TimeExhausted, ContractLogicError -from app.model.blockchain import ( - IbetStraightBondContract, - IbetSecurityTokenEscrow -) +from app.exceptions import ContractRevertError, SendTransactionError +from app.model.blockchain import IbetSecurityTokenEscrow, IbetStraightBondContract from app.model.blockchain.tx_params.ibet_security_token_escrow import ( - ApproveTransferParams + ApproveTransferParams, ) from app.utils.contract_utils import ContractUtils -from config import ( - CHAIN_ID, - TX_GAS_LIMIT, - WEB3_HTTP_PROVIDER -) -from app.exceptions import SendTransactionError, ContractRevertError - +from config import CHAIN_ID, TX_GAS_LIMIT, WEB3_HTTP_PROVIDER from tests.account_config import config_eth_account web3 = Web3(Web3.HTTPProvider(WEB3_HTTP_PROVIDER)) @@ -50,7 +42,7 @@ def deploy_security_token_escrow_contract(): deployer = config_eth_account("user1") private_key = decode_keyfile_json( raw_keyfile_json=deployer["keyfile_json"], - password=deployer["password"].encode("utf-8") + password=deployer["password"].encode("utf-8"), ) # deploy @@ -58,37 +50,35 @@ def deploy_security_token_escrow_contract(): contract_name="EscrowStorage", args=[], deployer=deployer["address"], - private_key=private_key + private_key=private_key, ) escrow_contract_address, _, _ = ContractUtils.deploy_contract( contract_name="IbetSecurityTokenEscrow", args=[escrow_storage_address], deployer=deployer["address"], - private_key=private_key + private_key=private_key, ) escrow_contract = ContractUtils.get_contract( contract_name="IbetSecurityTokenEscrow", - contract_address=escrow_contract_address + contract_address=escrow_contract_address, ) # update storage storage_contract = ContractUtils.get_contract( - contract_name="EscrowStorage", - contract_address=escrow_storage_address + contract_name="EscrowStorage", contract_address=escrow_storage_address ) tx = storage_contract.functions.upgradeVersion( escrow_contract_address - ).build_transaction({ - "chainId": CHAIN_ID, - "from": deployer["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) - ContractUtils.send_transaction( - transaction=tx, - private_key=private_key + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": deployer["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } ) + ContractUtils.send_transaction(transaction=tx, private_key=private_key) return escrow_contract @@ -97,92 +87,81 @@ def issue_bond_token(issuer: dict, exchange_address: str): issuer_address = issuer["address"] issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) # deploy token arguments = [ "テスト債券", "TEST", - 2 ** 256 - 1, + 2**256 - 1, 10000, "20211231", 10000, "20211231", "リターン内容", - "発行目的" + "発行目的", ] token_contract_address, abi, tx_hash = IbetStraightBondContract().create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) token_contract = ContractUtils.get_contract( - contract_name="IbetStraightBond", - contract_address=token_contract_address + contract_name="IbetStraightBond", contract_address=token_contract_address ) - tx = token_contract.functions.setTransferable( - True - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) - ContractUtils.send_transaction( - transaction=tx, - private_key=issuer_pk + tx = token_contract.functions.setTransferable(True).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } ) + ContractUtils.send_transaction(transaction=tx, private_key=issuer_pk) # set tradable exchange address tx = token_contract.functions.setTradableExchange( exchange_address - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) - ContractUtils.send_transaction( - transaction=tx, - private_key=issuer_pk + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } ) + ContractUtils.send_transaction(transaction=tx, private_key=issuer_pk) # set personal info address personal_info_contract_address, _, _ = ContractUtils.deploy_contract( - "PersonalInfo", [], issuer_address, issuer_pk) + "PersonalInfo", [], issuer_address, issuer_pk + ) tx = token_contract.functions.setPersonalInfoAddress( personal_info_contract_address - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) - ContractUtils.send_transaction( - transaction=tx, - private_key=issuer_pk + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } ) + ContractUtils.send_transaction(transaction=tx, private_key=issuer_pk) # set transfer approval required - tx = token_contract.functions.setTransferApprovalRequired( - True - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) - ContractUtils.send_transaction( - transaction=tx, - private_key=issuer_pk + tx = token_contract.functions.setTransferApprovalRequired(True).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } ) + ContractUtils.send_transaction(transaction=tx, private_key=issuer_pk) return token_contract class TestApproveTransfer: - ########################################################################### # Normal Case ########################################################################### @@ -194,63 +173,63 @@ def test_normal_1(self, db): user1_account = config_eth_account("user1") user1_account_pk = decode_keyfile_json( raw_keyfile_json=user1_account["keyfile_json"], - password=user1_account["password"].encode("utf-8") + password=user1_account["password"].encode("utf-8"), ) user2_account = config_eth_account("user2") user2_account_pk = decode_keyfile_json( raw_keyfile_json=user2_account["keyfile_json"], - password=user2_account["password"].encode("utf-8") + password=user2_account["password"].encode("utf-8"), ) user3_account = config_eth_account("user3") # deploy contract escrow_contract = deploy_security_token_escrow_contract() token_contract = issue_bond_token( - issuer=user1_account, - exchange_address=escrow_contract.address + issuer=user1_account, exchange_address=escrow_contract.address ) # Pre transfer - personal_info_contract_address = token_contract.functions.personalInfoAddress().call() - personal_info_contract = ContractUtils.get_contract("PersonalInfo", personal_info_contract_address) + personal_info_contract_address = ( + token_contract.functions.personalInfoAddress().call() + ) + personal_info_contract = ContractUtils.get_contract( + "PersonalInfo", personal_info_contract_address + ) tx = personal_info_contract.functions.register( user1_account["address"], "test" - ).build_transaction({ - "chainId": CHAIN_ID, - "from": user2_account["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) - ContractUtils.send_transaction( - transaction=tx, - private_key=user2_account_pk + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": user2_account["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } ) + ContractUtils.send_transaction(transaction=tx, private_key=user2_account_pk) tx = token_contract.functions.transferFrom( user1_account["address"], user2_account["address"], 100 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": user1_account["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) - ContractUtils.send_transaction( - transaction=tx, - private_key=user1_account_pk + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": user1_account["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } ) + ContractUtils.send_transaction(transaction=tx, private_key=user1_account_pk) # Deposit escrow tx = token_contract.functions.transfer( escrow_contract.address, 100 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": user2_account["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) - ContractUtils.send_transaction( - transaction=tx, - private_key=user2_account_pk + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": user2_account["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } ) + ContractUtils.send_transaction(transaction=tx, private_key=user2_account_pk) # Apply for transfer tx = escrow_contract.functions.createEscrow( @@ -259,37 +238,35 @@ def test_normal_1(self, db): 10, user2_account["address"], "test", - "test" - ).build_transaction({ - "chainId": CHAIN_ID, - "from": user2_account["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) - ContractUtils.send_transaction( - transaction=tx, - private_key=user2_account_pk + "test", + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": user2_account["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } ) + ContractUtils.send_transaction(transaction=tx, private_key=user2_account_pk) # Finish Escrow latest_escrow_id = escrow_contract.functions.latestEscrowId().call() - tx = escrow_contract.functions.finishEscrow(latest_escrow_id).build_transaction({ - "chainId": CHAIN_ID, - "from": user2_account["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) - ContractUtils.send_transaction( - transaction=tx, - private_key=user2_account_pk + tx = escrow_contract.functions.finishEscrow(latest_escrow_id).build_transaction( + { + "chainId": CHAIN_ID, + "from": user2_account["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } ) + ContractUtils.send_transaction(transaction=tx, private_key=user2_account_pk) # test IbetSecurityTokenEscrow.approve_transfer security_token_escrow = IbetSecurityTokenEscrow(escrow_contract.address) tx_hash, tx_receipt = security_token_escrow.approve_transfer( data=ApproveTransferParams(escrow_id=1, data="test"), tx_from=user1_account["address"], - private_key=user1_account_pk + private_key=user1_account_pk, ) # assertion @@ -297,15 +274,13 @@ def test_normal_1(self, db): assert tx_receipt["status"] == 1 user2_balance = security_token_escrow.get_account_balance( - user2_account["address"], - token_contract.address + user2_account["address"], token_contract.address ) assert user2_balance["balance"] == 90 assert user2_balance["commitment"] == 0 user3_balance = security_token_escrow.get_account_balance( - user3_account["address"], - token_contract.address + user3_account["address"], token_contract.address ) assert user3_balance["balance"] == 10 assert user3_balance["commitment"] == 0 @@ -320,63 +295,63 @@ def test_error_1(self, db): user1_account = config_eth_account("user1") user1_account_pk = decode_keyfile_json( raw_keyfile_json=user1_account["keyfile_json"], - password=user1_account["password"].encode("utf-8") + password=user1_account["password"].encode("utf-8"), ) user2_account = config_eth_account("user2") user2_account_pk = decode_keyfile_json( raw_keyfile_json=user2_account["keyfile_json"], - password=user2_account["password"].encode("utf-8") + password=user2_account["password"].encode("utf-8"), ) user3_account = config_eth_account("user3") # deploy contract escrow_contract = deploy_security_token_escrow_contract() token_contract = issue_bond_token( - issuer=user1_account, - exchange_address=escrow_contract.address + issuer=user1_account, exchange_address=escrow_contract.address ) # Pre transfer - personal_info_contract_address = token_contract.functions.personalInfoAddress().call() - personal_info_contract = ContractUtils.get_contract("PersonalInfo", personal_info_contract_address) + personal_info_contract_address = ( + token_contract.functions.personalInfoAddress().call() + ) + personal_info_contract = ContractUtils.get_contract( + "PersonalInfo", personal_info_contract_address + ) tx = personal_info_contract.functions.register( user1_account["address"], "test" - ).build_transaction({ - "chainId": CHAIN_ID, - "from": user2_account["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) - ContractUtils.send_transaction( - transaction=tx, - private_key=user2_account_pk + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": user2_account["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } ) + ContractUtils.send_transaction(transaction=tx, private_key=user2_account_pk) tx = token_contract.functions.transferFrom( user1_account["address"], user2_account["address"], 100 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": user1_account["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) - ContractUtils.send_transaction( - transaction=tx, - private_key=user1_account_pk + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": user1_account["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } ) + ContractUtils.send_transaction(transaction=tx, private_key=user1_account_pk) # Deposit escrow tx = token_contract.functions.transfer( escrow_contract.address, 100 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": user2_account["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) - ContractUtils.send_transaction( - transaction=tx, - private_key=user2_account_pk + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": user2_account["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } ) + ContractUtils.send_transaction(transaction=tx, private_key=user2_account_pk) # Apply for transfer tx = escrow_contract.functions.createEscrow( @@ -385,35 +360,33 @@ def test_error_1(self, db): 10, user2_account["address"], "test", - "test" - ).build_transaction({ - "chainId": CHAIN_ID, - "from": user2_account["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) - ContractUtils.send_transaction( - transaction=tx, - private_key=user2_account_pk + "test", + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": user2_account["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } ) + ContractUtils.send_transaction(transaction=tx, private_key=user2_account_pk) # Finish Escrow latest_escrow_id = escrow_contract.functions.latestEscrowId().call() - tx = escrow_contract.functions.finishEscrow(latest_escrow_id).build_transaction({ - "chainId": CHAIN_ID, - "from": user2_account["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) - ContractUtils.send_transaction( - transaction=tx, - private_key=user2_account_pk + tx = escrow_contract.functions.finishEscrow(latest_escrow_id).build_transaction( + { + "chainId": CHAIN_ID, + "from": user2_account["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } ) + ContractUtils.send_transaction(transaction=tx, private_key=user2_account_pk) # mock InspectionMock = mock.patch( "web3.eth.Eth.wait_for_transaction_receipt", - MagicMock(side_effect=ConnectionError) + MagicMock(side_effect=ConnectionError), ) # test IbetSecurityTokenEscrow.approve_transfer with InspectionMock, pytest.raises(SendTransactionError) as exc_info: @@ -421,7 +394,7 @@ def test_error_1(self, db): security_token_escrow.approve_transfer( data=ApproveTransferParams(escrow_id=1, data="test"), tx_from=user1_account["address"], - private_key=user1_account_pk + private_key=user1_account_pk, ) cause = exc_info.value.args[0] @@ -433,25 +406,28 @@ def test_error_2(self, db): user1_account = config_eth_account("user1") user1_account_pk = decode_keyfile_json( raw_keyfile_json=user1_account["keyfile_json"], - password=user1_account["password"].encode("utf-8") + password=user1_account["password"].encode("utf-8"), ) # deploy contract exchange_contract = deploy_security_token_escrow_contract() _ = issue_bond_token( - issuer=user1_account, - exchange_address=exchange_contract.address + issuer=user1_account, exchange_address=exchange_contract.address ) # test IbetSecurityTokenEscrow.approve_transfer with pytest.raises(SendTransactionError) as exc_info: - with mock.patch("app.utils.contract_utils.ContractUtils.send_transaction", - MagicMock(side_effect=TimeExhausted("Timeout Error test"))): - security_token_escrow = IbetSecurityTokenEscrow(exchange_contract.address) + with mock.patch( + "app.utils.contract_utils.ContractUtils.send_transaction", + MagicMock(side_effect=TimeExhausted("Timeout Error test")), + ): + security_token_escrow = IbetSecurityTokenEscrow( + exchange_contract.address + ) security_token_escrow.approve_transfer( data=ApproveTransferParams(escrow_id=0, data="test"), tx_from=user1_account["address"], - private_key=user1_account_pk + private_key=user1_account_pk, ) cause = exc_info.value.args[0] @@ -465,14 +441,13 @@ def test_error_3(self, db): user1_account = config_eth_account("user1") user1_account_pk = decode_keyfile_json( raw_keyfile_json=user1_account["keyfile_json"], - password=user1_account["password"].encode("utf-8") + password=user1_account["password"].encode("utf-8"), ) # deploy contract exchange_contract = deploy_security_token_escrow_contract() _ = issue_bond_token( - issuer=user1_account, - exchange_address=exchange_contract.address + issuer=user1_account, exchange_address=exchange_contract.address ) # mock @@ -481,7 +456,7 @@ def test_error_3(self, db): # geth: ContractLogicError("execution reverted") InspectionMock = mock.patch( "web3.eth.Eth.call", - MagicMock(side_effect=ContractLogicError("execution reverted")) + MagicMock(side_effect=ContractLogicError("execution reverted")), ) # test IbetSecurityTokenEscrow.approve_transfer @@ -490,7 +465,7 @@ def test_error_3(self, db): security_token_escrow.approve_transfer( data=ApproveTransferParams(escrow_id=0, data="test"), tx_from=user1_account["address"], - private_key=user1_account_pk + private_key=user1_account_pk, ) assert exc_info.value.args[0] == "execution reverted" diff --git a/tests/model/blockchain/test_token_IbetShare.py b/tests/model/blockchain/test_token_IbetShare.py index 6b6dcb06..5472e325 100644 --- a/tests/model/blockchain/test_token_IbetShare.py +++ b/tests/model/blockchain/test_token_IbetShare.py @@ -16,51 +16,46 @@ SPDX-License-Identifier: Apache-2.0 """ -import pytest import time -from unittest import mock from binascii import Error from datetime import datetime, timedelta +from unittest import mock +from unittest.mock import MagicMock, patch -from pydantic.error_wrappers import ValidationError +import pytest from eth_keyfile import decode_keyfile_json -from unittest.mock import patch, MagicMock +from pydantic.error_wrappers import ValidationError from web3.exceptions import ( + ContractLogicError, InvalidAddress, TimeExhausted, TransactionNotFound, - ValidationError as Web3ValidationError, - ContractLogicError ) +from web3.exceptions import ValidationError as Web3ValidationError -from config import ZERO_ADDRESS, TOKEN_CACHE_TTL -from app.model.db import ( - TokenAttrUpdate, - TokenCache -) +from app.exceptions import ContractRevertError, SendTransactionError from app.model.blockchain import IbetShareContract from app.model.blockchain.tx_params.ibet_share import ( - UpdateParams, - TransferParams, AdditionalIssueParams, - RedeemParams, ApproveTransferParams, CancelTransferParams, + ForceUnlockPrams, LockParams, - ForceUnlockPrams + RedeemParams, + TransferParams, + UpdateParams, ) +from app.model.db import TokenAttrUpdate, TokenCache from app.utils.contract_utils import ContractUtils -from app.exceptions import SendTransactionError, ContractRevertError - +from config import TOKEN_CACHE_TTL, ZERO_ADDRESS from tests.account_config import config_eth_account from tests.utils.contract_utils import ( + IbetSecurityTokenContractTestUtils, PersonalInfoContractTestUtils, - IbetSecurityTokenContractTestUtils ) class TestCreate: - ########################################################################### # Normal Case ########################################################################### @@ -71,7 +66,7 @@ def test_normal_1(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # execute the function @@ -84,19 +79,16 @@ def test_normal_1(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() contract_address, abi, tx_hash = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # assertion share_contract = ContractUtils.get_contract( - contract_name="IbetShare", - contract_address=contract_address + contract_name="IbetShare", contract_address=contract_address ) _dividend_info = share_contract.functions.dividendInformation().call() assert share_contract.functions.owner().call() == issuer_address @@ -121,7 +113,7 @@ def test_error_1(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # execute the function @@ -129,9 +121,7 @@ def test_error_1(self, db): share_contract = IbetShareContract() with pytest.raises(SendTransactionError) as exc_info: share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # assertion @@ -145,7 +135,7 @@ def test_error_2(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # execute the function @@ -158,19 +148,19 @@ def test_error_2(self, db): 0, 0, 0, - "string" + "string", ] # invalid types share_contract = IbetShareContract() with pytest.raises(SendTransactionError) as exc_info: share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # assertion assert isinstance(exc_info.value.args[0], TypeError) - assert exc_info.match("One or more arguments could not be encoded to the necessary ABI type.") + assert exc_info.match( + "One or more arguments could not be encoded to the necessary ABI type." + ) # # Invalid argument type (tx_from) @@ -179,7 +169,7 @@ def test_error_3(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # execute the function @@ -192,19 +182,19 @@ def test_error_3(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() with pytest.raises(SendTransactionError) as exc_info: share_contract.create( args=arguments, tx_from=issuer_address[:-1], # short address - private_key=private_key + private_key=private_key, ) # assertion assert isinstance(exc_info.value.args[0], InvalidAddress) - assert exc_info.match("ENS name: \'.+\' is invalid.") + assert exc_info.match("ENS name: '.+' is invalid.") # # Invalid argument type (private_key) @@ -222,14 +212,12 @@ def test_error_4(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() with pytest.raises(SendTransactionError) as exc_info: share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key="some_private_key" + args=arguments, tx_from=issuer_address, private_key="some_private_key" ) # assertion @@ -243,7 +231,7 @@ def test_error_5(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # execute the function @@ -256,19 +244,15 @@ def test_error_5(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] contract_address, abi, tx_hash = IbetShareContract().create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) with pytest.raises(SendTransactionError) as exc_info: IbetShareContract(contract_address).create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # assertion @@ -276,7 +260,6 @@ def test_error_5(self, db): class TestGet: - ########################################################################### # Normal Case ########################################################################### @@ -290,7 +273,7 @@ def test_normal_1(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -303,13 +286,11 @@ def test_normal_1(self, db): "20211229", "20211230", "20221231", - 10001 + 10001, ] share_contract = IbetShareContract() contract_address, abi, tx_hash = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # execute the function @@ -342,13 +323,12 @@ def test_normal_1(self, db): # TOKEN_CACHE is True @mock.patch("app.model.blockchain.token.TOKEN_CACHE", True) def test_normal_2(self, db): - # prepare account test_account = config_eth_account("user1") issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -361,13 +341,11 @@ def test_normal_2(self, db): "20211229", "20211230", "20221231", - 10001 + 10001, ] share_contract = IbetShareContract() contract_address, abi, tx_hash = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # create cache @@ -392,13 +370,15 @@ def test_normal_2(self, db): "is_canceled": True, "dividends": 9.99, "dividend_record_date": "99991230", - "dividend_payment_date": "99991229" + "dividend_payment_date": "99991229", } token_cache = TokenCache() token_cache.token_address = contract_address token_cache.attributes = token_attr token_cache.cached_datetime = datetime.utcnow() - token_cache.expiration_datetime = datetime.utcnow() + timedelta(seconds=TOKEN_CACHE_TTL) + token_cache.expiration_datetime = datetime.utcnow() + timedelta( + seconds=TOKEN_CACHE_TTL + ) db.add(token_cache) db.commit() @@ -413,9 +393,15 @@ def test_normal_2(self, db): assert share_contract.total_supply == 999999 assert share_contract.contact_information == "test1" assert share_contract.privacy_policy == "test2" - assert share_contract.tradable_exchange_contract_address == "0x1234567890123456789012345678901234567890" + assert ( + share_contract.tradable_exchange_contract_address + == "0x1234567890123456789012345678901234567890" + ) assert share_contract.status is False - assert share_contract.personal_info_contract_address == "0x1234567890123456789012345678901234567891" + assert ( + share_contract.personal_info_contract_address + == "0x1234567890123456789012345678901234567891" + ) assert share_contract.transferable is True assert share_contract.is_offering is True assert share_contract.transfer_approval_required is True @@ -432,13 +418,12 @@ def test_normal_2(self, db): # TOKEN_CACHE is True, updated token attribute @mock.patch("app.model.blockchain.token.TOKEN_CACHE", True) def test_normal_3(self, db): - # prepare account test_account = config_eth_account("user1") issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -451,13 +436,11 @@ def test_normal_3(self, db): "20211229", "20211230", "20221231", - 10001 + 10001, ] share_contract = IbetShareContract() contract_address, abi, tx_hash = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # create cache @@ -482,13 +465,15 @@ def test_normal_3(self, db): "is_canceled": True, "dividends": 9.99, "dividend_record_date": "99991230", - "dividend_payment_date": "99991229" + "dividend_payment_date": "99991229", } token_cache = TokenCache() token_cache.token_address = contract_address token_cache.attributes = token_attr token_cache.cached_datetime = datetime.utcnow() - token_cache.expiration_datetime = datetime.utcnow() + timedelta(seconds=TOKEN_CACHE_TTL) + token_cache.expiration_datetime = datetime.utcnow() + timedelta( + seconds=TOKEN_CACHE_TTL + ) db.add(token_cache) db.commit() @@ -561,7 +546,6 @@ def test_normal_4(self, db): class TestUpdate: - ########################################################################### # Normal Case ########################################################################### @@ -573,7 +557,7 @@ def test_normal_1(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -586,13 +570,11 @@ def test_normal_1(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() contract_address, abi, tx_hash = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # update @@ -600,9 +582,7 @@ def test_normal_1(self, db): _add_data = UpdateParams(**_data) pre_datetime = datetime.utcnow() share_contract.update( - data=_add_data, - tx_from=issuer_address, - private_key=private_key + data=_add_data, tx_from=issuer_address, private_key=private_key ) # assertion @@ -635,7 +615,7 @@ def test_normal_2(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -648,13 +628,11 @@ def test_normal_2(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() contract_address, abi, tx_hash = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # update @@ -678,9 +656,7 @@ def test_normal_2(self, db): _add_data = UpdateParams(**_data) pre_datetime = datetime.utcnow() share_contract.update( - data=_add_data, - tx_from=issuer_address, - private_key=private_key + data=_add_data, tx_from=issuer_address, private_key=private_key ) # assertion @@ -689,8 +665,14 @@ def test_normal_2(self, db): assert share_contract.dividend_record_date == "20210930" assert share_contract.dividend_payment_date == "20211001" assert share_contract.dividends == 0.01 - assert share_contract.tradable_exchange_contract_address == "0x0000000000000000000000000000000000000001" - assert share_contract.personal_info_contract_address == "0x0000000000000000000000000000000000000002" + assert ( + share_contract.tradable_exchange_contract_address + == "0x0000000000000000000000000000000000000001" + ) + assert ( + share_contract.personal_info_contract_address + == "0x0000000000000000000000000000000000000002" + ) assert share_contract.transferable is False assert share_contract.status is False assert share_contract.is_offering is True @@ -725,16 +707,18 @@ def test_error_1(self, db): { "loc": ("dividends",), "msg": "dividends must be rounded to 13 decimal places", - "type": "value_error" - }, { + "type": "value_error", + }, + { "loc": ("tradable_exchange_contract_address",), "msg": "tradable_exchange_contract_address is not a valid address", - "type": "value_error" - }, { + "type": "value_error", + }, + { "loc": ("personal_info_contract_address",), "msg": "personal_info_contract_address is not a valid address", - "type": "value_error" - } + "type": "value_error", + }, ] # @@ -744,7 +728,7 @@ def test_error_2(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -757,28 +741,24 @@ def test_error_2(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() contract_address, abi, tx_hash = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # update - _data = { - "cancellation_date": "20211231" - } + _data = {"cancellation_date": "20211231"} _add_data = UpdateParams(**_data) with pytest.raises(SendTransactionError) as exc_info: share_contract.update( data=_add_data, tx_from="invalid_tx_from", - private_key="invalid private key" + private_key="invalid private key", ) assert isinstance(exc_info.value.args[0], InvalidAddress) - assert exc_info.match("ENS name: \'invalid_tx_from\' is invalid.") + assert exc_info.match("ENS name: 'invalid_tx_from' is invalid.") # # invalid private key @@ -787,7 +767,7 @@ def test_error_3(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -800,25 +780,21 @@ def test_error_3(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() contract_address, abi, tx_hash = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # update - _data = { - "cancellation_date": "20211231" - } + _data = {"cancellation_date": "20211231"} _add_data = UpdateParams(**_data) with pytest.raises(SendTransactionError): share_contract.update( data=_add_data, tx_from=issuer_address, - private_key="invalid private key" + private_key="invalid private key", ) # @@ -828,7 +804,7 @@ def test_error_4(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -841,32 +817,26 @@ def test_error_4(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() contract_address, abi, tx_hash = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # mock Web3_send_raw_transaction = patch( target="web3.eth.Eth.wait_for_transaction_receipt", - side_effect=TimeExhausted + side_effect=TimeExhausted, ) # update - _data = { - "cancellation_date": "20211231" - } + _data = {"cancellation_date": "20211231"} _add_data = UpdateParams(**_data) with Web3_send_raw_transaction: with pytest.raises(SendTransactionError) as exc_info: share_contract.update( - data=_add_data, - tx_from=issuer_address, - private_key=private_key + data=_add_data, tx_from=issuer_address, private_key=private_key ) # assertion @@ -879,7 +849,7 @@ def test_error_5(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -892,32 +862,26 @@ def test_error_5(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() contract_address, abi, tx_hash = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # mock Web3_send_raw_transaction = patch( target="web3.eth.Eth.wait_for_transaction_receipt", - side_effect=TransactionNotFound + side_effect=TransactionNotFound, ) # update - _data = { - "cancellation_date": "20211231" - } + _data = {"cancellation_date": "20211231"} _add_data = UpdateParams(**_data) with Web3_send_raw_transaction: with pytest.raises(SendTransactionError) as exc_info: share_contract.update( - data=_add_data, - tx_from=issuer_address, - private_key=private_key + data=_add_data, tx_from=issuer_address, private_key=private_key ) # assertion @@ -932,11 +896,11 @@ def test_error_6(self, db): user_address = user_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) user_private_key = decode_keyfile_json( raw_keyfile_json=user_account.get("keyfile_json"), - password=user_account.get("password").encode("utf-8") + password=user_account.get("password").encode("utf-8"), ) # deploy token @@ -949,13 +913,11 @@ def test_error_6(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() contract_address, abi, tx_hash = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # mock @@ -964,19 +926,15 @@ def test_error_6(self, db): # geth: ContractLogicError("execution reverted") InspectionMock = mock.patch( "web3.eth.Eth.call", - MagicMock(side_effect=ContractLogicError("execution reverted: 500001")) + MagicMock(side_effect=ContractLogicError("execution reverted: 500001")), ) # update - _data = { - "cancellation_date": "20211231" - } + _data = {"cancellation_date": "20211231"} _add_data = UpdateParams(**_data) with InspectionMock, pytest.raises(ContractRevertError) as exc_info: share_contract.update( - data=_add_data, - tx_from=user_address, - private_key=user_private_key + data=_add_data, tx_from=user_address, private_key=user_private_key ) # assertion @@ -984,7 +942,6 @@ def test_error_6(self, db): class TestTransfer: - ########################################################################### # Normal Case ########################################################################### @@ -995,7 +952,7 @@ def test_normal_1(self, db): from_address = from_account.get("address") from_private_key = decode_keyfile_json( raw_keyfile_json=from_account.get("keyfile_json"), - password=from_account.get("password").encode("utf-8") + password=from_account.get("password").encode("utf-8"), ) to_account = config_eth_account("user2") @@ -1011,26 +968,18 @@ def test_normal_1(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() share_contract.create( - args=arguments, - tx_from=from_address, - private_key=from_private_key + args=arguments, tx_from=from_address, private_key=from_private_key ) # transfer - _data = { - "from_address": from_address, - "to_address": to_address, - "amount": 10 - } + _data = {"from_address": from_address, "to_address": to_address, "amount": 10} _transfer_data = TransferParams(**_data) share_contract.transfer( - data=_transfer_data, - tx_from=from_address, - private_key=from_private_key + data=_transfer_data, tx_from=from_address, private_key=from_private_key ) # assertion @@ -1054,16 +1003,18 @@ def test_error_1(self, db): { "loc": ("from_address",), "msg": "field required", - "type": "value_error.missing" - }, { + "type": "value_error.missing", + }, + { "loc": ("to_address",), "msg": "field required", - "type": "value_error.missing" - }, { + "type": "value_error.missing", + }, + { "loc": ("amount",), "msg": "field required", - "type": "value_error.missing" - } + "type": "value_error.missing", + }, ] # @@ -1073,7 +1024,7 @@ def test_error_2(self, db): _data = { "from_address": "invalid from_address", "to_address": "invalid to_address", - "amount": 0 + "amount": 0, } with pytest.raises(ValidationError) as exc_info: TransferParams(**_data) @@ -1081,19 +1032,19 @@ def test_error_2(self, db): { "loc": ("from_address",), "msg": "from_address is not a valid address", - "type": "value_error" + "type": "value_error", }, { "loc": ("to_address",), "msg": "to_address is not a valid address", - "type": "value_error" + "type": "value_error", }, { - 'loc': ('amount',), - 'msg': 'ensure this value is greater than 0', - 'type': 'value_error.number.not_gt', - 'ctx': {'limit_value': 0} - } + "loc": ("amount",), + "msg": "ensure this value is greater than 0", + "type": "value_error.number.not_gt", + "ctx": {"limit_value": 0}, + }, ] # @@ -1103,7 +1054,7 @@ def test_error_3(self, db): from_address = from_account.get("address") from_private_key = decode_keyfile_json( raw_keyfile_json=from_account.get("keyfile_json"), - password=from_account.get("password").encode("utf-8") + password=from_account.get("password").encode("utf-8"), ) to_account = config_eth_account("user2") @@ -1119,30 +1070,24 @@ def test_error_3(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() share_contract.create( - args=arguments, - tx_from=from_address, - private_key=from_private_key + args=arguments, tx_from=from_address, private_key=from_private_key ) # transfer - _data = { - "from_address": from_address, - "to_address": to_address, - "amount": 10 - } + _data = {"from_address": from_address, "to_address": to_address, "amount": 10} _transfer_data = TransferParams(**_data) with pytest.raises(SendTransactionError) as exc_info: share_contract.transfer( data=_transfer_data, tx_from="invalid_tx_from", - private_key=from_private_key + private_key=from_private_key, ) assert isinstance(exc_info.value.args[0], InvalidAddress) - assert exc_info.match("ENS name: \'invalid_tx_from\' is invalid.") + assert exc_info.match("ENS name: 'invalid_tx_from' is invalid.") # # invalid private key @@ -1151,7 +1096,7 @@ def test_error_4(self, db): from_address = from_account.get("address") from_private_key = decode_keyfile_json( raw_keyfile_json=from_account.get("keyfile_json"), - password=from_account.get("password").encode("utf-8") + password=from_account.get("password").encode("utf-8"), ) to_account = config_eth_account("user2") @@ -1167,27 +1112,21 @@ def test_error_4(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() share_contract.create( - args=arguments, - tx_from=from_address, - private_key=from_private_key + args=arguments, tx_from=from_address, private_key=from_private_key ) # transfer - _data = { - "from_address": from_address, - "to_address": to_address, - "amount": 10 - } + _data = {"from_address": from_address, "to_address": to_address, "amount": 10} _transfer_data = TransferParams(**_data) with pytest.raises(SendTransactionError): share_contract.transfer( data=_transfer_data, tx_from=from_address, - private_key="invalid_private_key" + private_key="invalid_private_key", ) # @@ -1197,7 +1136,7 @@ def test_error_5(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) to_account = config_eth_account("user2") @@ -1213,34 +1152,26 @@ def test_error_5(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # mock Web3_send_raw_transaction = patch( target="web3.eth.Eth.wait_for_transaction_receipt", - side_effect=TimeExhausted + side_effect=TimeExhausted, ) # transfer - _data = { - "from_address": issuer_address, - "to_address": to_address, - "amount": 10 - } + _data = {"from_address": issuer_address, "to_address": to_address, "amount": 10} _transfer_data = TransferParams(**_data) with Web3_send_raw_transaction: with pytest.raises(SendTransactionError) as exc_info: share_contract.transfer( - data=_transfer_data, - tx_from=issuer_address, - private_key=private_key + data=_transfer_data, tx_from=issuer_address, private_key=private_key ) assert isinstance(exc_info.value.args[0], TimeExhausted) @@ -1251,7 +1182,7 @@ def test_error_6(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) to_account = config_eth_account("user2") @@ -1267,34 +1198,26 @@ def test_error_6(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # mock Web3_send_raw_transaction = patch( target="web3.eth.Eth.wait_for_transaction_receipt", - side_effect=TransactionNotFound + side_effect=TransactionNotFound, ) # transfer - _data = { - "from_address": issuer_address, - "to_address": to_address, - "amount": 10 - } + _data = {"from_address": issuer_address, "to_address": to_address, "amount": 10} _transfer_data = TransferParams(**_data) with Web3_send_raw_transaction: with pytest.raises(SendTransactionError) as exc_info: share_contract.transfer( - data=_transfer_data, - tx_from=issuer_address, - private_key=private_key + data=_transfer_data, tx_from=issuer_address, private_key=private_key ) assert isinstance(exc_info.value.args[0], TransactionNotFound) @@ -1305,7 +1228,7 @@ def test_error_7(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) to_account = config_eth_account("user2") @@ -1321,20 +1244,18 @@ def test_error_7(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # transfer with insufficient balance _data = { "from_address": issuer_address, "to_address": to_address, - "amount": 10000000 + "amount": 10000000, } _transfer_data = TransferParams(**_data) @@ -1344,14 +1265,12 @@ def test_error_7(self, db): # geth: ContractLogicError("execution reverted: ") InspectionMock = mock.patch( "web3.eth.Eth.call", - MagicMock(side_effect=ContractLogicError("execution reverted: 110401")) + MagicMock(side_effect=ContractLogicError("execution reverted: 110401")), ) with InspectionMock, pytest.raises(ContractRevertError) as exc_info: share_contract.transfer( - data=_transfer_data, - tx_from=issuer_address, - private_key=private_key + data=_transfer_data, tx_from=issuer_address, private_key=private_key ) # assertion @@ -1359,7 +1278,6 @@ def test_error_7(self, db): class TestAdditionalIssue: - ########################################################################### # Normal Case ########################################################################### @@ -1370,7 +1288,7 @@ def test_normal_1(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -1383,26 +1301,19 @@ def test_normal_1(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() contract_address, abi, tx_hash = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # additional issue - _data = { - "account_address": issuer_address, - "amount": 10 - } + _data = {"account_address": issuer_address, "amount": 10} _add_data = AdditionalIssueParams(**_data) pre_datetime = datetime.utcnow() share_contract.additional_issue( - data=_add_data, - tx_from=issuer_address, - private_key=private_key + data=_add_data, tx_from=issuer_address, private_key=private_key ) # assertion @@ -1431,12 +1342,13 @@ def test_error_1(self, db): { "loc": ("account_address",), "msg": "field required", - "type": "value_error.missing" - }, { + "type": "value_error.missing", + }, + { "loc": ("amount",), "msg": "field required", - "type": "value_error.missing" - } + "type": "value_error.missing", + }, ] # @@ -1445,10 +1357,7 @@ def test_error_2(self, db): test_account = config_eth_account("user1") issuer_address = test_account.get("address") - _data = { - "account_address": issuer_address[:-1], # short address - "amount": 0 - } + _data = {"account_address": issuer_address[:-1], "amount": 0} # short address with pytest.raises(ValidationError) as exc_info: AdditionalIssueParams(**_data) @@ -1456,14 +1365,14 @@ def test_error_2(self, db): { "loc": ("account_address",), "msg": "account_address is not a valid address", - "type": "value_error" + "type": "value_error", }, { - 'loc': ('amount',), - 'msg': 'ensure this value is greater than 0', - 'type': 'value_error.number.not_gt', - 'ctx': {'limit_value': 0} - } + "loc": ("amount",), + "msg": "ensure this value is greater than 0", + "type": "value_error.number.not_gt", + "ctx": {"limit_value": 0}, + }, ] # @@ -1473,7 +1382,7 @@ def test_error_3(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -1486,29 +1395,22 @@ def test_error_3(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # additional issue - _data = { - "account_address": issuer_address, - "amount": 10 - } + _data = {"account_address": issuer_address, "amount": 10} _add_data = AdditionalIssueParams(**_data) with pytest.raises(SendTransactionError) as exc_info: share_contract.additional_issue( - data=_add_data, - tx_from="invalid_tx_from", - private_key=private_key + data=_add_data, tx_from="invalid_tx_from", private_key=private_key ) assert isinstance(exc_info.value.args[0], InvalidAddress) - assert exc_info.match("ENS name: \'invalid_tx_from\' is invalid.") + assert exc_info.match("ENS name: 'invalid_tx_from' is invalid.") # # invalid private key @@ -1517,7 +1419,7 @@ def test_error_4(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -1530,26 +1432,21 @@ def test_error_4(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # additional issue - _data = { - "account_address": issuer_address, - "amount": 10 - } + _data = {"account_address": issuer_address, "amount": 10} _add_data = AdditionalIssueParams(**_data) with pytest.raises(SendTransactionError) as exc_info: share_contract.additional_issue( data=_add_data, tx_from=test_account.get("address"), - private_key="invalid_private_key" + private_key="invalid_private_key", ) assert isinstance(exc_info.value.args[0], Error) assert exc_info.match("Non-hexadecimal digit found") @@ -1561,7 +1458,7 @@ def test_error_5(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -1574,33 +1471,26 @@ def test_error_5(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # mock Web3_send_raw_transaction = patch( target="web3.eth.Eth.wait_for_transaction_receipt", - side_effect=TimeExhausted + side_effect=TimeExhausted, ) # additional issue - _data = { - "account_address": issuer_address, - "amount": 10 - } + _data = {"account_address": issuer_address, "amount": 10} _add_data = AdditionalIssueParams(**_data) with Web3_send_raw_transaction: with pytest.raises(SendTransactionError) as exc_info: share_contract.additional_issue( - data=_add_data, - tx_from=issuer_address, - private_key=private_key + data=_add_data, tx_from=issuer_address, private_key=private_key ) assert exc_info.type(SendTransactionError(TimeExhausted)) @@ -1611,7 +1501,7 @@ def test_error_6(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -1624,33 +1514,26 @@ def test_error_6(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # mock Web3_send_raw_transaction = patch( target="web3.eth.Eth.wait_for_transaction_receipt", - side_effect=TransactionNotFound + side_effect=TransactionNotFound, ) # additional issue - _data = { - "account_address": issuer_address, - "amount": 10 - } + _data = {"account_address": issuer_address, "amount": 10} _add_data = AdditionalIssueParams(**_data) with Web3_send_raw_transaction: with pytest.raises(SendTransactionError) as exc_info: share_contract.additional_issue( - data=_add_data, - tx_from=issuer_address, - private_key=private_key + data=_add_data, tx_from=issuer_address, private_key=private_key ) assert isinstance(exc_info.value.args[0], TransactionNotFound) @@ -1663,11 +1546,11 @@ def test_error_7(self, db): user_address = user_account.get("address") issuer_private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) user_private_key = decode_keyfile_json( raw_keyfile_json=user_account.get("keyfile_json"), - password=user_account.get("password").encode("utf-8") + password=user_account.get("password").encode("utf-8"), ) # deploy token @@ -1680,20 +1563,15 @@ def test_error_7(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_private_key + args=arguments, tx_from=issuer_address, private_key=issuer_private_key ) # additional issue - _data = { - "account_address": issuer_address, - "amount": 10 - } + _data = {"account_address": issuer_address, "amount": 10} _add_data = AdditionalIssueParams(**_data) pre_datetime = datetime.utcnow() @@ -1703,14 +1581,12 @@ def test_error_7(self, db): # geth: ContractLogicError("execution reverted") InspectionMock = mock.patch( "web3.eth.Eth.call", - MagicMock(side_effect=ContractLogicError("execution reverted: 500001")) + MagicMock(side_effect=ContractLogicError("execution reverted: 500001")), ) with InspectionMock, pytest.raises(ContractRevertError) as exc_info: share_contract.additional_issue( - data=_add_data, - tx_from=user_address, - private_key=user_private_key + data=_add_data, tx_from=user_address, private_key=user_private_key ) # assertion @@ -1718,7 +1594,6 @@ def test_error_7(self, db): class TestRedeem: - ########################################################################### # Normal Case ########################################################################### @@ -1729,7 +1604,7 @@ def test_normal_1(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -1742,26 +1617,19 @@ def test_normal_1(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() contract_address, abi, tx_hash = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # redeem - _data = { - "account_address": issuer_address, - "amount": 10 - } + _data = {"account_address": issuer_address, "amount": 10} _add_data = RedeemParams(**_data) pre_datetime = datetime.utcnow() share_contract.redeem( - data=_add_data, - tx_from=issuer_address, - private_key=private_key + data=_add_data, tx_from=issuer_address, private_key=private_key ) # assertion @@ -1790,12 +1658,13 @@ def test_error_1(self, db): { "loc": ("account_address",), "msg": "field required", - "type": "value_error.missing" - }, { + "type": "value_error.missing", + }, + { "loc": ("amount",), "msg": "field required", - "type": "value_error.missing" - } + "type": "value_error.missing", + }, ] # @@ -1804,10 +1673,7 @@ def test_error_2(self, db): test_account = config_eth_account("user1") issuer_address = test_account.get("address") - _data = { - "account_address": issuer_address[:-1], # short address - "amount": 0 - } + _data = {"account_address": issuer_address[:-1], "amount": 0} # short address with pytest.raises(ValidationError) as exc_info: RedeemParams(**_data) @@ -1815,14 +1681,14 @@ def test_error_2(self, db): { "loc": ("account_address",), "msg": "account_address is not a valid address", - "type": "value_error" + "type": "value_error", }, { - 'loc': ('amount',), - 'msg': 'ensure this value is greater than 0', - 'type': 'value_error.number.not_gt', - 'ctx': {'limit_value': 0} - } + "loc": ("amount",), + "msg": "ensure this value is greater than 0", + "type": "value_error.number.not_gt", + "ctx": {"limit_value": 0}, + }, ] # @@ -1832,7 +1698,7 @@ def test_error_3(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -1845,29 +1711,22 @@ def test_error_3(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() contract_address, abi, tx_hash = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # redeem - _data = { - "account_address": issuer_address, - "amount": 10 - } + _data = {"account_address": issuer_address, "amount": 10} _add_data = RedeemParams(**_data) with pytest.raises(SendTransactionError) as exc_info: share_contract.redeem( - data=_add_data, - tx_from="invalid_tx_from", - private_key=private_key + data=_add_data, tx_from="invalid_tx_from", private_key=private_key ) assert isinstance(exc_info.value.args[0], InvalidAddress) - assert exc_info.match("ENS name: \'invalid_tx_from\' is invalid.") + assert exc_info.match("ENS name: 'invalid_tx_from' is invalid.") # # invalid private key @@ -1876,7 +1735,7 @@ def test_error_4(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -1889,26 +1748,21 @@ def test_error_4(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() contract_address, abi, tx_hash = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # redeem - _data = { - "account_address": issuer_address, - "amount": 10 - } + _data = {"account_address": issuer_address, "amount": 10} _add_data = RedeemParams(**_data) with pytest.raises(SendTransactionError) as exc_info: share_contract.redeem( data=_add_data, tx_from=test_account.get("address"), - private_key="invalid_private_key" + private_key="invalid_private_key", ) assert isinstance(exc_info.value.args[0], Error) assert exc_info.match("Non-hexadecimal digit found") @@ -1920,7 +1774,7 @@ def test_error_5(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -1933,33 +1787,26 @@ def test_error_5(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() contract_address, abi, tx_hash = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # mock Web3_send_raw_transaction = patch( target="web3.eth.Eth.wait_for_transaction_receipt", - side_effect=TimeExhausted + side_effect=TimeExhausted, ) # redeem - _data = { - "account_address": issuer_address, - "amount": 10 - } + _data = {"account_address": issuer_address, "amount": 10} _add_data = RedeemParams(**_data) with Web3_send_raw_transaction: with pytest.raises(SendTransactionError) as exc_info: share_contract.redeem( - data=_add_data, - tx_from=issuer_address, - private_key=private_key + data=_add_data, tx_from=issuer_address, private_key=private_key ) assert exc_info.type(SendTransactionError(TimeExhausted)) @@ -1970,7 +1817,7 @@ def test_error_6(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -1983,33 +1830,26 @@ def test_error_6(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() contract_address, abi, tx_hash = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # mock Web3_send_raw_transaction = patch( target="web3.eth.Eth.wait_for_transaction_receipt", - side_effect=TransactionNotFound + side_effect=TransactionNotFound, ) # redeem - _data = { - "account_address": issuer_address, - "amount": 10 - } + _data = {"account_address": issuer_address, "amount": 10} _add_data = RedeemParams(**_data) with Web3_send_raw_transaction: with pytest.raises(SendTransactionError) as exc_info: share_contract.redeem( - data=_add_data, - tx_from=issuer_address, - private_key=private_key + data=_add_data, tx_from=issuer_address, private_key=private_key ) assert isinstance(exc_info.value.args[0], TransactionNotFound) @@ -2020,7 +1860,7 @@ def test_error_7(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -2033,20 +1873,15 @@ def test_error_7(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() contract_address, abi, tx_hash = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # redeem - _data = { - "account_address": issuer_address, - "amount": 100_000_000 - } + _data = {"account_address": issuer_address, "amount": 100_000_000} _add_data = RedeemParams(**_data) pre_datetime = datetime.utcnow() @@ -2056,22 +1891,22 @@ def test_error_7(self, db): # geth: ContractLogicError("execution reverted") InspectionMock = mock.patch( "web3.eth.Eth.call", - MagicMock(side_effect=ContractLogicError("execution reverted: 111102")) + MagicMock(side_effect=ContractLogicError("execution reverted: 111102")), ) with InspectionMock, pytest.raises(ContractRevertError) as exc_info: share_contract.redeem( - data=_add_data, - tx_from=issuer_address, - private_key=private_key + data=_add_data, tx_from=issuer_address, private_key=private_key ) # assertion - assert exc_info.value.args[0] == "Redeem amount is less than target address balance." + assert ( + exc_info.value.args[0] + == "Redeem amount is less than target address balance." + ) class TestGetAccountBalance: - ########################################################################### # Normal Case ########################################################################### @@ -2082,7 +1917,7 @@ def test_normal_1(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -2095,13 +1930,11 @@ def test_normal_1(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() contract_address, abi, tx_hash = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # assertion @@ -2132,7 +1965,7 @@ def test_error_1(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -2145,20 +1978,16 @@ def test_error_1(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # execute the function with pytest.raises(Web3ValidationError): - share_contract.get_account_balance( - issuer_address[:-1] # short - ) + share_contract.get_account_balance(issuer_address[:-1]) # short class TestCheckAttrUpdate: @@ -2236,7 +2065,7 @@ class TestRecordAttrUpdate: # # data not exists - @pytest.mark.freeze_time('2021-04-27 12:34:56') + @pytest.mark.freeze_time("2021-04-27 12:34:56") def test_normal_1(self, db): # Test share_contract = IbetShareContract(self.token_address) @@ -2251,7 +2080,6 @@ def test_normal_1(self, db): # # data exists def test_normal_2(self, db, freezer): - # prepare data _update = TokenAttrUpdate() _update.token_address = self.token_address @@ -2260,7 +2088,7 @@ def test_normal_2(self, db, freezer): db.commit() # Mock datetime - freezer.move_to('2021-04-27 12:34:56') + freezer.move_to("2021-04-27 12:34:56") # Test share_contract = IbetShareContract(self.token_address) @@ -2278,7 +2106,6 @@ def test_normal_2(self, db, freezer): class TestApproveTransfer: - ########################################################################### # Normal Case ########################################################################### @@ -2289,21 +2116,21 @@ def test_normal_1(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) to_account = config_eth_account("user2") to_address = to_account.get("address") to_pk = decode_keyfile_json( raw_keyfile_json=to_account.get("keyfile_json"), - password=to_account.get("password").encode("utf-8") + password=to_account.get("password").encode("utf-8"), ) deployer = config_eth_account("user3") deployer_address = deployer.get("address") deployer_pk = decode_keyfile_json( raw_keyfile_json=deployer.get("keyfile_json"), - password=deployer.get("password").encode("utf-8") + password=deployer.get("password").encode("utf-8"), ) # deploy new personal info contract (from deployer) @@ -2311,7 +2138,7 @@ def test_normal_1(self, db): contract_name="PersonalInfo", args=[], deployer=deployer_address, - private_key=deployer_pk + private_key=deployer_pk, ) # deploy ibet share token (from issuer) @@ -2324,25 +2151,23 @@ def test_normal_1(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() token_address, _, _ = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # update token (from issuer) update_data = { "personal_info_contract_address": personal_info_contract_address, "transfer_approval_required": True, - "transferable": True + "transferable": True, } share_contract.update( data=UpdateParams(**update_data), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) # register personal info (to_account) @@ -2350,7 +2175,7 @@ def test_normal_1(self, db): contract_address=personal_info_contract_address, tx_from=to_address, private_key=to_pk, - args=[issuer_address, "test_personal_info"] + args=[issuer_address, "test_personal_info"], ) # apply transfer (from issuer) @@ -2358,18 +2183,15 @@ def test_normal_1(self, db): contract_address=token_address, tx_from=issuer_address, private_key=issuer_pk, - args=[to_address, 10, "test_data"] + args=[to_address, 10, "test_data"], ) # approve transfer (from issuer) - approve_data = { - "application_id": 0, - "data": "approve transfer test" - } + approve_data = {"application_id": 0, "data": "approve transfer test"} tx_hash, tx_receipt = share_contract.approve_transfer( data=ApproveTransferParams(**approve_data), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) # assertion @@ -2377,8 +2199,7 @@ def test_normal_1(self, db): assert tx_receipt["status"] == 1 share_token = ContractUtils.get_contract( - contract_name="IbetShare", - contract_address=token_address + contract_name="IbetShare", contract_address=token_address ) applications = share_token.functions.applicationsForTransfer(0).call() assert applications[0] == issuer_address @@ -2409,14 +2230,11 @@ def test_error_1(self, db): assert ex_info.value.errors() == [ { - 'loc': ('application_id',), - 'msg': 'value is not a valid integer', - 'type': 'type_error.integer' - }, { - 'loc': ('data',), - 'msg': 'field required', - 'type': 'value_error.missing' - } + "loc": ("application_id",), + "msg": "value is not a valid integer", + "type": "type_error.integer", + }, + {"loc": ("data",), "msg": "field required", "type": "value_error.missing"}, ] # @@ -2426,23 +2244,22 @@ def test_error_2(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # Transfer approve - approve_data = { - "application_id": 0, - "data": "test_data" - } + approve_data = {"application_id": 0, "data": "test_data"} _approve_transfer_data = ApproveTransferParams(**approve_data) share_contract = IbetShareContract("not address") with pytest.raises(SendTransactionError) as ex_info: share_contract.approve_transfer( data=_approve_transfer_data, tx_from=issuer_address, - private_key=private_key + private_key=private_key, ) - assert ex_info.match("when sending a str, it must be a hex string. Got: 'not address'") + assert ex_info.match( + "when sending a str, it must be a hex string. Got: 'not address'" + ) # # invalid issuer_address : does not exists @@ -2451,7 +2268,7 @@ def test_error_3(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -2464,26 +2281,21 @@ def test_error_3(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() contract_address, abi, tx_hash = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # Transfer approve - approve_data = { - "application_id": 0, - "data": "test_data" - } + approve_data = {"application_id": 0, "data": "test_data"} _approve_transfer_data = ApproveTransferParams(**approve_data) with pytest.raises(SendTransactionError) as ex_info: share_contract.approve_transfer( data=_approve_transfer_data, tx_from=issuer_address[:-1], - private_key=private_key + private_key=private_key, ) assert ex_info.match(f"ENS name: '{issuer_address[:-1]}' is invalid.") @@ -2494,7 +2306,7 @@ def test_error_4(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -2507,27 +2319,22 @@ def test_error_4(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() contract_address, abi, tx_hash = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # Transfer approve - approve_data = { - "application_id": 0, - "data": "test_data" - } + approve_data = {"application_id": 0, "data": "test_data"} _approve_transfer_data = ApproveTransferParams(**approve_data) with pytest.raises(SendTransactionError) as ex_info: share_contract.approve_transfer( data=_approve_transfer_data, tx_from=issuer_address, - private_key="dummy-private" + private_key="dummy-private", ) assert ex_info.match("Non-hexadecimal digit found") @@ -2538,21 +2345,21 @@ def test_error_5(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) to_account = config_eth_account("user2") to_address = to_account.get("address") to_pk = decode_keyfile_json( raw_keyfile_json=to_account.get("keyfile_json"), - password=to_account.get("password").encode("utf-8") + password=to_account.get("password").encode("utf-8"), ) deployer = config_eth_account("user3") deployer_address = deployer.get("address") deployer_pk = decode_keyfile_json( raw_keyfile_json=deployer.get("keyfile_json"), - password=deployer.get("password").encode("utf-8") + password=deployer.get("password").encode("utf-8"), ) # deploy new personal info contract (from deployer) @@ -2560,7 +2367,7 @@ def test_error_5(self, db): contract_name="PersonalInfo", args=[], deployer=deployer_address, - private_key=deployer_pk + private_key=deployer_pk, ) # deploy token @@ -2573,25 +2380,23 @@ def test_error_5(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() token_address, _, _ = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # update token (from issuer) update_data = { "personal_info_contract_address": personal_info_contract_address, "transfer_approval_required": True, - "transferable": True + "transferable": True, } share_contract.update( data=UpdateParams(**update_data), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) # register personal info (to_account) @@ -2599,7 +2404,7 @@ def test_error_5(self, db): contract_address=personal_info_contract_address, tx_from=to_address, private_key=to_pk, - args=[issuer_address, "test_personal_info"] + args=[issuer_address, "test_personal_info"], ) # apply transfer (from issuer) @@ -2607,18 +2412,15 @@ def test_error_5(self, db): contract_address=token_address, tx_from=issuer_address, private_key=issuer_pk, - args=[to_address, 10, "test_data"] + args=[to_address, 10, "test_data"], ) # approve transfer (from issuer) - approve_data = { - "application_id": 0, - "data": "approve transfer test" - } + approve_data = {"application_id": 0, "data": "approve transfer test"} share_contract.approve_transfer( data=ApproveTransferParams(**approve_data), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) # Then send approveTransfer transaction again. @@ -2630,14 +2432,14 @@ def test_error_5(self, db): # geth: ContractLogicError("execution reverted") InspectionMock = mock.patch( "web3.eth.Eth.call", - MagicMock(side_effect=ContractLogicError("execution reverted: 120902")) + MagicMock(side_effect=ContractLogicError("execution reverted: 120902")), ) with InspectionMock, pytest.raises(ContractRevertError) as exc_info: share_contract.approve_transfer( data=ApproveTransferParams(**approve_data), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) # assertion @@ -2645,7 +2447,6 @@ def test_error_5(self, db): class TestCancelTransfer: - ########################################################################### # Normal Case ########################################################################### @@ -2656,21 +2457,21 @@ def test_normal_1(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) to_account = config_eth_account("user2") to_address = to_account.get("address") to_pk = decode_keyfile_json( raw_keyfile_json=to_account.get("keyfile_json"), - password=to_account.get("password").encode("utf-8") + password=to_account.get("password").encode("utf-8"), ) deployer = config_eth_account("user3") deployer_address = deployer.get("address") deployer_pk = decode_keyfile_json( raw_keyfile_json=deployer.get("keyfile_json"), - password=deployer.get("password").encode("utf-8") + password=deployer.get("password").encode("utf-8"), ) # deploy new personal info contract (from deployer) @@ -2678,7 +2479,7 @@ def test_normal_1(self, db): contract_name="PersonalInfo", args=[], deployer=deployer_address, - private_key=deployer_pk + private_key=deployer_pk, ) # deploy ibet share token (from issuer) @@ -2691,25 +2492,23 @@ def test_normal_1(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() token_address, _, _ = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # update token (from issuer) update_data = { "personal_info_contract_address": personal_info_contract_address, "transfer_approval_required": True, - "transferable": True + "transferable": True, } share_contract.update( data=UpdateParams(**update_data), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) # register personal info (to_account) @@ -2717,7 +2516,7 @@ def test_normal_1(self, db): contract_address=personal_info_contract_address, tx_from=to_address, private_key=to_pk, - args=[issuer_address, "test_personal_info"] + args=[issuer_address, "test_personal_info"], ) # apply transfer (from issuer) @@ -2725,28 +2524,22 @@ def test_normal_1(self, db): contract_address=token_address, tx_from=issuer_address, private_key=issuer_pk, - args=[to_address, 10, "test_data"] + args=[to_address, 10, "test_data"], ) # cancel transfer (from issuer) - cancel_data = { - "application_id": 0, - "data": "approve transfer test" - } + cancel_data = {"application_id": 0, "data": "approve transfer test"} _approve_transfer_data = CancelTransferParams(**cancel_data) tx_hash, tx_receipt = share_contract.cancel_transfer( - data=_approve_transfer_data, - tx_from=issuer_address, - private_key=issuer_pk + data=_approve_transfer_data, tx_from=issuer_address, private_key=issuer_pk ) # assertion assert isinstance(tx_hash, str) and int(tx_hash, 16) > 0 assert tx_receipt["status"] == 1 share_token = ContractUtils.get_contract( - contract_name="IbetShare", - contract_address=token_address + contract_name="IbetShare", contract_address=token_address ) applications = share_token.functions.applicationsForTransfer(0).call() assert applications[0] == issuer_address @@ -2776,14 +2569,11 @@ def test_error_1(self, db): assert ex_info.value.errors() == [ { - 'loc': ('application_id',), - 'msg': 'value is not a valid integer', - 'type': 'type_error.integer' - }, { - 'loc': ('data',), - 'msg': 'field required', - 'type': 'value_error.missing' - } + "loc": ("application_id",), + "msg": "value is not a valid integer", + "type": "type_error.integer", + }, + {"loc": ("data",), "msg": "field required", "type": "value_error.missing"}, ] # @@ -2793,23 +2583,22 @@ def test_error_2(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # Transfer cancel - cancel_data = { - "application_id": 0, - "data": "test_data" - } + cancel_data = {"application_id": 0, "data": "test_data"} _cancel_transfer_data = CancelTransferParams(**cancel_data) share_contract = IbetShareContract("not address") with pytest.raises(SendTransactionError) as ex_info: share_contract.cancel_transfer( data=_cancel_transfer_data, tx_from=issuer_address, - private_key=private_key + private_key=private_key, ) - assert ex_info.match("when sending a str, it must be a hex string. Got: 'not address'") + assert ex_info.match( + "when sending a str, it must be a hex string. Got: 'not address'" + ) # # invalid issuer_address : does not exists @@ -2818,7 +2607,7 @@ def test_error_3(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -2831,27 +2620,22 @@ def test_error_3(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() contract_address, abi, tx_hash = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # Transfer cancel - cancel_data = { - "application_id": 0, - "data": "test_data" - } + cancel_data = {"application_id": 0, "data": "test_data"} _cancel_transfer_data = CancelTransferParams(**cancel_data) with pytest.raises(SendTransactionError) as ex_info: share_contract.cancel_transfer( data=_cancel_transfer_data, tx_from=issuer_address[:-1], - private_key=private_key + private_key=private_key, ) assert ex_info.match(f"ENS name: '{issuer_address[:-1]}' is invalid.") @@ -2862,7 +2646,7 @@ def test_error_4(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -2875,27 +2659,22 @@ def test_error_4(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() contract_address, abi, tx_hash = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # Transfer cancel - cancel_data = { - "application_id": 0, - "data": "test_data" - } + cancel_data = {"application_id": 0, "data": "test_data"} _cancel_transfer_data = CancelTransferParams(**cancel_data) with pytest.raises(SendTransactionError) as ex_info: share_contract.cancel_transfer( data=_cancel_transfer_data, tx_from=issuer_address, - private_key="dummy-private" + private_key="dummy-private", ) assert ex_info.match("Non-hexadecimal digit found") @@ -2906,21 +2685,21 @@ def test_error_5(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) to_account = config_eth_account("user2") to_address = to_account.get("address") to_pk = decode_keyfile_json( raw_keyfile_json=to_account.get("keyfile_json"), - password=to_account.get("password").encode("utf-8") + password=to_account.get("password").encode("utf-8"), ) deployer = config_eth_account("user3") deployer_address = deployer.get("address") deployer_pk = decode_keyfile_json( raw_keyfile_json=deployer.get("keyfile_json"), - password=deployer.get("password").encode("utf-8") + password=deployer.get("password").encode("utf-8"), ) # deploy new personal info contract (from deployer) @@ -2928,7 +2707,7 @@ def test_error_5(self, db): contract_name="PersonalInfo", args=[], deployer=deployer_address, - private_key=deployer_pk + private_key=deployer_pk, ) # deploy token @@ -2941,25 +2720,23 @@ def test_error_5(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() token_address, _, _ = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # update token (from issuer) update_data = { "personal_info_contract_address": personal_info_contract_address, "transfer_approval_required": True, - "transferable": True + "transferable": True, } share_contract.update( data=UpdateParams(**update_data), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) # register personal info (to_account) @@ -2967,7 +2744,7 @@ def test_error_5(self, db): contract_address=personal_info_contract_address, tx_from=to_address, private_key=to_pk, - args=[issuer_address, "test_personal_info"] + args=[issuer_address, "test_personal_info"], ) # apply transfer (from issuer) @@ -2975,18 +2752,15 @@ def test_error_5(self, db): contract_address=token_address, tx_from=issuer_address, private_key=issuer_pk, - args=[to_address, 10, "test_data"] + args=[to_address, 10, "test_data"], ) # approve transfer (from issuer) - approve_data = { - "application_id": 0, - "data": "approve transfer test" - } + approve_data = {"application_id": 0, "data": "approve transfer test"} share_contract.approve_transfer( data=ApproveTransferParams(**approve_data), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) # Then send cancelTransfer transaction. This would be failed. @@ -2998,14 +2772,14 @@ def test_error_5(self, db): # geth: ContractLogicError("execution reverted") InspectionMock = mock.patch( "web3.eth.Eth.call", - MagicMock(side_effect=ContractLogicError("execution reverted: 120802")) + MagicMock(side_effect=ContractLogicError("execution reverted: 120802")), ) with InspectionMock, pytest.raises(ContractRevertError) as exc_info: share_contract.cancel_transfer( data=CancelTransferParams(**cancel_data), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) # assertion @@ -3013,7 +2787,6 @@ def test_error_5(self, db): class TestLock: - ########################################################################### # Normal Case ########################################################################### @@ -3024,7 +2797,7 @@ def test_normal_1(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) lock_account = config_eth_account("user2") @@ -3040,21 +2813,15 @@ def test_normal_1(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() token_address, _, _ = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # lock - lock_data = { - "lock_address": lock_address, - "value": 10, - "data": "" - } + lock_data = {"lock_address": lock_address, "value": 10, "data": ""} tx_hash, tx_receipt = share_contract.lock( data=LockParams(**lock_data), tx_from=issuer_address, @@ -3066,10 +2833,11 @@ def test_normal_1(self, db): assert tx_receipt["status"] == 1 share_token = ContractUtils.get_contract( - contract_name="IbetShare", - contract_address=token_address + contract_name="IbetShare", contract_address=token_address ) - lock_amount = share_token.functions.lockedOf(lock_address, issuer_address).call() + lock_amount = share_token.functions.lockedOf( + lock_address, issuer_address + ).call() assert lock_amount == 10 ########################################################################### @@ -3086,19 +2854,12 @@ def test_error_1_1(self, db): assert ex_info.value.errors() == [ { - 'loc': ('lock_address',), - 'msg': 'field required', - 'type': 'value_error.missing' - }, - { - 'loc': ('value',), - 'msg': 'field required', - 'type': 'value_error.missing' + "loc": ("lock_address",), + "msg": "field required", + "type": "value_error.missing", }, - { - 'loc': ('data',), - 'msg': 'field required', - 'type': 'value_error.missing'} + {"loc": ("value",), "msg": "field required", "type": "value_error.missing"}, + {"loc": ("data",), "msg": "field required", "type": "value_error.missing"}, ] # @@ -3106,26 +2867,22 @@ def test_error_1_1(self, db): # - lock_address is not a valid address # - value is not greater than 0 def test_error_1_2(self, db): - lock_data = { - "lock_address": "test_address", - "value": 0, - "data": "" - } + lock_data = {"lock_address": "test_address", "value": 0, "data": ""} with pytest.raises(ValidationError) as ex_info: LockParams(**lock_data) assert ex_info.value.errors() == [ { - 'loc': ('lock_address',), - 'msg': 'lock_address is not a valid address', - 'type': 'value_error' + "loc": ("lock_address",), + "msg": "lock_address is not a valid address", + "type": "value_error", }, { - 'loc': ('value',), - 'msg': 'ensure this value is greater than 0', - 'type': 'value_error.number.not_gt', - 'ctx': {'limit_value': 0} - } + "loc": ("value",), + "msg": "ensure this value is greater than 0", + "type": "value_error.number.not_gt", + "ctx": {"limit_value": 0}, + }, ] # @@ -3136,7 +2893,7 @@ def test_error_2_1(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) lock_account = config_eth_account("user2") @@ -3152,21 +2909,15 @@ def test_error_2_1(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() token_address, _, _ = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # lock - lock_data = { - "lock_address": lock_address, - "value": 10, - "data": "" - } + lock_data = {"lock_address": lock_address, "value": 10, "data": ""} with pytest.raises(SendTransactionError) as exc_info: share_contract.lock( data=LockParams(**lock_data), @@ -3175,7 +2926,7 @@ def test_error_2_1(self, db): ) assert isinstance(exc_info.value.args[0], InvalidAddress) - assert exc_info.match("ENS name: \'invalid_tx_from\' is invalid.") + assert exc_info.match("ENS name: 'invalid_tx_from' is invalid.") # # SendTransactionError @@ -3185,7 +2936,7 @@ def test_error_2_2(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) lock_account = config_eth_account("user2") @@ -3201,21 +2952,15 @@ def test_error_2_2(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() token_address, _, _ = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # lock - lock_data = { - "lock_address": lock_address, - "value": 10, - "data": "" - } + lock_data = {"lock_address": lock_address, "value": 10, "data": ""} with pytest.raises(SendTransactionError) as exc_info: share_contract.lock( data=LockParams(**lock_data), @@ -3234,7 +2979,7 @@ def test_error_3(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) lock_account = config_eth_account("user2") @@ -3250,33 +2995,27 @@ def test_error_3(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() token_address, _, _ = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # mock Web3_send_raw_transaction = patch( target="web3.eth.Eth.wait_for_transaction_receipt", - side_effect=TimeExhausted + side_effect=TimeExhausted, ) # lock - lock_data = { - "lock_address": lock_address, - "value": 10, - "data": "" - } + lock_data = {"lock_address": lock_address, "value": 10, "data": ""} with Web3_send_raw_transaction: with pytest.raises(SendTransactionError) as exc_info: share_contract.lock( data=LockParams(**lock_data), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) assert exc_info.type(SendTransactionError(TimeExhausted)) @@ -3289,7 +3028,7 @@ def test_error_4(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) lock_account = config_eth_account("user2") @@ -3305,33 +3044,27 @@ def test_error_4(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() token_address, _, _ = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # mock Web3_send_raw_transaction = patch( target="web3.eth.Eth.wait_for_transaction_receipt", - side_effect=TransactionNotFound + side_effect=TransactionNotFound, ) # lock - lock_data = { - "lock_address": lock_address, - "value": 10, - "data": "" - } + lock_data = {"lock_address": lock_address, "value": 10, "data": ""} with Web3_send_raw_transaction: with pytest.raises(SendTransactionError) as exc_info: share_contract.lock( data=LockParams(**lock_data), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) assert exc_info.type(SendTransactionError(TransactionNotFound)) @@ -3343,7 +3076,7 @@ def test_error_5(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) lock_account = config_eth_account("user2") @@ -3359,13 +3092,11 @@ def test_error_5(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() token_address, _, _ = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # mock @@ -3374,29 +3105,27 @@ def test_error_5(self, db): # geth: ContractLogicError("execution reverted") InspectionMock = mock.patch( "web3.eth.Eth.call", - MagicMock(side_effect=ContractLogicError("execution reverted: 110002")) + MagicMock(side_effect=ContractLogicError("execution reverted: 110002")), ) # lock - lock_data = { - "lock_address": lock_address, - "value": 20001, - "data": "" - } + lock_data = {"lock_address": lock_address, "value": 20001, "data": ""} with InspectionMock, pytest.raises(ContractRevertError) as exc_info: share_contract.lock( data=LockParams(**lock_data), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) # assertion assert exc_info.value.code == 110002 - assert exc_info.value.message == "Lock amount is greater than message sender balance." + assert ( + exc_info.value.message + == "Lock amount is greater than message sender balance." + ) class TestForceUnlock: - ########################################################################### # Normal Case ########################################################################### @@ -3407,7 +3136,7 @@ def test_normal_1(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) lock_account = config_eth_account("user2") @@ -3423,21 +3152,15 @@ def test_normal_1(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() token_address, _, _ = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # lock - lock_data = { - "lock_address": lock_address, - "value": 10, - "data": "" - } + lock_data = {"lock_address": lock_address, "value": 10, "data": ""} share_contract.lock( data=LockParams(**lock_data), tx_from=issuer_address, @@ -3450,7 +3173,7 @@ def test_normal_1(self, db): "account_address": issuer_address, "recipient_address": issuer_address, "value": 5, - "data": "" + "data": "", } tx_hash, tx_receipt = share_contract.force_unlock( data=ForceUnlockPrams(**lock_data), @@ -3463,10 +3186,11 @@ def test_normal_1(self, db): assert tx_receipt["status"] == 1 share_token = ContractUtils.get_contract( - contract_name="IbetShare", - contract_address=token_address + contract_name="IbetShare", contract_address=token_address ) - lock_amount = share_token.functions.lockedOf(lock_address, issuer_address).call() + lock_amount = share_token.functions.lockedOf( + lock_address, issuer_address + ).call() assert lock_amount == 5 ########################################################################### @@ -3483,30 +3207,22 @@ def test_error_1_1(self, db): assert ex_info.value.errors() == [ { - 'loc': ('lock_address',), - 'msg': 'field required', - 'type': 'value_error.missing' - }, - { - 'loc': ('account_address',), - 'msg': 'field required', - 'type': 'value_error.missing' + "loc": ("lock_address",), + "msg": "field required", + "type": "value_error.missing", }, { - 'loc': ('recipient_address',), - 'msg': 'field required', - 'type': 'value_error.missing' + "loc": ("account_address",), + "msg": "field required", + "type": "value_error.missing", }, { - 'loc': ('value',), - 'msg': 'field required', - 'type': 'value_error.missing' + "loc": ("recipient_address",), + "msg": "field required", + "type": "value_error.missing", }, - { - 'loc': ('data',), - 'msg': 'field required', - 'type': 'value_error.missing' - } + {"loc": ("value",), "msg": "field required", "type": "value_error.missing"}, + {"loc": ("data",), "msg": "field required", "type": "value_error.missing"}, ] # @@ -3519,33 +3235,33 @@ def test_error_1_2(self, db): "account_address": "test_address", "recipient_address": "test_address", "value": 0, - "data": "" + "data": "", } with pytest.raises(ValidationError) as ex_info: ForceUnlockPrams(**lock_data) assert ex_info.value.errors() == [ { - 'loc': ('lock_address',), - 'msg': 'lock_address is not a valid address', - 'type': 'value_error' + "loc": ("lock_address",), + "msg": "lock_address is not a valid address", + "type": "value_error", }, { - 'loc': ('account_address',), - 'msg': 'account_address is not a valid address', - 'type': 'value_error' + "loc": ("account_address",), + "msg": "account_address is not a valid address", + "type": "value_error", }, { - 'loc': ('recipient_address',), - 'msg': 'recipient_address is not a valid address', - 'type': 'value_error' + "loc": ("recipient_address",), + "msg": "recipient_address is not a valid address", + "type": "value_error", }, { - 'loc': ('value',), - 'msg': 'ensure this value is greater than 0', - 'type': 'value_error.number.not_gt', - 'ctx': {'limit_value': 0} - } + "loc": ("value",), + "msg": "ensure this value is greater than 0", + "type": "value_error.number.not_gt", + "ctx": {"limit_value": 0}, + }, ] # @@ -3556,7 +3272,7 @@ def test_error_2_1(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) lock_account = config_eth_account("user2") @@ -3572,21 +3288,15 @@ def test_error_2_1(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() token_address, _, _ = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # lock - lock_data = { - "lock_address": lock_address, - "value": 10, - "data": "" - } + lock_data = {"lock_address": lock_address, "value": 10, "data": ""} share_contract.lock( data=LockParams(**lock_data), tx_from=issuer_address, @@ -3599,7 +3309,7 @@ def test_error_2_1(self, db): "account_address": issuer_address, "recipient_address": issuer_address, "value": 5, - "data": "" + "data": "", } with pytest.raises(SendTransactionError) as exc_info: share_contract.force_unlock( @@ -3609,7 +3319,7 @@ def test_error_2_1(self, db): ) assert isinstance(exc_info.value.args[0], InvalidAddress) - assert exc_info.match("ENS name: \'invalid_tx_from\' is invalid.") + assert exc_info.match("ENS name: 'invalid_tx_from' is invalid.") # # SendTransactionError @@ -3619,7 +3329,7 @@ def test_error_2_2(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) lock_account = config_eth_account("user2") @@ -3635,21 +3345,15 @@ def test_error_2_2(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() token_address, _, _ = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # lock - lock_data = { - "lock_address": lock_address, - "value": 10, - "data": "" - } + lock_data = {"lock_address": lock_address, "value": 10, "data": ""} share_contract.lock( data=LockParams(**lock_data), tx_from=issuer_address, @@ -3662,7 +3366,7 @@ def test_error_2_2(self, db): "account_address": issuer_address, "recipient_address": issuer_address, "value": 5, - "data": "" + "data": "", } with pytest.raises(SendTransactionError) as exc_info: share_contract.force_unlock( @@ -3682,7 +3386,7 @@ def test_error_3(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) lock_account = config_eth_account("user2") @@ -3698,21 +3402,15 @@ def test_error_3(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() token_address, _, _ = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # lock - lock_data = { - "lock_address": lock_address, - "value": 10, - "data": "" - } + lock_data = {"lock_address": lock_address, "value": 10, "data": ""} share_contract.lock( data=LockParams(**lock_data), tx_from=issuer_address, @@ -3722,7 +3420,7 @@ def test_error_3(self, db): # mock Web3_send_raw_transaction = patch( target="web3.eth.Eth.wait_for_transaction_receipt", - side_effect=TimeExhausted + side_effect=TimeExhausted, ) # forceUnlock @@ -3731,14 +3429,14 @@ def test_error_3(self, db): "account_address": issuer_address, "recipient_address": issuer_address, "value": 5, - "data": "" + "data": "", } with Web3_send_raw_transaction: with pytest.raises(SendTransactionError) as exc_info: share_contract.force_unlock( data=ForceUnlockPrams(**lock_data), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) assert exc_info.type(SendTransactionError(TimeExhausted)) @@ -3751,7 +3449,7 @@ def test_error_4(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) lock_account = config_eth_account("user2") @@ -3767,21 +3465,15 @@ def test_error_4(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() token_address, _, _ = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # lock - lock_data = { - "lock_address": lock_address, - "value": 10, - "data": "" - } + lock_data = {"lock_address": lock_address, "value": 10, "data": ""} share_contract.lock( data=LockParams(**lock_data), tx_from=issuer_address, @@ -3791,7 +3483,7 @@ def test_error_4(self, db): # mock Web3_send_raw_transaction = patch( target="web3.eth.Eth.wait_for_transaction_receipt", - side_effect=TransactionNotFound + side_effect=TransactionNotFound, ) # forceUnlock @@ -3800,14 +3492,14 @@ def test_error_4(self, db): "account_address": issuer_address, "recipient_address": issuer_address, "value": 5, - "data": "" + "data": "", } with Web3_send_raw_transaction: with pytest.raises(SendTransactionError) as exc_info: share_contract.force_unlock( data=ForceUnlockPrams(**lock_data), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) assert exc_info.type(SendTransactionError(TransactionNotFound)) @@ -3819,7 +3511,7 @@ def test_error_5(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) lock_account = config_eth_account("user2") @@ -3835,21 +3527,15 @@ def test_error_5(self, db): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() token_address, _, _ = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # lock - lock_data = { - "lock_address": lock_address, - "value": 10, - "data": "" - } + lock_data = {"lock_address": lock_address, "value": 10, "data": ""} share_contract.lock( data=LockParams(**lock_data), tx_from=issuer_address, @@ -3862,7 +3548,7 @@ def test_error_5(self, db): # geth: ContractLogicError("execution reverted") InspectionMock = mock.patch( "web3.eth.Eth.call", - MagicMock(side_effect=ContractLogicError("execution reverted: 111201")) + MagicMock(side_effect=ContractLogicError("execution reverted: 111201")), ) # forceUnlock @@ -3871,13 +3557,13 @@ def test_error_5(self, db): "account_address": issuer_address, "recipient_address": issuer_address, "value": 11, - "data": "" + "data": "", } with InspectionMock, pytest.raises(ContractRevertError) as exc_info: share_contract.force_unlock( data=ForceUnlockPrams(**lock_data), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) # assertion diff --git a/tests/model/blockchain/test_token_IbetStraightBond.py b/tests/model/blockchain/test_token_IbetStraightBond.py index fc4d5f84..c5466e50 100644 --- a/tests/model/blockchain/test_token_IbetStraightBond.py +++ b/tests/model/blockchain/test_token_IbetStraightBond.py @@ -16,51 +16,46 @@ SPDX-License-Identifier: Apache-2.0 """ -import pytest import time -from unittest import mock from binascii import Error -from unittest.mock import patch, MagicMock from datetime import datetime, timedelta +from unittest import mock +from unittest.mock import MagicMock, patch -from pydantic.error_wrappers import ValidationError +import pytest from eth_keyfile import decode_keyfile_json +from pydantic.error_wrappers import ValidationError from web3.exceptions import ( + ContractLogicError, InvalidAddress, TimeExhausted, TransactionNotFound, - ValidationError as Web3ValidationError, - ContractLogicError ) +from web3.exceptions import ValidationError as Web3ValidationError -from config import ZERO_ADDRESS, TOKEN_CACHE_TTL -from app.model.db import ( - TokenAttrUpdate, - TokenCache -) +from app.exceptions import ContractRevertError, SendTransactionError from app.model.blockchain import IbetStraightBondContract from app.model.blockchain.tx_params.ibet_straight_bond import ( - UpdateParams, - TransferParams, AdditionalIssueParams, - RedeemParams, ApproveTransferParams, CancelTransferParams, + ForceUnlockPrams, LockParams, - ForceUnlockPrams + RedeemParams, + TransferParams, + UpdateParams, ) +from app.model.db import TokenAttrUpdate, TokenCache from app.utils.contract_utils import ContractUtils -from app.exceptions import SendTransactionError, ContractRevertError - +from config import TOKEN_CACHE_TTL, ZERO_ADDRESS from tests.account_config import config_eth_account from tests.utils.contract_utils import ( + IbetSecurityTokenContractTestUtils, PersonalInfoContractTestUtils, - IbetSecurityTokenContractTestUtils ) class TestCreate: - ########################################################################### # Normal Case ########################################################################### @@ -71,7 +66,7 @@ def test_normal_1(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # execute the function @@ -84,18 +79,15 @@ def test_normal_1(self, db): 30000, "20211231", "リターン内容", - "発行目的" + "発行目的", ] contract_address, abi, tx_hash = IbetStraightBondContract().create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # assertion bond_contract = ContractUtils.get_contract( - contract_name="IbetStraightBond", - contract_address=contract_address + contract_name="IbetStraightBond", contract_address=contract_address ) assert bond_contract.functions.owner().call() == issuer_address assert bond_contract.functions.name().call() == "テスト債券" @@ -119,16 +111,14 @@ def test_error_1(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # execute the function arguments = [] with pytest.raises(SendTransactionError) as exc_info: IbetStraightBondContract().create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # assertion @@ -142,31 +132,21 @@ def test_error_2(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # execute the function - arguments = [ - 0, - 0, - "string", - "string", - 0, - 0, - "string", - 0, - 0 - ] # invalid types + arguments = [0, 0, "string", "string", 0, 0, "string", 0, 0] # invalid types with pytest.raises(SendTransactionError) as exc_info: IbetStraightBondContract().create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # assertion assert isinstance(exc_info.value.args[0], TypeError) - assert exc_info.match("One or more arguments could not be encoded to the necessary ABI type.") + assert exc_info.match( + "One or more arguments could not be encoded to the necessary ABI type." + ) # # Invalid argument type (tx_from) @@ -175,7 +155,7 @@ def test_error_3(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # execute the function @@ -188,18 +168,18 @@ def test_error_3(self, db): 30000, "20211231", "リターン内容", - "発行目的" + "発行目的", ] with pytest.raises(SendTransactionError) as exc_info: IbetStraightBondContract().create( args=arguments, tx_from=issuer_address[:-1], # short address - private_key=private_key + private_key=private_key, ) # assertion assert isinstance(exc_info.value.args[0], InvalidAddress) - assert exc_info.match("ENS name: \'.+\' is invalid.") + assert exc_info.match("ENS name: '.+' is invalid.") # # Invalid argument type (private_key) @@ -217,13 +197,11 @@ def test_error_4(self, db): 30000, "20211231", "リターン内容", - "発行目的" + "発行目的", ] with pytest.raises(SendTransactionError) as exc_info: IbetStraightBondContract().create( - args=arguments, - tx_from=issuer_address, - private_key="some_private_key" + args=arguments, tx_from=issuer_address, private_key="some_private_key" ) # assertion @@ -237,7 +215,7 @@ def test_error_5(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # execute the function @@ -250,26 +228,21 @@ def test_error_5(self, db): 30000, "20211231", "リターン内容", - "発行目的" + "発行目的", ] contract_address, abi, tx_hash = IbetStraightBondContract().create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) with pytest.raises(SendTransactionError) as exc_info: IbetStraightBondContract(contract_address).create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # assertion assert exc_info.match("contract is already deployed") class TestGet: - ########################################################################### # Normal Case ########################################################################### @@ -282,20 +255,23 @@ def test_normal_1(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token arguments = [ - "テスト債券", "TEST", 10000, 20000, - "20211231", 30000, - "20211231", "リターン内容", - "発行目的" + "テスト債券", + "TEST", + 10000, + 20000, + "20211231", + 30000, + "20211231", + "リターン内容", + "発行目的", ] contract_address, abi, tx_hash = IbetStraightBondContract().create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # get token data @@ -318,7 +294,20 @@ def test_normal_1(self, db): assert bond_contract.transfer_approval_required is False assert bond_contract.face_value == arguments[3] assert bond_contract.interest_rate == 0 - assert bond_contract.interest_payment_date == ["", "", "", "", "", "", "", "", "", "", "", ""] + assert bond_contract.interest_payment_date == [ + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + ] assert bond_contract.redemption_date == arguments[4] assert bond_contract.redemption_value == arguments[5] assert bond_contract.return_date == arguments[6] @@ -331,25 +320,27 @@ def test_normal_1(self, db): # TOKEN_CACHE is True @mock.patch("app.model.blockchain.token.TOKEN_CACHE", True) def test_normal_2(self, db): - test_account = config_eth_account("user1") issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token arguments = [ - "テスト債券", "TEST", 10000, 20000, - "20211231", 30000, - "20211231", "リターン内容", - "発行目的" + "テスト債券", + "TEST", + 10000, + 20000, + "20211231", + 30000, + "20211231", + "リターン内容", + "発行目的", ] contract_address, abi, tx_hash = IbetStraightBondContract(ZERO_ADDRESS).create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # create cache @@ -367,11 +358,21 @@ def test_normal_2(self, db): "transferable": True, "is_offering": True, "transfer_approval_required": True, - "face_value": 9999998, "interest_rate": 99.999, + "face_value": 9999998, + "interest_rate": 99.999, "interest_payment_date": [ - "99991231", "99991231", "99991231", "99991231", "99991231", - "99991231", "99991231", "99991231", "99991231", "99991231", - "99991231", "99991231" + "99991231", + "99991231", + "99991231", + "99991231", + "99991231", + "99991231", + "99991231", + "99991231", + "99991231", + "99991231", + "99991231", + "99991231", ], "redemption_date": "99991231", "redemption_value": 9999997, @@ -379,13 +380,15 @@ def test_normal_2(self, db): "return_amount": "return_amount-test", "purpose": "purpose-test", "memo": "memo-test", - "is_redeemed": True + "is_redeemed": True, } token_cache = TokenCache() token_cache.token_address = contract_address token_cache.attributes = token_attr token_cache.cached_datetime = datetime.utcnow() - token_cache.expiration_datetime = datetime.utcnow() + timedelta(seconds=TOKEN_CACHE_TTL) + token_cache.expiration_datetime = datetime.utcnow() + timedelta( + seconds=TOKEN_CACHE_TTL + ) db.add(token_cache) db.commit() @@ -400,17 +403,34 @@ def test_normal_2(self, db): assert bond_contract.total_supply == 9999999 assert bond_contract.contact_information == "test1" assert bond_contract.privacy_policy == "test2" - assert bond_contract.tradable_exchange_contract_address == "0x1234567890123456789012345678901234567890" + assert ( + bond_contract.tradable_exchange_contract_address + == "0x1234567890123456789012345678901234567890" + ) assert bond_contract.status is False - assert bond_contract.personal_info_contract_address == "0x1234567890123456789012345678901234567891" + assert ( + bond_contract.personal_info_contract_address + == "0x1234567890123456789012345678901234567891" + ) assert bond_contract.transferable is True assert bond_contract.is_offering is True assert bond_contract.transfer_approval_required is True assert bond_contract.face_value == 9999998 assert bond_contract.interest_rate == 99.999 - assert bond_contract.interest_payment_date == ["99991231", "99991231", "99991231", "99991231", "99991231", - "99991231", "99991231", "99991231", "99991231", "99991231", - "99991231", "99991231"] + assert bond_contract.interest_payment_date == [ + "99991231", + "99991231", + "99991231", + "99991231", + "99991231", + "99991231", + "99991231", + "99991231", + "99991231", + "99991231", + "99991231", + "99991231", + ] assert bond_contract.redemption_date == "99991231" assert bond_contract.redemption_value == 9999997 assert bond_contract.return_date == "99991230" @@ -423,25 +443,27 @@ def test_normal_2(self, db): # TOKEN_CACHE is True, updated token attribute @mock.patch("app.model.blockchain.token.TOKEN_CACHE", True) def test_normal_3(self, db): - test_account = config_eth_account("user1") issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token arguments = [ - "テスト債券", "TEST", 10000, 20000, - "20211231", 30000, - "20211231", "リターン内容", - "発行目的" + "テスト債券", + "TEST", + 10000, + 20000, + "20211231", + 30000, + "20211231", + "リターン内容", + "発行目的", ] contract_address, abi, tx_hash = IbetStraightBondContract(ZERO_ADDRESS).create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # create cache @@ -459,11 +481,21 @@ def test_normal_3(self, db): "transferable": True, "is_offering": True, "transfer_approval_required": True, - "face_value": 9999998, "interest_rate": 99.999, + "face_value": 9999998, + "interest_rate": 99.999, "interest_payment_date": [ - "99991231", "99991231", "99991231", "99991231", "99991231", - "99991231", "99991231", "99991231", "99991231", "99991231", - "99991231", "99991231" + "99991231", + "99991231", + "99991231", + "99991231", + "99991231", + "99991231", + "99991231", + "99991231", + "99991231", + "99991231", + "99991231", + "99991231", ], "redemption_date": "99991231", "redemption_value": 9999997, @@ -471,13 +503,15 @@ def test_normal_3(self, db): "return_amount": "return_amount-test", "purpose": "purpose-test", "memo": "memo-test", - "is_redeemed": True + "is_redeemed": True, } token_cache = TokenCache() token_cache.token_address = contract_address token_cache.attributes = token_attr token_cache.cached_datetime = datetime.utcnow() - token_cache.expiration_datetime = datetime.utcnow() + timedelta(seconds=TOKEN_CACHE_TTL) + token_cache.expiration_datetime = datetime.utcnow() + timedelta( + seconds=TOKEN_CACHE_TTL + ) db.add(token_cache) # updated token attribute @@ -506,7 +540,20 @@ def test_normal_3(self, db): assert bond_contract.transfer_approval_required is False assert bond_contract.face_value == arguments[3] assert bond_contract.interest_rate == 0 - assert bond_contract.interest_payment_date == ["", "", "", "", "", "", "", "", "", "", "", ""] + assert bond_contract.interest_payment_date == [ + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + ] assert bond_contract.redemption_date == arguments[4] assert bond_contract.redemption_value == arguments[5] assert bond_contract.return_date == arguments[6] @@ -537,7 +584,20 @@ def test_normal_4(self, db): assert bond_contract.transfer_approval_required is False assert bond_contract.face_value == 0 assert bond_contract.interest_rate == 0 - assert bond_contract.interest_payment_date == ["", "", "", "", "", "", "", "", "", "", "", ""] + assert bond_contract.interest_payment_date == [ + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + ] assert bond_contract.redemption_date == "" assert bond_contract.redemption_value == 0 assert bond_contract.return_date == "" @@ -552,7 +612,6 @@ def test_normal_4(self, db): class TestUpdate: - ########################################################################### # Normal Case ########################################################################### @@ -564,21 +623,24 @@ def test_normal_1(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token arguments = [ - "テスト債券", "TEST", 10000, 20000, - "20211231", 30000, - "20211231", "リターン内容", - "発行目的" + "テスト債券", + "TEST", + 10000, + 20000, + "20211231", + 30000, + "20211231", + "リターン内容", + "発行目的", ] bond_contract = IbetStraightBondContract() contract_address, abi, tx_hash = bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # update @@ -586,16 +648,27 @@ def test_normal_1(self, db): _add_data = UpdateParams(**_data) pre_datetime = datetime.utcnow() bond_contract.update( - data=_add_data, - tx_from=issuer_address, - private_key=private_key + data=_add_data, tx_from=issuer_address, private_key=private_key ) # assertion bond_contract = bond_contract.get() assert bond_contract.face_value == 20000 assert bond_contract.interest_rate == 0 - assert bond_contract.interest_payment_date == ["", "", "", "", "", "", "", "", "", "", "", ""] + assert bond_contract.interest_payment_date == [ + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + ] assert bond_contract.redemption_value == 30000 assert bond_contract.transferable is False assert bond_contract.status is True @@ -620,21 +693,24 @@ def test_normal_2(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token arguments = [ - "テスト債券", "TEST", 10000, 20000, - "20211231", 30000, - "20211231", "リターン内容", - "発行目的" + "テスト債券", + "TEST", + 10000, + 20000, + "20211231", + 30000, + "20211231", + "リターン内容", + "発行目的", ] bond_contract = IbetStraightBondContract() contract_address, abi, tx_hash = bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # update @@ -657,23 +733,40 @@ def test_normal_2(self, db): _add_data = UpdateParams(**_data) pre_datetime = datetime.utcnow() bond_contract.update( - data=_add_data, - tx_from=issuer_address, - private_key=private_key + data=_add_data, tx_from=issuer_address, private_key=private_key ) # assertion bond_contract = bond_contract.get() assert bond_contract.face_value == 20001 assert bond_contract.interest_rate == 0.0001 - assert bond_contract.interest_payment_date == ["0331", "0930", "", "", "", "", "", "", "", "", "", ""] + assert bond_contract.interest_payment_date == [ + "0331", + "0930", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + ] assert bond_contract.redemption_value == 30001 assert bond_contract.transferable is True assert bond_contract.status is False assert bond_contract.is_offering is True assert bond_contract.is_redeemed is True - assert bond_contract.tradable_exchange_contract_address == "0x0000000000000000000000000000000000000001" - assert bond_contract.personal_info_contract_address == "0x0000000000000000000000000000000000000002" + assert ( + bond_contract.tradable_exchange_contract_address + == "0x0000000000000000000000000000000000000001" + ) + assert ( + bond_contract.personal_info_contract_address + == "0x0000000000000000000000000000000000000002" + ) assert bond_contract.contact_information == "contact info test" assert bond_contract.privacy_policy == "privacy policy test" assert bond_contract.transfer_approval_required is True @@ -708,7 +801,7 @@ def test_error_1(self, db): "1001", "1101", "1201", - "1231" + "1231", ], "tradable_exchange_contract_address": "invalid contract address", "personal_info_contract_address": "invalid contract address", @@ -719,20 +812,23 @@ def test_error_1(self, db): { "loc": ("interest_rate",), "msg": "interest_rate must be rounded to 4 decimal places", - "type": "value_error" - }, { + "type": "value_error", + }, + { "loc": ("interest_payment_date",), "msg": "list length of interest_payment_date must be less than 13", - "type": "value_error" - }, { + "type": "value_error", + }, + { "loc": ("tradable_exchange_contract_address",), "msg": "tradable_exchange_contract_address is not a valid address", - "type": "value_error" - }, { + "type": "value_error", + }, + { "loc": ("personal_info_contract_address",), "msg": "personal_info_contract_address is not a valid address", - "type": "value_error" - } + "type": "value_error", + }, ] # @@ -742,36 +838,35 @@ def test_error_2(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token arguments = [ - "テスト債券", "TEST", 10000, 20000, - "20211231", 30000, - "20211231", "リターン内容", - "発行目的" + "テスト債券", + "TEST", + 10000, + 20000, + "20211231", + 30000, + "20211231", + "リターン内容", + "発行目的", ] bond_contract = IbetStraightBondContract() bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # update - _data = { - "face_value": 20001 - } + _data = {"face_value": 20001} _add_data = UpdateParams(**_data) with pytest.raises(SendTransactionError) as exc_info: bond_contract.update( - data=_add_data, - tx_from="DUMMY", - private_key=private_key + data=_add_data, tx_from="DUMMY", private_key=private_key ) assert isinstance(exc_info.value.args[0], InvalidAddress) - assert exc_info.match("ENS name: \'DUMMY\' is invalid.") + assert exc_info.match("ENS name: 'DUMMY' is invalid.") # # invalid private key @@ -780,33 +875,34 @@ def test_error_3(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token arguments = [ - "テスト債券", "TEST", 10000, 20000, - "20211231", 30000, - "20211231", "リターン内容", - "発行目的" + "テスト債券", + "TEST", + 10000, + 20000, + "20211231", + 30000, + "20211231", + "リターン内容", + "発行目的", ] bond_contract = IbetStraightBondContract() bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # update - _data = { - "face_value": 20001 - } + _data = {"face_value": 20001} _add_data = UpdateParams(**_data) with pytest.raises(SendTransactionError) as exc_info: bond_contract.update( data=_add_data, tx_from=issuer_address, - private_key="invalid private key" + private_key="invalid private key", ) assert isinstance(exc_info.value.args[0], Error) assert exc_info.match("Non-hexadecimal digit found") @@ -818,40 +914,39 @@ def test_error_4(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token arguments = [ - "テスト債券", "TEST", 10000, 20000, - "20211231", 30000, - "20211231", "リターン内容", - "発行目的" + "テスト債券", + "TEST", + 10000, + 20000, + "20211231", + 30000, + "20211231", + "リターン内容", + "発行目的", ] bond_contract = IbetStraightBondContract() bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # mock Web3_send_raw_transaction = patch( target="web3.eth.Eth.wait_for_transaction_receipt", - side_effect=TimeExhausted + side_effect=TimeExhausted, ) # update - _data = { - "face_value": 20001 - } + _data = {"face_value": 20001} _add_data = UpdateParams(**_data) with Web3_send_raw_transaction: with pytest.raises(SendTransactionError) as exc_info: bond_contract.update( - data=_add_data, - tx_from=issuer_address, - private_key=private_key + data=_add_data, tx_from=issuer_address, private_key=private_key ) assert isinstance(exc_info.value.args[0], TimeExhausted) @@ -862,40 +957,39 @@ def test_error_5(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token arguments = [ - "テスト債券", "TEST", 10000, 20000, - "20211231", 30000, - "20211231", "リターン内容", - "発行目的" + "テスト債券", + "TEST", + 10000, + 20000, + "20211231", + 30000, + "20211231", + "リターン内容", + "発行目的", ] bond_contract = IbetStraightBondContract() bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # mock Web3_send_raw_transaction = patch( target="web3.eth.Eth.wait_for_transaction_receipt", - side_effect=TransactionNotFound + side_effect=TransactionNotFound, ) # update - _data = { - "face_value": 20001 - } + _data = {"face_value": 20001} _add_data = UpdateParams(**_data) with Web3_send_raw_transaction: with pytest.raises(SendTransactionError) as exc_info: bond_contract.update( - data=_add_data, - tx_from=issuer_address, - private_key=private_key + data=_add_data, tx_from=issuer_address, private_key=private_key ) assert isinstance(exc_info.value.args[0], TransactionNotFound) @@ -908,31 +1002,32 @@ def test_error_6(self, db): user_address = user_account.get("address") issuer_private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) user_private_key = decode_keyfile_json( raw_keyfile_json=user_account.get("keyfile_json"), - password=user_account.get("password").encode("utf-8") + password=user_account.get("password").encode("utf-8"), ) # deploy token arguments = [ - "テスト債券", "TEST", 10000, 20000, - "20211231", 30000, - "20211231", "リターン内容", - "発行目的" + "テスト債券", + "TEST", + 10000, + 20000, + "20211231", + 30000, + "20211231", + "リターン内容", + "発行目的", ] bond_contract = IbetStraightBondContract() bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_private_key + args=arguments, tx_from=issuer_address, private_key=issuer_private_key ) # update - _data = { - "face_value": 20001 - } + _data = {"face_value": 20001} _add_data = UpdateParams(**_data) # mock @@ -941,14 +1036,12 @@ def test_error_6(self, db): # geth: ContractLogicError("execution reverted") InspectionMock = mock.patch( "web3.eth.Eth.call", - MagicMock(side_effect=ContractLogicError("execution reverted: 500001")) + MagicMock(side_effect=ContractLogicError("execution reverted: 500001")), ) with InspectionMock, pytest.raises(ContractRevertError) as exc_info: bond_contract.update( - data=_add_data, - tx_from=user_address, - private_key=user_private_key + data=_add_data, tx_from=user_address, private_key=user_private_key ) # assertion @@ -956,7 +1049,6 @@ def test_error_6(self, db): class TestTransfer: - ########################################################################### # Normal Case ########################################################################### @@ -967,7 +1059,7 @@ def test_normal_1(self, db): from_address = from_account.get("address") from_private_key = decode_keyfile_json( raw_keyfile_json=from_account.get("keyfile_json"), - password=from_account.get("password").encode("utf-8") + password=from_account.get("password").encode("utf-8"), ) to_account = config_eth_account("user2") @@ -975,29 +1067,26 @@ def test_normal_1(self, db): # deploy token arguments = [ - "テスト債券", "TEST", 10000, 20000, - "20211231", 30000, - "20211231", "リターン内容", - "発行目的" + "テスト債券", + "TEST", + 10000, + 20000, + "20211231", + 30000, + "20211231", + "リターン内容", + "発行目的", ] bond_contract = IbetStraightBondContract() bond_contract.create( - args=arguments, - tx_from=from_address, - private_key=from_private_key + args=arguments, tx_from=from_address, private_key=from_private_key ) # transfer - _data = { - "from_address": from_address, - "to_address": to_address, - "amount": 10 - } + _data = {"from_address": from_address, "to_address": to_address, "amount": 10} _transfer_data = TransferParams(**_data) bond_contract.transfer( - data=_transfer_data, - tx_from=from_address, - private_key=from_private_key + data=_transfer_data, tx_from=from_address, private_key=from_private_key ) # assertion @@ -1021,16 +1110,18 @@ def test_error_1(self, db): { "loc": ("from_address",), "msg": "field required", - "type": "value_error.missing" - }, { + "type": "value_error.missing", + }, + { "loc": ("to_address",), "msg": "field required", - "type": "value_error.missing" - }, { + "type": "value_error.missing", + }, + { "loc": ("amount",), "msg": "field required", - "type": "value_error.missing" - } + "type": "value_error.missing", + }, ] # @@ -1041,7 +1132,7 @@ def test_error_2(self, db): "token_address": "invalid contract address", "from_address": "invalid from_address", "to_address": "invalid to_address", - "amount": 0 + "amount": 0, } with pytest.raises(ValidationError) as exc_info: TransferParams(**_data) @@ -1049,19 +1140,19 @@ def test_error_2(self, db): { "loc": ("from_address",), "msg": "from_address is not a valid address", - "type": "value_error" + "type": "value_error", }, { "loc": ("to_address",), "msg": "to_address is not a valid address", - "type": "value_error" + "type": "value_error", }, { - 'loc': ('amount',), - 'msg': 'ensure this value is greater than 0', - 'type': 'value_error.number.not_gt', - 'ctx': {'limit_value': 0} - } + "loc": ("amount",), + "msg": "ensure this value is greater than 0", + "type": "value_error.number.not_gt", + "ctx": {"limit_value": 0}, + }, ] # @@ -1071,7 +1162,7 @@ def test_error_3(self, db): from_address = from_account.get("address") from_private_key = decode_keyfile_json( raw_keyfile_json=from_account.get("keyfile_json"), - password=from_account.get("password").encode("utf-8") + password=from_account.get("password").encode("utf-8"), ) to_account = config_eth_account("user2") @@ -1079,33 +1170,32 @@ def test_error_3(self, db): # deploy token arguments = [ - "テスト債券", "TEST", 10000, 20000, - "20211231", 30000, - "20211231", "リターン内容", - "発行目的" + "テスト債券", + "TEST", + 10000, + 20000, + "20211231", + 30000, + "20211231", + "リターン内容", + "発行目的", ] bond_contract = IbetStraightBondContract() bond_contract.create( - args=arguments, - tx_from=from_address, - private_key=from_private_key + args=arguments, tx_from=from_address, private_key=from_private_key ) # transfer - _data = { - "from_address": from_address, - "to_address": to_address, - "amount": 10 - } + _data = {"from_address": from_address, "to_address": to_address, "amount": 10} _transfer_data = TransferParams(**_data) with pytest.raises(SendTransactionError) as exc_info: bond_contract.transfer( data=_transfer_data, tx_from="invalid_tx_from", - private_key=from_private_key + private_key=from_private_key, ) assert isinstance(exc_info.value.args[0], InvalidAddress) - assert exc_info.match("ENS name: \'invalid_tx_from\' is invalid.") + assert exc_info.match("ENS name: 'invalid_tx_from' is invalid.") # # invalid private key @@ -1114,7 +1204,7 @@ def test_error_4(self, db): from_address = from_account.get("address") from_private_key = decode_keyfile_json( raw_keyfile_json=from_account.get("keyfile_json"), - password=from_account.get("password").encode("utf-8") + password=from_account.get("password").encode("utf-8"), ) to_account = config_eth_account("user2") @@ -1122,30 +1212,29 @@ def test_error_4(self, db): # deploy token arguments = [ - "テスト債券", "TEST", 10000, 20000, - "20211231", 30000, - "20211231", "リターン内容", - "発行目的" + "テスト債券", + "TEST", + 10000, + 20000, + "20211231", + 30000, + "20211231", + "リターン内容", + "発行目的", ] bond_contract = IbetStraightBondContract() bond_contract.create( - args=arguments, - tx_from=from_address, - private_key=from_private_key + args=arguments, tx_from=from_address, private_key=from_private_key ) # transfer - _data = { - "from_address": from_address, - "to_address": to_address, - "amount": 10 - } + _data = {"from_address": from_address, "to_address": to_address, "amount": 10} _transfer_data = TransferParams(**_data) with pytest.raises(SendTransactionError) as exc_info: bond_contract.transfer( data=_transfer_data, tx_from=from_address, - private_key="invalid_private_key" + private_key="invalid_private_key", ) assert isinstance(exc_info.value.args[0], Error) assert exc_info.match("Non-hexadecimal digit found") @@ -1157,7 +1246,7 @@ def test_error_5(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) to_account = config_eth_account("user2") @@ -1165,37 +1254,34 @@ def test_error_5(self, db): # deploy token arguments = [ - "テスト債券", "TEST", 10000, 20000, - "20211231", 30000, - "20211231", "リターン内容", - "発行目的" + "テスト債券", + "TEST", + 10000, + 20000, + "20211231", + 30000, + "20211231", + "リターン内容", + "発行目的", ] bond_contract = IbetStraightBondContract() bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # mock Web3_send_raw_transaction = patch( target="web3.eth.Eth.wait_for_transaction_receipt", - side_effect=TimeExhausted + side_effect=TimeExhausted, ) # transfer - _data = { - "from_address": issuer_address, - "to_address": to_address, - "amount": 10 - } + _data = {"from_address": issuer_address, "to_address": to_address, "amount": 10} _transfer_data = TransferParams(**_data) with Web3_send_raw_transaction: with pytest.raises(SendTransactionError) as exc_info: bond_contract.transfer( - data=_transfer_data, - tx_from=issuer_address, - private_key=private_key + data=_transfer_data, tx_from=issuer_address, private_key=private_key ) assert isinstance(exc_info.value.args[0], TimeExhausted) @@ -1206,7 +1292,7 @@ def test_error_6(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) to_account = config_eth_account("user2") @@ -1214,37 +1300,34 @@ def test_error_6(self, db): # deploy token arguments = [ - "テスト債券", "TEST", 10000, 20000, - "20211231", 30000, - "20211231", "リターン内容", - "発行目的" + "テスト債券", + "TEST", + 10000, + 20000, + "20211231", + 30000, + "20211231", + "リターン内容", + "発行目的", ] bond_contract = IbetStraightBondContract() bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # mock Web3_send_raw_transaction = patch( target="web3.eth.Eth.wait_for_transaction_receipt", - side_effect=TransactionNotFound + side_effect=TransactionNotFound, ) # transfer - _data = { - "from_address": issuer_address, - "to_address": to_address, - "amount": 10 - } + _data = {"from_address": issuer_address, "to_address": to_address, "amount": 10} _transfer_data = TransferParams(**_data) with Web3_send_raw_transaction: with pytest.raises(SendTransactionError) as exc_info: bond_contract.transfer( - data=_transfer_data, - tx_from=issuer_address, - private_key=private_key + data=_transfer_data, tx_from=issuer_address, private_key=private_key ) assert isinstance(exc_info.value.args[0], TransactionNotFound) @@ -1255,7 +1338,7 @@ def test_error_7(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) to_account = config_eth_account("user2") @@ -1263,23 +1346,26 @@ def test_error_7(self, db): # deploy token arguments = [ - "テスト債券", "TEST", 10000, 20000, - "20211231", 30000, - "20211231", "リターン内容", - "発行目的" + "テスト債券", + "TEST", + 10000, + 20000, + "20211231", + 30000, + "20211231", + "リターン内容", + "発行目的", ] bond_contract = IbetStraightBondContract() bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # transfer with insufficient balance _data = { "from_address": issuer_address, "to_address": to_address, - "amount": 10000000 + "amount": 10000000, } _transfer_data = TransferParams(**_data) @@ -1289,14 +1375,12 @@ def test_error_7(self, db): # geth: ContractLogicError("execution reverted: ") InspectionMock = mock.patch( "web3.eth.Eth.call", - MagicMock(side_effect=ContractLogicError("execution reverted: 120401")) + MagicMock(side_effect=ContractLogicError("execution reverted: 120401")), ) with InspectionMock, pytest.raises(ContractRevertError) as exc_info: bond_contract.transfer( - data=_transfer_data, - tx_from=issuer_address, - private_key=private_key + data=_transfer_data, tx_from=issuer_address, private_key=private_key ) # assertion @@ -1304,7 +1388,6 @@ def test_error_7(self, db): class TestAdditionalIssue: - ########################################################################### # Normal Case ########################################################################### @@ -1315,34 +1398,32 @@ def test_normal_1(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token arguments = [ - "テスト債券", "TEST", 10000, 20000, - "20211231", 30000, - "20211231", "リターン内容", - "発行目的" + "テスト債券", + "TEST", + 10000, + 20000, + "20211231", + 30000, + "20211231", + "リターン内容", + "発行目的", ] bond_contract = IbetStraightBondContract() contract_address, abi, tx_hash = bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # additional issue - _data = { - "account_address": issuer_address, - "amount": 10 - } + _data = {"account_address": issuer_address, "amount": 10} _add_data = AdditionalIssueParams(**_data) pre_datetime = datetime.utcnow() bond_contract.additional_issue( - data=_add_data, - tx_from=issuer_address, - private_key=private_key + data=_add_data, tx_from=issuer_address, private_key=private_key ) # assertion @@ -1372,36 +1453,34 @@ def test_error_1(self, db): { "loc": ("account_address",), "msg": "field required", - "type": "value_error.missing" - }, { + "type": "value_error.missing", + }, + { "loc": ("amount",), "msg": "field required", - "type": "value_error.missing" - } + "type": "value_error.missing", + }, ] # # validation (AdditionalIssueParams) # invalid parameter def test_error_2(self, db): - _data = { - "account_address": "invalid account address", - "amount": 0 - } + _data = {"account_address": "invalid account address", "amount": 0} with pytest.raises(ValidationError) as exc_info: AdditionalIssueParams(**_data) assert exc_info.value.errors() == [ { "loc": ("account_address",), "msg": "account_address is not a valid address", - "type": "value_error" + "type": "value_error", }, { - 'loc': ('amount',), - 'msg': 'ensure this value is greater than 0', - 'type': 'value_error.number.not_gt', - 'ctx': {'limit_value': 0} - } + "loc": ("amount",), + "msg": "ensure this value is greater than 0", + "type": "value_error.number.not_gt", + "ctx": {"limit_value": 0}, + }, ] # @@ -1411,37 +1490,35 @@ def test_error_3(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token arguments = [ - "テスト債券", "TEST", 10000, 20000, - "20211231", 30000, - "20211231", "リターン内容", - "発行目的" + "テスト債券", + "TEST", + 10000, + 20000, + "20211231", + 30000, + "20211231", + "リターン内容", + "発行目的", ] bond_contract = IbetStraightBondContract() bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # additional issue - _data = { - "account_address": issuer_address, - "amount": 10 - } + _data = {"account_address": issuer_address, "amount": 10} _add_data = AdditionalIssueParams(**_data) with pytest.raises(SendTransactionError) as exc_info: bond_contract.additional_issue( - data=_add_data, - tx_from="invalid_tx_from", - private_key=private_key + data=_add_data, tx_from="invalid_tx_from", private_key=private_key ) assert isinstance(exc_info.value.args[0], InvalidAddress) - assert exc_info.match("ENS name: \'invalid_tx_from\' is invalid.") + assert exc_info.match("ENS name: 'invalid_tx_from' is invalid.") # # invalid private key @@ -1450,34 +1527,34 @@ def test_error_4(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token arguments = [ - "テスト債券", "TEST", 10000, 20000, - "20211231", 30000, - "20211231", "リターン内容", - "発行目的" + "テスト債券", + "TEST", + 10000, + 20000, + "20211231", + 30000, + "20211231", + "リターン内容", + "発行目的", ] bond_contract = IbetStraightBondContract() bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # additional issue - _data = { - "account_address": issuer_address, - "amount": 10 - } + _data = {"account_address": issuer_address, "amount": 10} _add_data = AdditionalIssueParams(**_data) with pytest.raises(SendTransactionError) as exc_info: bond_contract.additional_issue( data=_add_data, tx_from=test_account.get("address"), - private_key="invalid_private_key" + private_key="invalid_private_key", ) assert isinstance(exc_info.value.args[0], Error) assert exc_info.match("Non-hexadecimal digit found") @@ -1489,41 +1566,41 @@ def test_error_5(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token arguments = [ - "テスト債券", "TEST", 10000, 20000, - "20211231", 30000, - "20211231", "リターン内容", - "発行目的" + "テスト債券", + "TEST", + 10000, + 20000, + "20211231", + 30000, + "20211231", + "リターン内容", + "発行目的", ] bond_contract = IbetStraightBondContract() bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # mock Web3_send_raw_transaction = patch( target="web3.eth.Eth.wait_for_transaction_receipt", - side_effect=TimeExhausted + side_effect=TimeExhausted, ) # additional issue - _data = { - "account_address": issuer_address, - "amount": 10 - } + _data = {"account_address": issuer_address, "amount": 10} _add_data = AdditionalIssueParams(**_data) with Web3_send_raw_transaction: with pytest.raises(SendTransactionError) as exc_info: bond_contract.additional_issue( data=_add_data, tx_from=test_account.get("address"), - private_key=private_key + private_key=private_key, ) assert exc_info.type(SendTransactionError(TimeExhausted)) @@ -1534,41 +1611,39 @@ def test_error_6(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token arguments = [ - "テスト債券", "TEST", 10000, 20000, - "20211231", 30000, - "20211231", "リターン内容", - "発行目的" + "テスト債券", + "TEST", + 10000, + 20000, + "20211231", + 30000, + "20211231", + "リターン内容", + "発行目的", ] bond_contract = IbetStraightBondContract() bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # mock Web3_send_raw_transaction = patch( target="web3.eth.Eth.wait_for_transaction_receipt", - side_effect=TransactionNotFound + side_effect=TransactionNotFound, ) # additional issue - _data = { - "account_address": issuer_address, - "amount": 10 - } + _data = {"account_address": issuer_address, "amount": 10} _add_data = AdditionalIssueParams(**_data) with Web3_send_raw_transaction: with pytest.raises(SendTransactionError) as exc_info: bond_contract.additional_issue( - data=_add_data, - tx_from=issuer_address, - private_key=private_key + data=_add_data, tx_from=issuer_address, private_key=private_key ) assert isinstance(exc_info.value.args[0], TransactionNotFound) @@ -1581,32 +1656,32 @@ def test_error_7(self, db): user_address = user_account.get("address") issuer_private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) user_private_key = decode_keyfile_json( raw_keyfile_json=user_account.get("keyfile_json"), - password=user_account.get("password").encode("utf-8") + password=user_account.get("password").encode("utf-8"), ) # deploy token arguments = [ - "テスト債券", "TEST", 10000, 20000, - "20211231", 30000, - "20211231", "リターン内容", - "発行目的" + "テスト債券", + "TEST", + 10000, + 20000, + "20211231", + 30000, + "20211231", + "リターン内容", + "発行目的", ] bond_contract = IbetStraightBondContract() bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_private_key + args=arguments, tx_from=issuer_address, private_key=issuer_private_key ) # additional issue - _data = { - "account_address": issuer_address, - "amount": 10 - } + _data = {"account_address": issuer_address, "amount": 10} _add_data = AdditionalIssueParams(**_data) pre_datetime = datetime.utcnow() @@ -1616,14 +1691,12 @@ def test_error_7(self, db): # geth: ContractLogicError("execution reverted") InspectionMock = mock.patch( "web3.eth.Eth.call", - MagicMock(side_effect=ContractLogicError("execution reverted: 500001")) + MagicMock(side_effect=ContractLogicError("execution reverted: 500001")), ) with InspectionMock, pytest.raises(ContractRevertError) as exc_info: bond_contract.additional_issue( - data=_add_data, - tx_from=user_address, - private_key=user_private_key + data=_add_data, tx_from=user_address, private_key=user_private_key ) # assertion @@ -1631,7 +1704,6 @@ def test_error_7(self, db): class TestRedeem: - ########################################################################### # Normal Case ########################################################################### @@ -1642,34 +1714,32 @@ def test_normal_1(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token arguments = [ - "テスト債券", "TEST", 10000, 20000, - "20211231", 30000, - "20211231", "リターン内容", - "発行目的" + "テスト債券", + "TEST", + 10000, + 20000, + "20211231", + 30000, + "20211231", + "リターン内容", + "発行目的", ] bond_contract = IbetStraightBondContract() contract_address, abi, tx_hash = bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # redeem - _data = { - "account_address": issuer_address, - "amount": 10 - } + _data = {"account_address": issuer_address, "amount": 10} _add_data = RedeemParams(**_data) pre_datetime = datetime.utcnow() bond_contract.redeem( - data=_add_data, - tx_from=issuer_address, - private_key=private_key + data=_add_data, tx_from=issuer_address, private_key=private_key ) # assertion @@ -1699,36 +1769,34 @@ def test_error_1(self, db): { "loc": ("account_address",), "msg": "field required", - "type": "value_error.missing" - }, { + "type": "value_error.missing", + }, + { "loc": ("amount",), "msg": "field required", - "type": "value_error.missing" - } + "type": "value_error.missing", + }, ] # # validation (RedeemParams) # invalid parameter def test_error_2(self, db): - _data = { - "account_address": "invalid account address", - "amount": 0 - } + _data = {"account_address": "invalid account address", "amount": 0} with pytest.raises(ValidationError) as exc_info: RedeemParams(**_data) assert exc_info.value.errors() == [ { "loc": ("account_address",), "msg": "account_address is not a valid address", - "type": "value_error" + "type": "value_error", }, { - 'loc': ('amount',), - 'msg': 'ensure this value is greater than 0', - 'type': 'value_error.number.not_gt', - 'ctx': {'limit_value': 0} - } + "loc": ("amount",), + "msg": "ensure this value is greater than 0", + "type": "value_error.number.not_gt", + "ctx": {"limit_value": 0}, + }, ] # @@ -1738,37 +1806,35 @@ def test_error_3(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token arguments = [ - "テスト債券", "TEST", 10000, 20000, - "20211231", 30000, - "20211231", "リターン内容", - "発行目的" + "テスト債券", + "TEST", + 10000, + 20000, + "20211231", + 30000, + "20211231", + "リターン内容", + "発行目的", ] bond_contract = IbetStraightBondContract() bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # redeem - _data = { - "account_address": issuer_address, - "amount": 10 - } + _data = {"account_address": issuer_address, "amount": 10} _add_data = RedeemParams(**_data) with pytest.raises(SendTransactionError) as exc_info: bond_contract.redeem( - data=_add_data, - tx_from="invalid_tx_from", - private_key=private_key + data=_add_data, tx_from="invalid_tx_from", private_key=private_key ) assert isinstance(exc_info.value.args[0], InvalidAddress) - assert exc_info.match("ENS name: \'invalid_tx_from\' is invalid.") + assert exc_info.match("ENS name: 'invalid_tx_from' is invalid.") # # invalid private key @@ -1777,34 +1843,34 @@ def test_error_4(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token arguments = [ - "テスト債券", "TEST", 10000, 20000, - "20211231", 30000, - "20211231", "リターン内容", - "発行目的" + "テスト債券", + "TEST", + 10000, + 20000, + "20211231", + 30000, + "20211231", + "リターン内容", + "発行目的", ] bond_contract = IbetStraightBondContract() bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # redeem - _data = { - "account_address": issuer_address, - "amount": 10 - } + _data = {"account_address": issuer_address, "amount": 10} _add_data = RedeemParams(**_data) with pytest.raises(SendTransactionError) as exc_info: bond_contract.redeem( data=_add_data, tx_from=test_account.get("address"), - private_key="invalid_private_key" + private_key="invalid_private_key", ) assert isinstance(exc_info.value.args[0], Error) assert exc_info.match("Non-hexadecimal digit found") @@ -1816,41 +1882,41 @@ def test_error_5(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token arguments = [ - "テスト債券", "TEST", 10000, 20000, - "20211231", 30000, - "20211231", "リターン内容", - "発行目的" + "テスト債券", + "TEST", + 10000, + 20000, + "20211231", + 30000, + "20211231", + "リターン内容", + "発行目的", ] bond_contract = IbetStraightBondContract() bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # mock Web3_send_raw_transaction = patch( target="web3.eth.Eth.wait_for_transaction_receipt", - side_effect=TimeExhausted + side_effect=TimeExhausted, ) # redeem - _data = { - "account_address": issuer_address, - "amount": 10 - } + _data = {"account_address": issuer_address, "amount": 10} _add_data = RedeemParams(**_data) with Web3_send_raw_transaction: with pytest.raises(SendTransactionError) as exc_info: bond_contract.redeem( data=_add_data, tx_from=test_account.get("address"), - private_key=private_key + private_key=private_key, ) assert exc_info.type(SendTransactionError(TimeExhausted)) @@ -1861,41 +1927,39 @@ def test_error_6(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token arguments = [ - "テスト債券", "TEST", 10000, 20000, - "20211231", 30000, - "20211231", "リターン内容", - "発行目的" + "テスト債券", + "TEST", + 10000, + 20000, + "20211231", + 30000, + "20211231", + "リターン内容", + "発行目的", ] bond_contract = IbetStraightBondContract() bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # mock Web3_send_raw_transaction = patch( target="web3.eth.Eth.wait_for_transaction_receipt", - side_effect=TransactionNotFound + side_effect=TransactionNotFound, ) # redeem - _data = { - "account_address": issuer_address, - "amount": 10 - } + _data = {"account_address": issuer_address, "amount": 10} _add_data = RedeemParams(**_data) with Web3_send_raw_transaction: with pytest.raises(SendTransactionError) as exc_info: bond_contract.redeem( - data=_add_data, - tx_from=issuer_address, - private_key=private_key + data=_add_data, tx_from=issuer_address, private_key=private_key ) assert isinstance(exc_info.value.args[0], TransactionNotFound) @@ -1906,28 +1970,28 @@ def test_error_7(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token arguments = [ - "テスト債券", "TEST", 10000, 20000, - "20211231", 30000, - "20211231", "リターン内容", - "発行目的" + "テスト債券", + "TEST", + 10000, + 20000, + "20211231", + 30000, + "20211231", + "リターン内容", + "発行目的", ] bond_contract = IbetStraightBondContract() bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # redeem - _data = { - "account_address": issuer_address, - "amount": 100_000_000 - } + _data = {"account_address": issuer_address, "amount": 100_000_000} _add_data = RedeemParams(**_data) pre_datetime = datetime.utcnow() @@ -1937,22 +2001,22 @@ def test_error_7(self, db): # geth: ContractLogicError("execution reverted") InspectionMock = mock.patch( "web3.eth.Eth.call", - MagicMock(side_effect=ContractLogicError("execution reverted: 121102")) + MagicMock(side_effect=ContractLogicError("execution reverted: 121102")), ) with InspectionMock, pytest.raises(ContractRevertError) as exc_info: bond_contract.redeem( - data=_add_data, - tx_from=issuer_address, - private_key=private_key + data=_add_data, tx_from=issuer_address, private_key=private_key ) # assertion - assert exc_info.value.args[0] == "Redeem amount is less than target address balance." + assert ( + exc_info.value.args[0] + == "Redeem amount is less than target address balance." + ) class TestGetAccountBalance: - ########################################################################### # Normal Case ########################################################################### @@ -1963,7 +2027,7 @@ def test_normal_1(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -1976,13 +2040,11 @@ def test_normal_1(self, db): 30000, "20211231", "リターン内容", - "発行目的" + "発行目的", ] bond_contract = IbetStraightBondContract() bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # assertion @@ -2013,7 +2075,7 @@ def test_error_2(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -2026,20 +2088,16 @@ def test_error_2(self, db): 30000, "20211231", "リターン内容", - "発行目的" + "発行目的", ] bond_contract = IbetStraightBondContract() bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # execute the function with pytest.raises(Web3ValidationError): - bond_contract.get_account_balance( - issuer_address[:-1] # short - ) + bond_contract.get_account_balance(issuer_address[:-1]) # short class TestCheckAttrUpdate: @@ -2117,7 +2175,7 @@ class TestRecordAttrUpdate: # # data not exists - @pytest.mark.freeze_time('2021-04-27 12:34:56') + @pytest.mark.freeze_time("2021-04-27 12:34:56") def test_normal_1(self, db): # Test bond_contract = IbetStraightBondContract(self.token_address) @@ -2132,7 +2190,6 @@ def test_normal_1(self, db): # # data exists def test_normal_2(self, db, freezer): - # prepare data _update = TokenAttrUpdate() _update.token_address = self.token_address @@ -2141,7 +2198,7 @@ def test_normal_2(self, db, freezer): db.commit() # Mock datetime - freezer.move_to('2021-04-27 12:34:56') + freezer.move_to("2021-04-27 12:34:56") # Test bond_contract = IbetStraightBondContract(self.token_address) @@ -2159,7 +2216,6 @@ def test_normal_2(self, db, freezer): class TestApproveTransfer: - ########################################################################### # Normal Case ########################################################################### @@ -2170,21 +2226,21 @@ def test_normal_1(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) to_account = config_eth_account("user2") to_address = to_account.get("address") to_pk = decode_keyfile_json( raw_keyfile_json=to_account.get("keyfile_json"), - password=to_account.get("password").encode("utf-8") + password=to_account.get("password").encode("utf-8"), ) deployer = config_eth_account("user3") deployer_address = deployer.get("address") deployer_pk = decode_keyfile_json( raw_keyfile_json=deployer.get("keyfile_json"), - password=deployer.get("password").encode("utf-8") + password=deployer.get("password").encode("utf-8"), ) # deploy new personal info contract (from deployer) @@ -2192,7 +2248,7 @@ def test_normal_1(self, db): contract_name="PersonalInfo", args=[], deployer=deployer_address, - private_key=deployer_pk + private_key=deployer_pk, ) # deploy ibet bond token (from issuer) @@ -2205,25 +2261,23 @@ def test_normal_1(self, db): 30000, "20211231", "リターン内容", - "発行目的" + "発行目的", ] bond_contract = IbetStraightBondContract() token_address, _, _ = bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # update token (from issuer) update_data = { "personal_info_contract_address": personal_info_contract_address, "transfer_approval_required": True, - "transferable": True + "transferable": True, } bond_contract.update( data=UpdateParams(**update_data), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) # register personal info (to_account) @@ -2231,7 +2285,7 @@ def test_normal_1(self, db): contract_address=personal_info_contract_address, tx_from=to_address, private_key=to_pk, - args=[issuer_address, "test_personal_info"] + args=[issuer_address, "test_personal_info"], ) # apply transfer (from issuer) @@ -2239,18 +2293,15 @@ def test_normal_1(self, db): contract_address=token_address, tx_from=issuer_address, private_key=issuer_pk, - args=[to_address, 10, "test_data"] + args=[to_address, 10, "test_data"], ) # approve transfer (from issuer) - approve_data = { - "application_id": 0, - "data": "approve transfer test" - } + approve_data = {"application_id": 0, "data": "approve transfer test"} tx_hash, tx_receipt = bond_contract.approve_transfer( data=ApproveTransferParams(**approve_data), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) # assertion @@ -2258,8 +2309,7 @@ def test_normal_1(self, db): assert tx_receipt["status"] == 1 bond_token = ContractUtils.get_contract( - contract_name="IbetShare", - contract_address=token_address + contract_name="IbetShare", contract_address=token_address ) applications = bond_token.functions.applicationsForTransfer(0).call() assert applications[0] == issuer_address @@ -2290,14 +2340,11 @@ def test_error_1(self, db): assert ex_info.value.errors() == [ { - 'loc': ('application_id',), - 'msg': 'value is not a valid integer', - 'type': 'type_error.integer' - }, { - 'loc': ('data',), - 'msg': 'field required', - 'type': 'value_error.missing' - } + "loc": ("application_id",), + "msg": "value is not a valid integer", + "type": "type_error.integer", + }, + {"loc": ("data",), "msg": "field required", "type": "value_error.missing"}, ] # @@ -2307,23 +2354,22 @@ def test_error_2(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # Transfer approve - approve_data = { - "application_id": 0, - "data": "test_data" - } + approve_data = {"application_id": 0, "data": "test_data"} _approve_transfer_data = ApproveTransferParams(**approve_data) bond_contract = IbetStraightBondContract("not address") with pytest.raises(SendTransactionError) as ex_info: bond_contract.approve_transfer( data=_approve_transfer_data, tx_from=issuer_address, - private_key=private_key + private_key=private_key, ) - assert ex_info.match("when sending a str, it must be a hex string. Got: 'not address'") + assert ex_info.match( + "when sending a str, it must be a hex string. Got: 'not address'" + ) # # invalid issuer_address : does not exists @@ -2332,7 +2378,7 @@ def test_error_3(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -2345,26 +2391,21 @@ def test_error_3(self, db): 30000, "20211231", "リターン内容", - "発行目的" + "発行目的", ] bond_contract = IbetStraightBondContract() bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # Transfer approve - approve_data = { - "application_id": 0, - "data": "test_data" - } + approve_data = {"application_id": 0, "data": "test_data"} _approve_transfer_data = ApproveTransferParams(**approve_data) with pytest.raises(SendTransactionError) as ex_info: bond_contract.approve_transfer( data=_approve_transfer_data, tx_from=issuer_address[:-1], - private_key=private_key + private_key=private_key, ) assert ex_info.match(f"ENS name: '{issuer_address[:-1]}' is invalid.") @@ -2375,7 +2416,7 @@ def test_error_4(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -2388,26 +2429,21 @@ def test_error_4(self, db): 30000, "20211231", "リターン内容", - "発行目的" + "発行目的", ] bond_contract = IbetStraightBondContract() bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # Transfer approve - approve_data = { - "application_id": 0, - "data": "test_data" - } + approve_data = {"application_id": 0, "data": "test_data"} _approve_transfer_data = ApproveTransferParams(**approve_data) with pytest.raises(SendTransactionError) as ex_info: bond_contract.approve_transfer( data=_approve_transfer_data, tx_from=issuer_address, - private_key="dummy-private" + private_key="dummy-private", ) assert ex_info.match("Non-hexadecimal digit found") @@ -2418,21 +2454,21 @@ def test_error_5(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) to_account = config_eth_account("user2") to_address = to_account.get("address") to_pk = decode_keyfile_json( raw_keyfile_json=to_account.get("keyfile_json"), - password=to_account.get("password").encode("utf-8") + password=to_account.get("password").encode("utf-8"), ) deployer = config_eth_account("user3") deployer_address = deployer.get("address") deployer_pk = decode_keyfile_json( raw_keyfile_json=deployer.get("keyfile_json"), - password=deployer.get("password").encode("utf-8") + password=deployer.get("password").encode("utf-8"), ) # deploy new personal info contract (from deployer) @@ -2440,7 +2476,7 @@ def test_error_5(self, db): contract_name="PersonalInfo", args=[], deployer=deployer_address, - private_key=deployer_pk + private_key=deployer_pk, ) # deploy ibet bond token (from issuer) @@ -2453,25 +2489,23 @@ def test_error_5(self, db): 30000, "20211231", "リターン内容", - "発行目的" + "発行目的", ] bond_contract = IbetStraightBondContract() token_address, _, _ = bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # update token (from issuer) update_data = { "personal_info_contract_address": personal_info_contract_address, "transfer_approval_required": True, - "transferable": True + "transferable": True, } bond_contract.update( data=UpdateParams(**update_data), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) # register personal info (to_account) @@ -2479,7 +2513,7 @@ def test_error_5(self, db): contract_address=personal_info_contract_address, tx_from=to_address, private_key=to_pk, - args=[issuer_address, "test_personal_info"] + args=[issuer_address, "test_personal_info"], ) # apply transfer (from issuer) @@ -2487,18 +2521,15 @@ def test_error_5(self, db): contract_address=token_address, tx_from=issuer_address, private_key=issuer_pk, - args=[to_address, 10, "test_data"] + args=[to_address, 10, "test_data"], ) # approve transfer (from issuer) - approve_data = { - "application_id": 0, - "data": "approve transfer test" - } + approve_data = {"application_id": 0, "data": "approve transfer test"} bond_contract.approve_transfer( data=ApproveTransferParams(**approve_data), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) # Then send approveTransfer transaction again. @@ -2510,14 +2541,14 @@ def test_error_5(self, db): # geth: ContractLogicError("execution reverted") InspectionMock = mock.patch( "web3.eth.Eth.call", - MagicMock(side_effect=ContractLogicError("execution reverted: 120902")) + MagicMock(side_effect=ContractLogicError("execution reverted: 120902")), ) with InspectionMock, pytest.raises(ContractRevertError) as exc_info: bond_contract.approve_transfer( data=ApproveTransferParams(**approve_data), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) # assertion @@ -2525,7 +2556,6 @@ def test_error_5(self, db): class TestCancelTransfer: - ########################################################################### # Normal Case ########################################################################### @@ -2536,21 +2566,21 @@ def test_normal_1(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) to_account = config_eth_account("user2") to_address = to_account.get("address") to_pk = decode_keyfile_json( raw_keyfile_json=to_account.get("keyfile_json"), - password=to_account.get("password").encode("utf-8") + password=to_account.get("password").encode("utf-8"), ) deployer = config_eth_account("user3") deployer_address = deployer.get("address") deployer_pk = decode_keyfile_json( raw_keyfile_json=deployer.get("keyfile_json"), - password=deployer.get("password").encode("utf-8") + password=deployer.get("password").encode("utf-8"), ) # deploy new personal info contract (from deployer) @@ -2558,7 +2588,7 @@ def test_normal_1(self, db): contract_name="PersonalInfo", args=[], deployer=deployer_address, - private_key=deployer_pk + private_key=deployer_pk, ) # deploy ibet bond token (from issuer) @@ -2571,25 +2601,23 @@ def test_normal_1(self, db): 30000, "20211231", "リターン内容", - "発行目的" + "発行目的", ] bond_contract = IbetStraightBondContract() token_address, _, _ = bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # update token (from issuer) update_data = { "personal_info_contract_address": personal_info_contract_address, "transfer_approval_required": True, - "transferable": True + "transferable": True, } bond_contract.update( data=UpdateParams(**update_data), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) # register personal info (to_account) @@ -2597,7 +2625,7 @@ def test_normal_1(self, db): contract_address=personal_info_contract_address, tx_from=to_address, private_key=to_pk, - args=[issuer_address, "test_personal_info"] + args=[issuer_address, "test_personal_info"], ) # apply transfer (from issuer) @@ -2605,28 +2633,22 @@ def test_normal_1(self, db): contract_address=token_address, tx_from=issuer_address, private_key=issuer_pk, - args=[to_address, 10, "test_data"] + args=[to_address, 10, "test_data"], ) # cancel transfer (from issuer) - cancel_data = { - "application_id": 0, - "data": "approve transfer test" - } + cancel_data = {"application_id": 0, "data": "approve transfer test"} _approve_transfer_data = CancelTransferParams(**cancel_data) tx_hash, tx_receipt = bond_contract.cancel_transfer( - data=_approve_transfer_data, - tx_from=issuer_address, - private_key=issuer_pk + data=_approve_transfer_data, tx_from=issuer_address, private_key=issuer_pk ) # assertion assert isinstance(tx_hash, str) and int(tx_hash, 16) > 0 assert tx_receipt["status"] == 1 bond_token = ContractUtils.get_contract( - contract_name="IbetShare", - contract_address=token_address + contract_name="IbetShare", contract_address=token_address ) applications = bond_token.functions.applicationsForTransfer(0).call() assert applications[0] == issuer_address @@ -2656,14 +2678,11 @@ def test_error_1(self, db): assert ex_info.value.errors() == [ { - 'loc': ('application_id',), - 'msg': 'value is not a valid integer', - 'type': 'type_error.integer' - }, { - 'loc': ('data',), - 'msg': 'field required', - 'type': 'value_error.missing' - } + "loc": ("application_id",), + "msg": "value is not a valid integer", + "type": "type_error.integer", + }, + {"loc": ("data",), "msg": "field required", "type": "value_error.missing"}, ] # @@ -2673,23 +2692,22 @@ def test_error_2(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # Transfer cancel - cancel_data = { - "application_id": 0, - "data": "test_data" - } + cancel_data = {"application_id": 0, "data": "test_data"} _cancel_transfer_data = CancelTransferParams(**cancel_data) bond_contract = IbetStraightBondContract("not address") with pytest.raises(SendTransactionError) as ex_info: bond_contract.cancel_transfer( data=_cancel_transfer_data, tx_from=issuer_address, - private_key=private_key + private_key=private_key, ) - assert ex_info.match("when sending a str, it must be a hex string. Got: 'not address'") + assert ex_info.match( + "when sending a str, it must be a hex string. Got: 'not address'" + ) # # invalid issuer_address : does not exists @@ -2698,7 +2716,7 @@ def test_error_3(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -2711,26 +2729,21 @@ def test_error_3(self, db): 30000, "20211231", "リターン内容", - "発行目的" + "発行目的", ] bond_contract = IbetStraightBondContract() contract_address, abi, tx_hash = bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # Transfer cancel - cancel_data = { - "application_id": 0, - "data": "test_data" - } + cancel_data = {"application_id": 0, "data": "test_data"} _cancel_transfer_data = CancelTransferParams(**cancel_data) with pytest.raises(SendTransactionError) as ex_info: bond_contract.cancel_transfer( data=_cancel_transfer_data, tx_from=issuer_address[:-1], - private_key=private_key + private_key=private_key, ) assert ex_info.match(f"ENS name: '{issuer_address[:-1]}' is invalid.") @@ -2741,7 +2754,7 @@ def test_error_4(self, db): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # deploy token @@ -2754,26 +2767,21 @@ def test_error_4(self, db): 30000, "20211231", "リターン内容", - "発行目的" + "発行目的", ] bond_contract = IbetStraightBondContract() contract_address, abi, tx_hash = bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) # Transfer cancel - cancel_data = { - "application_id": 0, - "data": "test_data" - } + cancel_data = {"application_id": 0, "data": "test_data"} _cancel_transfer_data = CancelTransferParams(**cancel_data) with pytest.raises(SendTransactionError) as ex_info: bond_contract.cancel_transfer( data=_cancel_transfer_data, tx_from=issuer_address, - private_key="dummy-private" + private_key="dummy-private", ) assert ex_info.match("Non-hexadecimal digit found") @@ -2784,21 +2792,21 @@ def test_error_5(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) to_account = config_eth_account("user2") to_address = to_account.get("address") to_pk = decode_keyfile_json( raw_keyfile_json=to_account.get("keyfile_json"), - password=to_account.get("password").encode("utf-8") + password=to_account.get("password").encode("utf-8"), ) deployer = config_eth_account("user3") deployer_address = deployer.get("address") deployer_pk = decode_keyfile_json( raw_keyfile_json=deployer.get("keyfile_json"), - password=deployer.get("password").encode("utf-8") + password=deployer.get("password").encode("utf-8"), ) # deploy new personal info contract (from deployer) @@ -2806,7 +2814,7 @@ def test_error_5(self, db): contract_name="PersonalInfo", args=[], deployer=deployer_address, - private_key=deployer_pk + private_key=deployer_pk, ) # deploy ibet bond token (from issuer) @@ -2819,25 +2827,23 @@ def test_error_5(self, db): 30000, "20211231", "リターン内容", - "発行目的" + "発行目的", ] bond_contract = IbetStraightBondContract() token_address, _, _ = bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # update token (from issuer) update_data = { "personal_info_contract_address": personal_info_contract_address, "transfer_approval_required": True, - "transferable": True + "transferable": True, } bond_contract.update( data=UpdateParams(**update_data), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) # register personal info (to_account) @@ -2845,7 +2851,7 @@ def test_error_5(self, db): contract_address=personal_info_contract_address, tx_from=to_address, private_key=to_pk, - args=[issuer_address, "test_personal_info"] + args=[issuer_address, "test_personal_info"], ) # apply transfer (from issuer) @@ -2853,18 +2859,15 @@ def test_error_5(self, db): contract_address=token_address, tx_from=issuer_address, private_key=issuer_pk, - args=[to_address, 10, "test_data"] + args=[to_address, 10, "test_data"], ) # approve transfer (from issuer) - approve_data = { - "application_id": 0, - "data": "approve transfer test" - } + approve_data = {"application_id": 0, "data": "approve transfer test"} bond_contract.approve_transfer( data=ApproveTransferParams(**approve_data), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) # Then send cancelTransfer transaction. This would be failed. @@ -2877,14 +2880,14 @@ def test_error_5(self, db): # geth: ContractLogicError("execution reverted") InspectionMock = mock.patch( "web3.eth.Eth.call", - MagicMock(side_effect=ContractLogicError("execution reverted: 120802")) + MagicMock(side_effect=ContractLogicError("execution reverted: 120802")), ) with InspectionMock, pytest.raises(ContractRevertError) as exc_info: bond_contract.cancel_transfer( data=CancelTransferParams(**cancel_data), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) # assertion @@ -2892,7 +2895,6 @@ def test_error_5(self, db): class TestLock: - ########################################################################### # Normal Case ########################################################################### @@ -2903,7 +2905,7 @@ def test_normal_1(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) lock_account = config_eth_account("user2") @@ -2919,21 +2921,15 @@ def test_normal_1(self, db): 30000, "20211231", "リターン内容", - "発行目的" + "発行目的", ] bond_contract = IbetStraightBondContract() token_address, _, _ = bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # lock - lock_data = { - "lock_address": lock_address, - "value": 10, - "data": "" - } + lock_data = {"lock_address": lock_address, "value": 10, "data": ""} tx_hash, tx_receipt = bond_contract.lock( data=LockParams(**lock_data), tx_from=issuer_address, @@ -2945,10 +2941,11 @@ def test_normal_1(self, db): assert tx_receipt["status"] == 1 share_token = ContractUtils.get_contract( - contract_name="IbetShare", - contract_address=token_address + contract_name="IbetShare", contract_address=token_address ) - lock_amount = share_token.functions.lockedOf(lock_address, issuer_address).call() + lock_amount = share_token.functions.lockedOf( + lock_address, issuer_address + ).call() assert lock_amount == 10 ########################################################################### @@ -2965,19 +2962,12 @@ def test_error_1_1(self, db): assert ex_info.value.errors() == [ { - 'loc': ('lock_address',), - 'msg': 'field required', - 'type': 'value_error.missing' - }, - { - 'loc': ('value',), - 'msg': 'field required', - 'type': 'value_error.missing' + "loc": ("lock_address",), + "msg": "field required", + "type": "value_error.missing", }, - { - 'loc': ('data',), - 'msg': 'field required', - 'type': 'value_error.missing'} + {"loc": ("value",), "msg": "field required", "type": "value_error.missing"}, + {"loc": ("data",), "msg": "field required", "type": "value_error.missing"}, ] # @@ -2985,26 +2975,22 @@ def test_error_1_1(self, db): # - lock_address is not a valid address # - value is not greater than 0 def test_error_1_2(self, db): - lock_data = { - "lock_address": "test_address", - "value": 0, - "data": "" - } + lock_data = {"lock_address": "test_address", "value": 0, "data": ""} with pytest.raises(ValidationError) as ex_info: LockParams(**lock_data) assert ex_info.value.errors() == [ { - 'loc': ('lock_address',), - 'msg': 'lock_address is not a valid address', - 'type': 'value_error' + "loc": ("lock_address",), + "msg": "lock_address is not a valid address", + "type": "value_error", }, { - 'loc': ('value',), - 'msg': 'ensure this value is greater than 0', - 'type': 'value_error.number.not_gt', - 'ctx': {'limit_value': 0} - } + "loc": ("value",), + "msg": "ensure this value is greater than 0", + "type": "value_error.number.not_gt", + "ctx": {"limit_value": 0}, + }, ] # @@ -3015,7 +3001,7 @@ def test_error_2_1(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) lock_account = config_eth_account("user2") @@ -3031,21 +3017,15 @@ def test_error_2_1(self, db): 30000, "20211231", "リターン内容", - "発行目的" + "発行目的", ] bond_contract = IbetStraightBondContract() token_address, _, _ = bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # lock - lock_data = { - "lock_address": lock_address, - "value": 10, - "data": "" - } + lock_data = {"lock_address": lock_address, "value": 10, "data": ""} with pytest.raises(SendTransactionError) as exc_info: bond_contract.lock( data=LockParams(**lock_data), @@ -3054,7 +3034,7 @@ def test_error_2_1(self, db): ) assert isinstance(exc_info.value.args[0], InvalidAddress) - assert exc_info.match("ENS name: \'invalid_tx_from\' is invalid.") + assert exc_info.match("ENS name: 'invalid_tx_from' is invalid.") # # SendTransactionError @@ -3064,7 +3044,7 @@ def test_error_2_2(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) lock_account = config_eth_account("user2") @@ -3080,21 +3060,15 @@ def test_error_2_2(self, db): 30000, "20211231", "リターン内容", - "発行目的" + "発行目的", ] bond_contract = IbetStraightBondContract() token_address, _, _ = bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # lock - lock_data = { - "lock_address": lock_address, - "value": 10, - "data": "" - } + lock_data = {"lock_address": lock_address, "value": 10, "data": ""} with pytest.raises(SendTransactionError) as exc_info: bond_contract.lock( data=LockParams(**lock_data), @@ -3113,7 +3087,7 @@ def test_error_3(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) lock_account = config_eth_account("user2") @@ -3129,33 +3103,27 @@ def test_error_3(self, db): 30000, "20211231", "リターン内容", - "発行目的" + "発行目的", ] bond_contract = IbetStraightBondContract() token_address, _, _ = bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # mock Web3_send_raw_transaction = patch( target="web3.eth.Eth.wait_for_transaction_receipt", - side_effect=TimeExhausted + side_effect=TimeExhausted, ) # lock - lock_data = { - "lock_address": lock_address, - "value": 10, - "data": "" - } + lock_data = {"lock_address": lock_address, "value": 10, "data": ""} with Web3_send_raw_transaction: with pytest.raises(SendTransactionError) as exc_info: bond_contract.lock( data=LockParams(**lock_data), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) assert exc_info.type(SendTransactionError(TimeExhausted)) @@ -3168,7 +3136,7 @@ def test_error_4(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) lock_account = config_eth_account("user2") @@ -3184,33 +3152,27 @@ def test_error_4(self, db): 30000, "20211231", "リターン内容", - "発行目的" + "発行目的", ] bond_contract = IbetStraightBondContract() token_address, _, _ = bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # mock Web3_send_raw_transaction = patch( target="web3.eth.Eth.wait_for_transaction_receipt", - side_effect=TransactionNotFound + side_effect=TransactionNotFound, ) # lock - lock_data = { - "lock_address": lock_address, - "value": 10, - "data": "" - } + lock_data = {"lock_address": lock_address, "value": 10, "data": ""} with Web3_send_raw_transaction: with pytest.raises(SendTransactionError) as exc_info: bond_contract.lock( data=LockParams(**lock_data), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) assert exc_info.type(SendTransactionError(TransactionNotFound)) @@ -3222,7 +3184,7 @@ def test_error_5(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) lock_account = config_eth_account("user2") @@ -3238,13 +3200,11 @@ def test_error_5(self, db): 30000, "20211231", "リターン内容", - "発行目的" + "発行目的", ] bond_contract = IbetStraightBondContract() token_address, _, _ = bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # mock @@ -3253,29 +3213,27 @@ def test_error_5(self, db): # geth: ContractLogicError("execution reverted") InspectionMock = mock.patch( "web3.eth.Eth.call", - MagicMock(side_effect=ContractLogicError("execution reverted: 120002")) + MagicMock(side_effect=ContractLogicError("execution reverted: 120002")), ) # lock - lock_data = { - "lock_address": lock_address, - "value": 20001, - "data": "" - } + lock_data = {"lock_address": lock_address, "value": 20001, "data": ""} with InspectionMock, pytest.raises(ContractRevertError) as exc_info: bond_contract.lock( data=LockParams(**lock_data), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) # assertion assert exc_info.value.code == 120002 - assert exc_info.value.message == "Lock amount is greater than message sender balance." + assert ( + exc_info.value.message + == "Lock amount is greater than message sender balance." + ) class TestForceUnlock: - ########################################################################### # Normal Case ########################################################################### @@ -3286,7 +3244,7 @@ def test_normal_1(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) lock_account = config_eth_account("user2") @@ -3302,21 +3260,15 @@ def test_normal_1(self, db): 30000, "20211231", "リターン内容", - "発行目的" + "発行目的", ] bond_contract = IbetStraightBondContract() token_address, _, _ = bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # lock - lock_data = { - "lock_address": lock_address, - "value": 10, - "data": "" - } + lock_data = {"lock_address": lock_address, "value": 10, "data": ""} bond_contract.lock( data=LockParams(**lock_data), tx_from=issuer_address, @@ -3329,7 +3281,7 @@ def test_normal_1(self, db): "account_address": issuer_address, "recipient_address": issuer_address, "value": 5, - "data": "" + "data": "", } tx_hash, tx_receipt = bond_contract.force_unlock( data=ForceUnlockPrams(**lock_data), @@ -3342,10 +3294,11 @@ def test_normal_1(self, db): assert tx_receipt["status"] == 1 share_token = ContractUtils.get_contract( - contract_name="IbetShare", - contract_address=token_address + contract_name="IbetShare", contract_address=token_address ) - lock_amount = share_token.functions.lockedOf(lock_address, issuer_address).call() + lock_amount = share_token.functions.lockedOf( + lock_address, issuer_address + ).call() assert lock_amount == 5 ########################################################################### @@ -3362,30 +3315,22 @@ def test_error_1_1(self, db): assert ex_info.value.errors() == [ { - 'loc': ('lock_address',), - 'msg': 'field required', - 'type': 'value_error.missing' - }, - { - 'loc': ('account_address',), - 'msg': 'field required', - 'type': 'value_error.missing' + "loc": ("lock_address",), + "msg": "field required", + "type": "value_error.missing", }, { - 'loc': ('recipient_address',), - 'msg': 'field required', - 'type': 'value_error.missing' + "loc": ("account_address",), + "msg": "field required", + "type": "value_error.missing", }, { - 'loc': ('value',), - 'msg': 'field required', - 'type': 'value_error.missing' + "loc": ("recipient_address",), + "msg": "field required", + "type": "value_error.missing", }, - { - 'loc': ('data',), - 'msg': 'field required', - 'type': 'value_error.missing' - } + {"loc": ("value",), "msg": "field required", "type": "value_error.missing"}, + {"loc": ("data",), "msg": "field required", "type": "value_error.missing"}, ] # @@ -3398,33 +3343,33 @@ def test_error_1_2(self, db): "account_address": "test_address", "recipient_address": "test_address", "value": 0, - "data": "" + "data": "", } with pytest.raises(ValidationError) as ex_info: ForceUnlockPrams(**lock_data) assert ex_info.value.errors() == [ { - 'loc': ('lock_address',), - 'msg': 'lock_address is not a valid address', - 'type': 'value_error' + "loc": ("lock_address",), + "msg": "lock_address is not a valid address", + "type": "value_error", }, { - 'loc': ('account_address',), - 'msg': 'account_address is not a valid address', - 'type': 'value_error' + "loc": ("account_address",), + "msg": "account_address is not a valid address", + "type": "value_error", }, { - 'loc': ('recipient_address',), - 'msg': 'recipient_address is not a valid address', - 'type': 'value_error' + "loc": ("recipient_address",), + "msg": "recipient_address is not a valid address", + "type": "value_error", }, { - 'loc': ('value',), - 'msg': 'ensure this value is greater than 0', - 'type': 'value_error.number.not_gt', - 'ctx': {'limit_value': 0} - } + "loc": ("value",), + "msg": "ensure this value is greater than 0", + "type": "value_error.number.not_gt", + "ctx": {"limit_value": 0}, + }, ] # @@ -3435,7 +3380,7 @@ def test_error_2_1(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) lock_account = config_eth_account("user2") @@ -3451,21 +3396,15 @@ def test_error_2_1(self, db): 30000, "20211231", "リターン内容", - "発行目的" + "発行目的", ] bond_contract = IbetStraightBondContract() token_address, _, _ = bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # lock - lock_data = { - "lock_address": lock_address, - "value": 10, - "data": "" - } + lock_data = {"lock_address": lock_address, "value": 10, "data": ""} bond_contract.lock( data=LockParams(**lock_data), tx_from=issuer_address, @@ -3478,7 +3417,7 @@ def test_error_2_1(self, db): "account_address": issuer_address, "recipient_address": issuer_address, "value": 5, - "data": "" + "data": "", } with pytest.raises(SendTransactionError) as exc_info: bond_contract.force_unlock( @@ -3488,7 +3427,7 @@ def test_error_2_1(self, db): ) assert isinstance(exc_info.value.args[0], InvalidAddress) - assert exc_info.match("ENS name: \'invalid_tx_from\' is invalid.") + assert exc_info.match("ENS name: 'invalid_tx_from' is invalid.") # # SendTransactionError @@ -3498,7 +3437,7 @@ def test_error_2_2(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) lock_account = config_eth_account("user2") @@ -3514,21 +3453,15 @@ def test_error_2_2(self, db): 30000, "20211231", "リターン内容", - "発行目的" + "発行目的", ] bond_contract = IbetStraightBondContract() token_address, _, _ = bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # lock - lock_data = { - "lock_address": lock_address, - "value": 10, - "data": "" - } + lock_data = {"lock_address": lock_address, "value": 10, "data": ""} bond_contract.lock( data=LockParams(**lock_data), tx_from=issuer_address, @@ -3541,7 +3474,7 @@ def test_error_2_2(self, db): "account_address": issuer_address, "recipient_address": issuer_address, "value": 5, - "data": "" + "data": "", } with pytest.raises(SendTransactionError) as exc_info: bond_contract.force_unlock( @@ -3561,7 +3494,7 @@ def test_error_3(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) lock_account = config_eth_account("user2") @@ -3577,21 +3510,15 @@ def test_error_3(self, db): 30000, "20211231", "リターン内容", - "発行目的" + "発行目的", ] bond_contract = IbetStraightBondContract() token_address, _, _ = bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # lock - lock_data = { - "lock_address": lock_address, - "value": 10, - "data": "" - } + lock_data = {"lock_address": lock_address, "value": 10, "data": ""} bond_contract.lock( data=LockParams(**lock_data), tx_from=issuer_address, @@ -3601,7 +3528,7 @@ def test_error_3(self, db): # mock Web3_send_raw_transaction = patch( target="web3.eth.Eth.wait_for_transaction_receipt", - side_effect=TimeExhausted + side_effect=TimeExhausted, ) # forceUnlock @@ -3610,14 +3537,14 @@ def test_error_3(self, db): "account_address": issuer_address, "recipient_address": issuer_address, "value": 5, - "data": "" + "data": "", } with Web3_send_raw_transaction: with pytest.raises(SendTransactionError) as exc_info: bond_contract.force_unlock( data=ForceUnlockPrams(**lock_data), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) assert exc_info.type(SendTransactionError(TimeExhausted)) @@ -3630,7 +3557,7 @@ def test_error_4(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) lock_account = config_eth_account("user2") @@ -3646,21 +3573,15 @@ def test_error_4(self, db): 30000, "20211231", "リターン内容", - "発行目的" + "発行目的", ] bond_contract = IbetStraightBondContract() token_address, _, _ = bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # lock - lock_data = { - "lock_address": lock_address, - "value": 10, - "data": "" - } + lock_data = {"lock_address": lock_address, "value": 10, "data": ""} bond_contract.lock( data=LockParams(**lock_data), tx_from=issuer_address, @@ -3670,7 +3591,7 @@ def test_error_4(self, db): # mock Web3_send_raw_transaction = patch( target="web3.eth.Eth.wait_for_transaction_receipt", - side_effect=TransactionNotFound + side_effect=TransactionNotFound, ) # forceUnlock @@ -3679,14 +3600,14 @@ def test_error_4(self, db): "account_address": issuer_address, "recipient_address": issuer_address, "value": 5, - "data": "" + "data": "", } with Web3_send_raw_transaction: with pytest.raises(SendTransactionError) as exc_info: bond_contract.force_unlock( data=ForceUnlockPrams(**lock_data), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) assert exc_info.type(SendTransactionError(TransactionNotFound)) @@ -3698,7 +3619,7 @@ def test_error_5(self, db): issuer_address = issuer.get("address") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer.get("keyfile_json"), - password=issuer.get("password").encode("utf-8") + password=issuer.get("password").encode("utf-8"), ) lock_account = config_eth_account("user2") @@ -3714,21 +3635,15 @@ def test_error_5(self, db): 30000, "20211231", "リターン内容", - "発行目的" + "発行目的", ] bond_contract = IbetStraightBondContract() token_address, _, _ = bond_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=issuer_pk + args=arguments, tx_from=issuer_address, private_key=issuer_pk ) # lock - lock_data = { - "lock_address": lock_address, - "value": 10, - "data": "" - } + lock_data = {"lock_address": lock_address, "value": 10, "data": ""} bond_contract.lock( data=LockParams(**lock_data), tx_from=issuer_address, @@ -3741,7 +3656,7 @@ def test_error_5(self, db): # geth: ContractLogicError("execution reverted") InspectionMock = mock.patch( "web3.eth.Eth.call", - MagicMock(side_effect=ContractLogicError("execution reverted: 121201")) + MagicMock(side_effect=ContractLogicError("execution reverted: 121201")), ) # forceUnlock @@ -3750,13 +3665,13 @@ def test_error_5(self, db): "account_address": issuer_address, "recipient_address": issuer_address, "value": 11, - "data": "" + "data": "", } with InspectionMock, pytest.raises(ContractRevertError) as exc_info: bond_contract.force_unlock( data=ForceUnlockPrams(**lock_data), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) # assertion diff --git a/tests/model/blockchain/test_token_list.py b/tests/model/blockchain/test_token_list.py index 65396a87..0cbdd401 100755 --- a/tests/model/blockchain/test_token_list.py +++ b/tests/model/blockchain/test_token_list.py @@ -19,23 +19,20 @@ from binascii import Error from unittest import mock +from unittest.mock import MagicMock, patch import pytest -from unittest.mock import patch, MagicMock from eth_keyfile import decode_keyfile_json from web3 import Web3 -from web3.exceptions import InvalidAddress, ValidationError, ContractLogicError +from web3.exceptions import ContractLogicError, InvalidAddress, ValidationError from web3.middleware import geth_poa_middleware import config -from app.exceptions import SendTransactionError, ContractRevertError -from app.model.blockchain import ( - IbetStraightBondContract, - IbetShareContract -) +from app.exceptions import ContractRevertError, SendTransactionError +from app.model.blockchain import IbetShareContract, IbetStraightBondContract from app.model.blockchain.token_list import TokenListContract -from app.utils.contract_utils import ContractUtils from app.model.db import TokenType +from app.utils.contract_utils import ContractUtils from config import WEB3_HTTP_PROVIDER, ZERO_ADDRESS from tests.account_config import config_eth_account @@ -49,13 +46,13 @@ def contract_list(db): deployer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) contract_address, abi, tx_hash = ContractUtils.deploy_contract( contract_name="TokenList", args=[], deployer=deployer_address, - private_key=private_key + private_key=private_key, ) config.TOKEN_LIST_CONTRACT_ADDRESS = contract_address @@ -70,7 +67,7 @@ def test_normal_1(self, db, contract_list): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # execute the function @@ -83,26 +80,24 @@ def test_normal_1(self, db, contract_list): "20211231", "20211231", "20221231", - 10000 + 10000, ] share_contract = IbetShareContract() share_token_address, abi, tx_hash = share_contract.create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) TokenListContract(config.TOKEN_LIST_CONTRACT_ADDRESS).register( token_address=share_token_address, token_template=TokenType.IBET_SHARE.value, tx_from=issuer_address, - private_key=private_key + private_key=private_key, ) # assertion : list length token_list_contract = ContractUtils.get_contract( contract_name="TokenList", - contract_address=config.TOKEN_LIST_CONTRACT_ADDRESS + contract_address=config.TOKEN_LIST_CONTRACT_ADDRESS, ) assert token_list_contract.functions.getListLength().call() == 1 @@ -116,32 +111,34 @@ def test_normal_1(self, db, contract_list): 30000, "20211231", "リターン内容", - "発行目的" + "発行目的", ] bond_token_address, abi, tx_hash = IbetStraightBondContract().create( - args=arguments, - tx_from=issuer_address, - private_key=private_key + args=arguments, tx_from=issuer_address, private_key=private_key ) TokenListContract(config.TOKEN_LIST_CONTRACT_ADDRESS).register( token_address=bond_token_address, token_template=TokenType.IBET_STRAIGHT_BOND.value, tx_from=issuer_address, - private_key=private_key + private_key=private_key, ) # assertion token_list_contract = ContractUtils.get_contract( contract_name="TokenList", - contract_address=config.TOKEN_LIST_CONTRACT_ADDRESS + contract_address=config.TOKEN_LIST_CONTRACT_ADDRESS, ) assert token_list_contract.functions.getListLength().call() == 2 - _share_token = token_list_contract.functions.getTokenByAddress(share_token_address).call() + _share_token = token_list_contract.functions.getTokenByAddress( + share_token_address + ).call() assert _share_token[0] == share_token_address assert _share_token[1] == TokenType.IBET_SHARE.value assert _share_token[2] == issuer_address - _bond_token = token_list_contract.functions.getTokenByAddress(bond_token_address).call() + _bond_token = token_list_contract.functions.getTokenByAddress( + bond_token_address + ).call() assert _bond_token[0] == bond_token_address assert _bond_token[1] == TokenType.IBET_STRAIGHT_BOND.value assert _bond_token[2] == issuer_address @@ -155,7 +152,7 @@ def test_error_1(self, db, contract_list): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) with pytest.raises(SendTransactionError) as exc_info: @@ -163,7 +160,7 @@ def test_error_1(self, db, contract_list): token_address="dummy_token_address", token_template=TokenType.IBET_SHARE.value, tx_from=issuer_address, - private_key=private_key + private_key=private_key, ) assert isinstance(exc_info.value.args[0], ValidationError) @@ -173,7 +170,7 @@ def test_error_2(self, db, contract_list): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) with pytest.raises(SendTransactionError) as exc_info: @@ -181,7 +178,7 @@ def test_error_2(self, db, contract_list): token_address=ZERO_ADDRESS, token_template=TokenType.IBET_STRAIGHT_BOND.value, tx_from=issuer_address, - private_key=private_key + private_key=private_key, ) assert isinstance(exc_info.value.args[0], ValueError) @@ -191,7 +188,7 @@ def test_error_3(self, db, contract_list): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) with pytest.raises(SendTransactionError) as exc_info: @@ -199,7 +196,7 @@ def test_error_3(self, db, contract_list): token_address=ZERO_ADDRESS, token_template=TokenType.IBET_SHARE.value, tx_from=issuer_address[:-1], - private_key=private_key + private_key=private_key, ) assert isinstance(exc_info.value.args[0], InvalidAddress) @@ -213,7 +210,7 @@ def test_error_4(self, db, contract_list): token_address=ZERO_ADDRESS, token_template=TokenType.IBET_SHARE.value, tx_from=issuer_address, - private_key="not private key" + private_key="not private key", ) assert isinstance(exc_info.value.args[0], Error) @@ -223,13 +220,13 @@ def test_error_5(self, db, contract_list): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # mock ContractUtils_send_transaction = patch( target="app.utils.contract_utils.ContractUtils.send_transaction", - side_effect=SendTransactionError() + side_effect=SendTransactionError(), ) # execute the function @@ -239,7 +236,7 @@ def test_error_5(self, db, contract_list): token_address=ZERO_ADDRESS, token_template=TokenType.IBET_SHARE.value, tx_from=issuer_address, - private_key=private_key + private_key=private_key, ) # Transaction REVERT(token address is zero) @@ -248,7 +245,7 @@ def test_error_6(self, db, contract_list): issuer_address = test_account.get("address") private_key = decode_keyfile_json( raw_keyfile_json=test_account.get("keyfile_json"), - password=test_account.get("password").encode("utf-8") + password=test_account.get("password").encode("utf-8"), ) # mock @@ -257,7 +254,7 @@ def test_error_6(self, db, contract_list): # geth: ContractLogicError("execution reverted") InspectionMock = mock.patch( "web3.eth.Eth.call", - MagicMock(side_effect=ContractLogicError("execution reverted: 100001")) + MagicMock(side_effect=ContractLogicError("execution reverted: 100001")), ) # execute the function @@ -266,7 +263,7 @@ def test_error_6(self, db, contract_list): token_address=ZERO_ADDRESS, token_template=TokenType.IBET_SHARE.value, tx_from=issuer_address, - private_key=private_key + private_key=private_key, ) # assertion diff --git a/tests/test_app_routers_accounts_GET.py b/tests/test_app_routers_accounts_GET.py index 3b4cb7b1..3100f78e 100644 --- a/tests/test_app_routers_accounts_GET.py +++ b/tests/test_app_routers_accounts_GET.py @@ -50,7 +50,7 @@ def test_normal_1(self, client, db): "issuer_address": _admin_account["address"], "rsa_public_key": None, "rsa_status": AccountRsaStatus.UNSET.value, - "is_deleted": False + "is_deleted": False, } ] @@ -78,7 +78,7 @@ def test_normal_2(self, client, db): "issuer_address": _admin_account["address"], "rsa_public_key": _admin_account["rsa_public_key"], "rsa_status": AccountRsaStatus.CHANGING.value, - "is_deleted": False + "is_deleted": False, } ] diff --git a/tests/test_app_routers_accounts_POST.py b/tests/test_app_routers_accounts_POST.py index 0265178e..49ec03ba 100644 --- a/tests/test_app_routers_accounts_POST.py +++ b/tests/test_app_routers_accounts_POST.py @@ -17,12 +17,11 @@ SPDX-License-Identifier: Apache-2.0 """ import base64 - from unittest import mock -from config import EOA_PASSWORD_PATTERN_MSG from app.model.db import Account, AccountRsaStatus from app.utils.e2ee_utils import E2EEUtils +from config import EOA_PASSWORD_PATTERN_MSG class TestAppRoutersAccountsPOST: @@ -41,9 +40,7 @@ def test_normal_1(self, client, db): accounts_before = db.query(Account).all() password = self.valid_password - req_param = { - "eoa_password": E2EEUtils.encrypt(password) - } + req_param = {"eoa_password": E2EEUtils.encrypt(password)} resp = client.post(self.apiurl, json=req_param) @@ -76,21 +73,15 @@ def test_normal_2(self, boto3_mock, client, db): accounts_before = db.query(Account).all() password = self.valid_password - req_param = { - "eoa_password": E2EEUtils.encrypt(password) - } + req_param = {"eoa_password": E2EEUtils.encrypt(password)} # mock class KMSClientMock: def generate_random(self, NumberOfBytes): assert NumberOfBytes == 32 - return { - "Plaintext": b"12345678901234567890123456789012" - } + return {"Plaintext": b"12345678901234567890123456789012"} - boto3_mock.side_effect = [ - KMSClientMock() - ] + boto3_mock.side_effect = [KMSClientMock()] resp = client.post(self.apiurl, json=req_param) @@ -131,32 +122,26 @@ def test_error_1(self, client, db): # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, - "detail": [{ - "loc": ["body", "eoa_password"], - "msg": "eoa_password is not a Base64-encoded encrypted data", - "type": "value_error" - }] + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ + { + "loc": ["body", "eoa_password"], + "msg": "eoa_password is not a Base64-encoded encrypted data", + "type": "value_error", + } + ], } # # Invalid Password def test_error_2(self, client, db): - req_param = { - "eoa_password": E2EEUtils.encrypt(self.invalid_password) - } + req_param = {"eoa_password": E2EEUtils.encrypt(self.invalid_password)} resp = client.post(self.apiurl, json=req_param) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": EOA_PASSWORD_PATTERN_MSG + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": EOA_PASSWORD_PATTERN_MSG, } diff --git a/tests/test_app_routers_accounts_{issuer_address}_DELETE.py b/tests/test_app_routers_accounts_{issuer_address}_DELETE.py index e987284d..b4d49b95 100644 --- a/tests/test_app_routers_accounts_{issuer_address}_DELETE.py +++ b/tests/test_app_routers_accounts_{issuer_address}_DELETE.py @@ -21,7 +21,6 @@ class TestAppRoutersAccountsIssuerAddressDELETE: - # target API endpoint base_url = "/accounts/{}" @@ -52,7 +51,7 @@ def test_normal_1(self, client, db): "issuer_address": _admin_account["address"], "rsa_public_key": None, "rsa_status": AccountRsaStatus.UNSET.value, - "is_deleted": True + "is_deleted": True, } _account_after = db.query(Account).first() assert _account_after.issuer_address == _admin_account["address"] @@ -71,8 +70,6 @@ def test_error_1(self, client, db): # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, "title": "NotFound" - }, - "detail": "issuer does not exist" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "issuer does not exist", } diff --git a/tests/test_app_routers_accounts_{issuer_address}_GET.py b/tests/test_app_routers_accounts_{issuer_address}_GET.py index 620b39d0..a97ec05a 100644 --- a/tests/test_app_routers_accounts_{issuer_address}_GET.py +++ b/tests/test_app_routers_accounts_{issuer_address}_GET.py @@ -49,7 +49,7 @@ def test_normal_1(self, client, db): "issuer_address": _admin_account["address"], "rsa_public_key": None, "rsa_status": AccountRsaStatus.UNSET.value, - "is_deleted": False + "is_deleted": False, } # @@ -75,7 +75,7 @@ def test_normal_2(self, client, db): "issuer_address": _admin_account["address"], "rsa_public_key": _admin_account["rsa_public_key"], "rsa_status": AccountRsaStatus.CHANGING.value, - "is_deleted": False + "is_deleted": False, } ########################################################################### @@ -89,8 +89,6 @@ def test_error_1(self, client, db): assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, "title": "NotFound" - }, - "detail": "issuer does not exist" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "issuer does not exist", } diff --git a/tests/test_app_routers_accounts_{issuer_address}_authtoken_DELETE.py b/tests/test_app_routers_accounts_{issuer_address}_authtoken_DELETE.py index 3a52d475..e7380530 100644 --- a/tests/test_app_routers_accounts_{issuer_address}_authtoken_DELETE.py +++ b/tests/test_app_routers_accounts_{issuer_address}_authtoken_DELETE.py @@ -57,15 +57,17 @@ def test_normal_1(self, client, db): # request target api resp = client.delete( self.apiurl.format(test_account["address"]), - headers={"eoa-password": E2EEUtils.encrypt(self.eoa_password)} + headers={"eoa-password": E2EEUtils.encrypt(self.eoa_password)}, ) # assertion assert resp.status_code == 200 - auth_token: AuthToken = db.query(AuthToken). \ - filter(AuthToken.issuer_address == test_account["address"]). \ - first() + auth_token: AuthToken = ( + db.query(AuthToken) + .filter(AuthToken.issuer_address == test_account["address"]) + .first() + ) assert auth_token is None # Normal_2 @@ -89,15 +91,17 @@ def test_normal_2(self, client, db): # request target api resp = client.delete( self.apiurl.format(test_account["address"]), - headers={"auth-token": self.auth_token} + headers={"auth-token": self.auth_token}, ) # assertion assert resp.status_code == 200 - auth_token: AuthToken = db.query(AuthToken). \ - filter(AuthToken.issuer_address == test_account["address"]). \ - first() + auth_token: AuthToken = ( + db.query(AuthToken) + .filter(AuthToken.issuer_address == test_account["address"]) + .first() + ) assert auth_token is None ########################################################################### @@ -127,28 +131,27 @@ def test_error_1(self, client, db): # request target api resp = client.delete( self.apiurl.format(test_account["address"][::-1]), # invalid issue address - headers={"eoa-password": E2EEUtils.encrypt(self.eoa_password)} + headers={"eoa-password": E2EEUtils.encrypt(self.eoa_password)}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['header', 'issuer-address'], - 'msg': 'issuer-address is not a valid address', - 'type': 'value_error' + "loc": ["header", "issuer-address"], + "msg": "issuer-address is not a valid address", + "type": "value_error", } - ] + ], } - auth_token: AuthToken = db.query(AuthToken). \ - filter(AuthToken.issuer_address == test_account["address"]). \ - first() + auth_token: AuthToken = ( + db.query(AuthToken) + .filter(AuthToken.issuer_address == test_account["address"]) + .first() + ) assert auth_token is not None # Error_2 @@ -174,28 +177,27 @@ def test_error_2(self, client, db): # request target api resp = client.delete( self.apiurl.format(test_account["address"]), - headers={"eoa-password": self.eoa_password} + headers={"eoa-password": self.eoa_password}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['header', 'eoa-password'], - 'msg': 'eoa-password is not a Base64-encoded encrypted data', - 'type': 'value_error' + "loc": ["header", "eoa-password"], + "msg": "eoa-password is not a Base64-encoded encrypted data", + "type": "value_error", } - ] + ], } - auth_token: AuthToken = db.query(AuthToken). \ - filter(AuthToken.issuer_address == test_account["address"]). \ - first() + auth_token: AuthToken = ( + db.query(AuthToken) + .filter(AuthToken.issuer_address == test_account["address"]) + .first() + ) assert auth_token is not None # Error_3_1 @@ -226,16 +228,15 @@ def test_error_3_1(self, client, db): # assertion assert resp.status_code == 401 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'AuthorizationError' - }, - 'detail': 'issuer does not exist, or password mismatch' + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } - auth_token: AuthToken = db.query(AuthToken). \ - filter(AuthToken.issuer_address == test_account["address"]). \ - first() + auth_token: AuthToken = ( + db.query(AuthToken) + .filter(AuthToken.issuer_address == test_account["address"]) + .first() + ) assert auth_token is not None # Error_3_2 @@ -261,22 +262,23 @@ def test_error_3_2(self, client, db): # request target api resp = client.delete( self.apiurl.format(test_account["address"]), - headers={"eoa-password": E2EEUtils.encrypt("incorrect_password")} # incorrect password + headers={ + "eoa-password": E2EEUtils.encrypt("incorrect_password") + }, # incorrect password ) # assertion assert resp.status_code == 401 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'AuthorizationError' - }, - 'detail': 'issuer does not exist, or password mismatch' + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } - auth_token: AuthToken = db.query(AuthToken). \ - filter(AuthToken.issuer_address == test_account["address"]). \ - first() + auth_token: AuthToken = ( + db.query(AuthToken) + .filter(AuthToken.issuer_address == test_account["address"]) + .first() + ) assert auth_token is not None # Error_4 @@ -294,15 +296,12 @@ def test_error_4(self, client, db): # request target api resp = client.delete( self.apiurl.format(test_account["address"]), - headers={"eoa-password": E2EEUtils.encrypt(self.eoa_password)} + headers={"eoa-password": E2EEUtils.encrypt(self.eoa_password)}, ) # assertion assert resp.status_code == 404 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'NotFound' - }, - 'detail': 'auth token does not exist' + "meta": {"code": 1, "title": "NotFound"}, + "detail": "auth token does not exist", } diff --git a/tests/test_app_routers_accounts_{issuer_address}_authtoken_POST.py b/tests/test_app_routers_accounts_{issuer_address}_authtoken_POST.py index 8fba3ee6..039c3ffc 100644 --- a/tests/test_app_routers_accounts_{issuer_address}_authtoken_POST.py +++ b/tests/test_app_routers_accounts_{issuer_address}_authtoken_POST.py @@ -48,25 +48,30 @@ def test_normal_1(self, client, db, freezer): db.add(account) # request target api - freezer.move_to('2022-07-15 12:34:56') + freezer.move_to("2022-07-15 12:34:56") resp = client.post( self.apiurl.format(test_account["address"]), json={"valid_duration": 120}, - headers={"eoa-password": E2EEUtils.encrypt(self.eoa_password)} + headers={"eoa-password": E2EEUtils.encrypt(self.eoa_password)}, ) # assertion - auth_token: AuthToken = db.query(AuthToken). \ - filter(AuthToken.issuer_address == test_account["address"]). \ - first() + auth_token: AuthToken = ( + db.query(AuthToken) + .filter(AuthToken.issuer_address == test_account["address"]) + .first() + ) assert auth_token.issuer_address == test_account["address"] assert auth_token.usage_start == datetime(2022, 7, 15, 12, 34, 56) assert auth_token.valid_duration == 120 assert resp.status_code == 200 response = resp.json() - assert hashlib.sha256(response["auth_token"].encode()).hexdigest() == auth_token.auth_token - assert response["usage_start"] == '2022-07-15T21:34:56+09:00' + assert ( + hashlib.sha256(response["auth_token"].encode()).hexdigest() + == auth_token.auth_token + ) + assert response["usage_start"] == "2022-07-15T21:34:56+09:00" assert response["valid_duration"] == 120 # Normal_2 @@ -84,30 +89,37 @@ def test_normal_2(self, client, db, freezer): auth_token = AuthToken() auth_token.issuer_address = test_account["address"] auth_token.auth_token = "hashed_token" - auth_token.usage_start = datetime(2022, 7, 15, 12, 32, 55) # 2022-07-15 12:34:56 - 121sec + auth_token.usage_start = datetime( + 2022, 7, 15, 12, 32, 55 + ) # 2022-07-15 12:34:56 - 121sec auth_token.valid_duration = 120 db.add(auth_token) # request target api - freezer.move_to('2022-07-15 12:34:56') + freezer.move_to("2022-07-15 12:34:56") resp = client.post( self.apiurl.format(test_account["address"]), json={"valid_duration": 120}, - headers={"eoa-password": E2EEUtils.encrypt(self.eoa_password)} + headers={"eoa-password": E2EEUtils.encrypt(self.eoa_password)}, ) # assertion - auth_token: AuthToken = db.query(AuthToken). \ - filter(AuthToken.issuer_address == test_account["address"]). \ - first() + auth_token: AuthToken = ( + db.query(AuthToken) + .filter(AuthToken.issuer_address == test_account["address"]) + .first() + ) assert auth_token.issuer_address == test_account["address"] assert auth_token.usage_start == datetime(2022, 7, 15, 12, 34, 56) assert auth_token.valid_duration == 120 assert resp.status_code == 200 response = resp.json() - assert hashlib.sha256(response["auth_token"].encode()).hexdigest() == auth_token.auth_token - assert response["usage_start"] == '2022-07-15T21:34:56+09:00' + assert ( + hashlib.sha256(response["auth_token"].encode()).hexdigest() + == auth_token.auth_token + ) + assert response["usage_start"] == "2022-07-15T21:34:56+09:00" assert response["valid_duration"] == 120 ########################################################################### @@ -128,31 +140,29 @@ def test_error_1_1(self, client, db, freezer): db.add(account) # request target api - freezer.move_to('2022-07-15 12:34:56') + freezer.move_to("2022-07-15 12:34:56") resp = client.post( - self.apiurl.format(test_account["address"]), - json={"valid_duration": 120} + self.apiurl.format(test_account["address"]), json={"valid_duration": 120} ) # assertion - auth_token = db.query(AuthToken). \ - filter(AuthToken.issuer_address == test_account["address"]). \ - first() + auth_token = ( + db.query(AuthToken) + .filter(AuthToken.issuer_address == test_account["address"]) + .first() + ) assert auth_token is None assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['header', 'eoa-password'], - 'msg': 'field required', - 'type': 'value_error.missing' + "loc": ["header", "eoa-password"], + "msg": "field required", + "type": "value_error.missing", } - ] + ], } # Error_1_2 @@ -169,31 +179,30 @@ def test_error_1_2(self, client, db, freezer): db.add(account) # request target api - freezer.move_to('2022-07-15 12:34:56') + freezer.move_to("2022-07-15 12:34:56") resp = client.post( self.apiurl.format(test_account["address"]), - headers={"eoa-password": E2EEUtils.encrypt(self.eoa_password)} + headers={"eoa-password": E2EEUtils.encrypt(self.eoa_password)}, ) # assertion - auth_token = db.query(AuthToken). \ - filter(AuthToken.issuer_address == test_account["address"]). \ - first() + auth_token = ( + db.query(AuthToken) + .filter(AuthToken.issuer_address == test_account["address"]) + .first() + ) assert auth_token is None assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['body'], - 'msg': 'field required', - 'type': 'value_error.missing' + "loc": ["body"], + "msg": "field required", + "type": "value_error.missing", } - ] + ], } # Error_2 @@ -210,32 +219,31 @@ def test_error_2(self, client, db, freezer): db.add(account) # request target api - freezer.move_to('2022-07-15 12:34:56') + freezer.move_to("2022-07-15 12:34:56") resp = client.post( self.apiurl.format(test_account["address"][::-1]), # invalid address json={"valid_duration": 120}, - headers={"eoa-password": E2EEUtils.encrypt(self.eoa_password)} + headers={"eoa-password": E2EEUtils.encrypt(self.eoa_password)}, ) # assertion - auth_token = db.query(AuthToken). \ - filter(AuthToken.issuer_address == test_account["address"]). \ - first() + auth_token = ( + db.query(AuthToken) + .filter(AuthToken.issuer_address == test_account["address"]) + .first() + ) assert auth_token is None assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['header', 'issuer-address'], - 'msg': 'issuer-address is not a valid address', - 'type': 'value_error' + "loc": ["header", "issuer-address"], + "msg": "issuer-address is not a valid address", + "type": "value_error", } - ] + ], } # Error_3 @@ -252,32 +260,33 @@ def test_error_3(self, client, db, freezer): db.add(account) # request target api - freezer.move_to('2022-07-15 12:34:56') + freezer.move_to("2022-07-15 12:34:56") resp = client.post( self.apiurl.format(test_account["address"]), json={"valid_duration": 120}, - headers={"eoa-password": "not_encrypted_password"} # not encrypted password + headers={ + "eoa-password": "not_encrypted_password" + }, # not encrypted password ) # assertion - auth_token = db.query(AuthToken). \ - filter(AuthToken.issuer_address == test_account["address"]). \ - first() + auth_token = ( + db.query(AuthToken) + .filter(AuthToken.issuer_address == test_account["address"]) + .first() + ) assert auth_token is None assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['header', 'eoa-password'], - 'msg': 'eoa-password is not a Base64-encoded encrypted data', - 'type': 'value_error' + "loc": ["header", "eoa-password"], + "msg": "eoa-password is not a Base64-encoded encrypted data", + "type": "value_error", } - ] + ], } # Error_4_1 @@ -294,32 +303,31 @@ def test_error_4_1(self, client, db, freezer): db.add(account) # request target api - freezer.move_to('2022-07-15 12:34:56') + freezer.move_to("2022-07-15 12:34:56") resp = client.post( self.apiurl.format(test_account["address"]), json={"valid_duration": "invalid_duration"}, - headers={"eoa-password": E2EEUtils.encrypt(self.eoa_password)} + headers={"eoa-password": E2EEUtils.encrypt(self.eoa_password)}, ) # assertion - auth_token = db.query(AuthToken). \ - filter(AuthToken.issuer_address == test_account["address"]). \ - first() + auth_token = ( + db.query(AuthToken) + .filter(AuthToken.issuer_address == test_account["address"]) + .first() + ) assert auth_token is None assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['body', 'valid_duration'], - 'msg': 'value is not a valid integer', - 'type': 'type_error.integer' + "loc": ["body", "valid_duration"], + "msg": "value is not a valid integer", + "type": "type_error.integer", } - ] + ], } # Error_4_2 @@ -336,33 +344,32 @@ def test_error_4_2(self, client, db, freezer): db.add(account) # request target api - freezer.move_to('2022-07-15 12:34:56') + freezer.move_to("2022-07-15 12:34:56") resp = client.post( self.apiurl.format(test_account["address"]), json={"valid_duration": -1}, - headers={"eoa-password": E2EEUtils.encrypt(self.eoa_password)} + headers={"eoa-password": E2EEUtils.encrypt(self.eoa_password)}, ) # assertion - auth_token = db.query(AuthToken). \ - filter(AuthToken.issuer_address == test_account["address"]). \ - first() + auth_token = ( + db.query(AuthToken) + .filter(AuthToken.issuer_address == test_account["address"]) + .first() + ) assert auth_token is None assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['body', 'valid_duration'], - 'msg': 'ensure this value is greater than or equal to 0', - 'type': 'value_error.number.not_ge', - 'ctx': {'limit_value': 0} + "loc": ["body", "valid_duration"], + "msg": "ensure this value is greater than or equal to 0", + "type": "value_error.number.not_ge", + "ctx": {"limit_value": 0}, } - ] + ], } # Error_4_3 @@ -379,33 +386,32 @@ def test_error_4_3(self, client, db, freezer): db.add(account) # request target api - freezer.move_to('2022-07-15 12:34:56') + freezer.move_to("2022-07-15 12:34:56") resp = client.post( self.apiurl.format(test_account["address"]), json={"valid_duration": 259201}, - headers={"eoa-password": E2EEUtils.encrypt(self.eoa_password)} + headers={"eoa-password": E2EEUtils.encrypt(self.eoa_password)}, ) # assertion - auth_token = db.query(AuthToken). \ - filter(AuthToken.issuer_address == test_account["address"]). \ - first() + auth_token = ( + db.query(AuthToken) + .filter(AuthToken.issuer_address == test_account["address"]) + .first() + ) assert auth_token is None assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['body', 'valid_duration'], - 'msg': 'ensure this value is less than or equal to 259200', - 'type': 'value_error.number.not_le', - 'ctx': {'limit_value': 259200} + "loc": ["body", "valid_duration"], + "msg": "ensure this value is less than or equal to 259200", + "type": "value_error.number.not_le", + "ctx": {"limit_value": 259200}, } - ] + ], } # Error_5 @@ -421,26 +427,27 @@ def test_error_5(self, client, db, freezer): db.add(account) # request target api - freezer.move_to('2022-07-15 12:34:56') + freezer.move_to("2022-07-15 12:34:56") resp = client.post( self.apiurl.format(test_account["address"]), json={"valid_duration": 120}, - headers={"eoa-password": E2EEUtils.encrypt("mismatch_password")} # incorrect password + headers={ + "eoa-password": E2EEUtils.encrypt("mismatch_password") + }, # incorrect password ) # assertion - auth_token = db.query(AuthToken). \ - filter(AuthToken.issuer_address == test_account["address"]). \ - first() + auth_token = ( + db.query(AuthToken) + .filter(AuthToken.issuer_address == test_account["address"]) + .first() + ) assert auth_token is None assert resp.status_code == 401 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'AuthorizationError' - }, - 'detail': 'issuer does not exist, or password mismatch' + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # Error_6_1 @@ -464,20 +471,17 @@ def test_error_6_1(self, client, db, freezer): db.add(auth_token) # request target api - freezer.move_to('2022-07-15 12:34:56') + freezer.move_to("2022-07-15 12:34:56") resp = client.post( self.apiurl.format(test_account["address"]), json={"valid_duration": 120}, - headers={"eoa-password": E2EEUtils.encrypt(self.eoa_password)} + headers={"eoa-password": E2EEUtils.encrypt(self.eoa_password)}, ) # assertion assert resp.status_code == 400 assert resp.json() == { - 'meta': { - 'code': 3, - 'title': 'AuthTokenAlreadyExistsError' - } + "meta": {"code": 3, "title": "AuthTokenAlreadyExistsError"} } # Error_6_2 @@ -496,23 +500,22 @@ def test_error_6_2(self, client, db, freezer): auth_token = AuthToken() auth_token.issuer_address = test_account["address"] auth_token.auth_token = "hashed_token" - auth_token.usage_start = datetime(2022, 7, 15, 12, 32, 56) # 2022-07-15 12:34:56 - 120sec + auth_token.usage_start = datetime( + 2022, 7, 15, 12, 32, 56 + ) # 2022-07-15 12:34:56 - 120sec auth_token.valid_duration = 120 db.add(auth_token) # request target api - freezer.move_to('2022-07-15 12:34:56') + freezer.move_to("2022-07-15 12:34:56") resp = client.post( self.apiurl.format(test_account["address"]), json={"valid_duration": 120}, - headers={"eoa-password": E2EEUtils.encrypt(self.eoa_password)} + headers={"eoa-password": E2EEUtils.encrypt(self.eoa_password)}, ) # assertion assert resp.status_code == 400 assert resp.json() == { - 'meta': { - 'code': 3, - 'title': 'AuthTokenAlreadyExistsError' - } + "meta": {"code": 3, "title": "AuthTokenAlreadyExistsError"} } diff --git a/tests/test_app_routers_accounts_{issuer_address}_eoa_password_POST.py b/tests/test_app_routers_accounts_{issuer_address}_eoa_password_POST.py index fac4581d..10c50af8 100644 --- a/tests/test_app_routers_accounts_{issuer_address}_eoa_password_POST.py +++ b/tests/test_app_routers_accounts_{issuer_address}_eoa_password_POST.py @@ -18,13 +18,10 @@ """ import eth_keyfile -from config import EOA_PASSWORD_PATTERN_MSG from app.model.blockchain import IbetStraightBondContract -from app.model.db import ( - Account, - AccountRsaStatus -) +from app.model.db import Account, AccountRsaStatus from app.utils.e2ee_utils import E2EEUtils +from config import EOA_PASSWORD_PATTERN_MSG from tests.account_config import config_eth_account @@ -57,10 +54,7 @@ def test_normal_1(self, client, db): "old_eoa_password": E2EEUtils.encrypt(_old_password), "eoa_password": E2EEUtils.encrypt(_new_password), } - resp = client.post( - self.base_url.format(_issuer_address), - json=req_param - ) + resp = client.post(self.base_url.format(_issuer_address), json=req_param) # assertion assert resp.status_code == 200 @@ -74,7 +68,7 @@ def test_normal_1(self, client, db): # deploy test private_key = eth_keyfile.decode_keyfile_json( raw_keyfile_json=_account_keyfile, - password=_account_eoa_password.encode("utf-8") + password=_account_eoa_password.encode("utf-8"), ) arguments = [ "name_test", @@ -85,12 +79,10 @@ def test_normal_1(self, client, db): 30, "return_date_test", "return_amount_test", - "purpose_test" + "purpose_test", ] IbetStraightBondContract().create( - args=arguments, - tx_from=_issuer_address, - private_key=private_key + args=arguments, tx_from=_issuer_address, private_key=private_key ) ########################################################################### @@ -104,24 +96,19 @@ def test_error_1(self, client, db): _issuer_address = _account["address"] # request target API - resp = client.post( - self.base_url.format(_issuer_address) - ) + resp = client.post(self.base_url.format(_issuer_address)) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, - ] + ], } # @@ -134,30 +121,24 @@ def test_error_2(self, client, db): req_param = { "dummy": "dummy", } - resp = client.post( - self.base_url.format(_issuer_address), - json=req_param - ) + resp = client.post(self.base_url.format(_issuer_address), json=req_param) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "old_eoa_password"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, { "loc": ["body", "eoa_password"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, - ] + ], } # @@ -173,30 +154,24 @@ def test_error_3(self, client, db): "old_eoa_password": _old_password, "eoa_password": _new_password, } - resp = client.post( - self.base_url.format(_issuer_address), - json=req_param - ) + resp = client.post(self.base_url.format(_issuer_address), json=req_param) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "old_eoa_password"], "msg": "old_eoa_password is not a Base64-encoded encrypted data", - "type": "value_error" + "type": "value_error", }, { "loc": ["body", "eoa_password"], "msg": "eoa_password is not a Base64-encoded encrypted data", - "type": "value_error" + "type": "value_error", }, - ] + ], } # @@ -211,17 +186,14 @@ def test_error_4(self, client, db): "eoa_password": E2EEUtils.encrypt(_new_password), } resp = client.post( - self.base_url.format("non_existent_issuer_address"), - json=req_param + self.base_url.format("non_existent_issuer_address"), json=req_param ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, "title": "NotFound" - }, - "detail": "issuer does not exist" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "issuer does not exist", } # @@ -246,18 +218,13 @@ def test_error_5(self, client, db): "old_eoa_password": E2EEUtils.encrypt("passwordtest"), "eoa_password": E2EEUtils.encrypt(_new_password), } - resp = client.post( - self.base_url.format(_issuer_address), - json=req_param - ) + resp = client.post(self.base_url.format(_issuer_address), json=req_param) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, "title": "InvalidParameterError" - }, - "detail": "old password mismatch" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "old password mismatch", } # @@ -282,16 +249,11 @@ def test_error_6(self, client, db): "old_eoa_password": E2EEUtils.encrypt(_old_password), "eoa_password": E2EEUtils.encrypt(_new_password), } - resp = client.post( - self.base_url.format(_issuer_address), - json=req_param - ) + resp = client.post(self.base_url.format(_issuer_address), json=req_param) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, "title": "InvalidParameterError" - }, - "detail": EOA_PASSWORD_PATTERN_MSG + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": EOA_PASSWORD_PATTERN_MSG, } diff --git a/tests/test_app_routers_accounts_{issuer_address}_rsa_passphrase_POST.py b/tests/test_app_routers_accounts_{issuer_address}_rsa_passphrase_POST.py index 7cdeb38f..df7a4bdf 100644 --- a/tests/test_app_routers_accounts_{issuer_address}_rsa_passphrase_POST.py +++ b/tests/test_app_routers_accounts_{issuer_address}_rsa_passphrase_POST.py @@ -19,12 +19,9 @@ from Crypto.Cipher import PKCS1_OAEP from Crypto.PublicKey import RSA -from config import PERSONAL_INFO_RSA_PASSPHRASE_PATTERN_MSG -from app.model.db import ( - Account, - AccountRsaStatus -) +from app.model.db import Account, AccountRsaStatus from app.utils.e2ee_utils import E2EEUtils +from config import PERSONAL_INFO_RSA_PASSPHRASE_PATTERN_MSG from tests.account_config import config_eth_account @@ -62,10 +59,7 @@ def test_normal_1(self, client, db): "old_rsa_passphrase": E2EEUtils.encrypt(_old_password), "rsa_passphrase": E2EEUtils.encrypt(_new_password), } - resp = client.post( - self.base_url.format(_issuer_address), - json=req_param - ) + resp = client.post(self.base_url.format(_issuer_address), json=req_param) # assertion assert resp.status_code == 200 @@ -81,7 +75,9 @@ def test_normal_1(self, client, db): pub_rsa_key = RSA.importKey(_rsa_public_key) pub_cipher = PKCS1_OAEP.new(pub_rsa_key) encrypt_data = pub_cipher.encrypt(test_data.encode("utf-8")) - pri_rsa_key = RSA.importKey(_account_rsa_private_key, passphrase=_account_rsa_passphrase) + pri_rsa_key = RSA.importKey( + _account_rsa_private_key, passphrase=_account_rsa_passphrase + ) pri_cipher = PKCS1_OAEP.new(pri_rsa_key) decrypt_data = pri_cipher.decrypt(encrypt_data).decode() assert decrypt_data == test_data @@ -97,24 +93,19 @@ def test_error_1(self, client, db): _issuer_address = _account["address"] # request target API - resp = client.post( - self.base_url.format(_issuer_address) - ) + resp = client.post(self.base_url.format(_issuer_address)) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, - ] + ], } # @@ -127,30 +118,24 @@ def test_error_2(self, client, db): req_param = { "dummy": "dummy", } - resp = client.post( - self.base_url.format(_issuer_address), - json=req_param - ) + resp = client.post(self.base_url.format(_issuer_address), json=req_param) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "old_rsa_passphrase"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, { "loc": ["body", "rsa_passphrase"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, - ] + ], } # @@ -166,30 +151,24 @@ def test_error_3(self, client, db): "old_rsa_passphrase": _old_password, "rsa_passphrase": _new_password, } - resp = client.post( - self.base_url.format(_issuer_address), - json=req_param - ) + resp = client.post(self.base_url.format(_issuer_address), json=req_param) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "old_rsa_passphrase"], "msg": "old_rsa_passphrase is not a Base64-encoded encrypted data", - "type": "value_error" + "type": "value_error", }, { "loc": ["body", "rsa_passphrase"], "msg": "rsa_passphrase is not a Base64-encoded encrypted data", - "type": "value_error" + "type": "value_error", }, - ] + ], } # @@ -204,17 +183,14 @@ def test_error_4(self, client, db): "rsa_passphrase": E2EEUtils.encrypt(_new_password), } resp = client.post( - self.base_url.format("non_existent_issuer_address"), - json=req_param + self.base_url.format("non_existent_issuer_address"), json=req_param ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, "title": "NotFound" - }, - "detail": "issuer does not exist" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "issuer does not exist", } # @@ -241,18 +217,13 @@ def test_error_5(self, client, db): "old_rsa_passphrase": E2EEUtils.encrypt("passwordtest"), "rsa_passphrase": E2EEUtils.encrypt(_new_password), } - resp = client.post( - self.base_url.format(_issuer_address), - json=req_param - ) + resp = client.post(self.base_url.format(_issuer_address), json=req_param) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, "title": "InvalidParameterError" - }, - "detail": "old passphrase mismatch" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "old passphrase mismatch", } # @@ -279,16 +250,11 @@ def test_error_6(self, client, db): "old_rsa_passphrase": E2EEUtils.encrypt(_old_password), "rsa_passphrase": E2EEUtils.encrypt(_new_password), } - resp = client.post( - self.base_url.format(_issuer_address), - json=req_param - ) + resp = client.post(self.base_url.format(_issuer_address), json=req_param) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, "title": "InvalidParameterError" - }, - "detail": PERSONAL_INFO_RSA_PASSPHRASE_PATTERN_MSG + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": PERSONAL_INFO_RSA_PASSPHRASE_PATTERN_MSG, } diff --git a/tests/test_app_routers_accounts_{issuer_address}_rsakey_POST.py b/tests/test_app_routers_accounts_{issuer_address}_rsakey_POST.py index fb88fca9..4af7227f 100644 --- a/tests/test_app_routers_accounts_{issuer_address}_rsakey_POST.py +++ b/tests/test_app_routers_accounts_{issuer_address}_rsakey_POST.py @@ -16,9 +16,13 @@ SPDX-License-Identifier: Apache-2.0 """ -from config import PERSONAL_INFO_RSA_PASSPHRASE_PATTERN_MSG, PERSONAL_INFO_RSA_DEFAULT_PASSPHRASE, ZERO_ADDRESS from app.model.db import Account, AccountRsaKeyTemporary, AccountRsaStatus from app.utils.e2ee_utils import E2EEUtils +from config import ( + PERSONAL_INFO_RSA_DEFAULT_PASSPHRASE, + PERSONAL_INFO_RSA_PASSPHRASE_PATTERN_MSG, + ZERO_ADDRESS, +) from tests.account_config import config_eth_account @@ -48,9 +52,7 @@ def test_normal_1(self, client, db): db.commit() password = self.valid_password - req_param = { - "rsa_passphrase": E2EEUtils.encrypt(password) - } + req_param = {"rsa_passphrase": E2EEUtils.encrypt(password)} resp = client.post(self.base_url.format(_user_1["address"]), json=req_param) @@ -60,7 +62,7 @@ def test_normal_1(self, client, db): "issuer_address": _user_1["address"], "rsa_public_key": None, "rsa_status": AccountRsaStatus.CREATING.value, - "is_deleted": False + "is_deleted": False, } _account_after = db.query(Account).first() assert _account_after.issuer_address == _user_1["address"] @@ -93,9 +95,7 @@ def test_normal_2(self, client, db): _temporary_before = db.query(AccountRsaKeyTemporary).all() password = self.valid_password - req_param = { - "rsa_passphrase": E2EEUtils.encrypt(password) - } + req_param = {"rsa_passphrase": E2EEUtils.encrypt(password)} resp = client.post(self.base_url.format(_user_1["address"]), json=req_param) @@ -105,7 +105,7 @@ def test_normal_2(self, client, db): "issuer_address": _user_1["address"], "rsa_public_key": _user_1["rsa_public_key"], "rsa_status": AccountRsaStatus.CHANGING.value, - "is_deleted": False + "is_deleted": False, } _temporary_after = db.query(AccountRsaKeyTemporary).all() assert len(_temporary_before) == 0 @@ -148,7 +148,7 @@ def test_normal_3(self, client, db): "issuer_address": _user_1["address"], "rsa_public_key": None, "rsa_status": AccountRsaStatus.CREATING.value, - "is_deleted": False + "is_deleted": False, } _account_after = db.query(Account).first() assert _account_after.issuer_address == _user_1["address"] @@ -156,7 +156,10 @@ def test_normal_3(self, client, db): assert _account_after.eoa_password == eoa_password assert _account_after.rsa_private_key is None assert _account_after.rsa_public_key is None - assert E2EEUtils.decrypt(_account_after.rsa_passphrase) == PERSONAL_INFO_RSA_DEFAULT_PASSPHRASE + assert ( + E2EEUtils.decrypt(_account_after.rsa_passphrase) + == PERSONAL_INFO_RSA_DEFAULT_PASSPHRASE + ) assert _account_after.rsa_status == AccountRsaStatus.CREATING.value ########################################################################### @@ -166,24 +169,19 @@ def test_normal_3(self, client, db): # # Parameter Error: no body def test_error_1(self, client, db): - resp = client.post( - self.base_url.format(ZERO_ADDRESS) - ) + resp = client.post(self.base_url.format(ZERO_ADDRESS)) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", } - ] + ], } # @@ -191,26 +189,21 @@ def test_error_1(self, client, db): def test_error_2(self, client, db): _user_1 = config_eth_account("user1") - req_param = { - "rsa_passphrase": "test" - } + req_param = {"rsa_passphrase": "test"} resp = client.post(self.base_url.format(_user_1["address"]), json=req_param) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "rsa_passphrase"], "msg": "rsa_passphrase is not a Base64-encoded encrypted data", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -228,9 +221,7 @@ def test_error_3(self, client, db): _account.rsa_status = AccountRsaStatus.SET.value db.add(_account) - req_param = { - "rsa_passphrase": E2EEUtils.encrypt(self.valid_password) - } + req_param = {"rsa_passphrase": E2EEUtils.encrypt(self.valid_password)} _user_2 = config_eth_account("user2") resp = client.post(self.base_url.format(_user_2["address"]), json=req_param) @@ -238,11 +229,8 @@ def test_error_3(self, client, db): # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "issuer does not exist" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "issuer does not exist", } # @@ -257,20 +245,15 @@ def test_error_4(self, client, db): _account.rsa_status = AccountRsaStatus.CREATING.value db.add(_account) - req_param = { - "rsa_passphrase": E2EEUtils.encrypt(self.valid_password) - } + req_param = {"rsa_passphrase": E2EEUtils.encrypt(self.valid_password)} resp = client.post(self.base_url.format(_user_1["address"]), json=req_param) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "RSA key is now generating" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "RSA key is now generating", } # @@ -288,20 +271,15 @@ def test_error_5(self, client, db): _account.rsa_status = AccountRsaStatus.CHANGING.value db.add(_account) - req_param = { - "rsa_passphrase": E2EEUtils.encrypt(self.valid_password) - } + req_param = {"rsa_passphrase": E2EEUtils.encrypt(self.valid_password)} resp = client.post(self.base_url.format(_user_1["address"]), json=req_param) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "RSA key is now generating" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "RSA key is now generating", } # @@ -319,18 +297,13 @@ def test_error_6(self, client, db): _account.rsa_status = AccountRsaStatus.SET.value db.add(_account) - req_param = { - "rsa_passphrase": E2EEUtils.encrypt(self.invalid_password) - } + req_param = {"rsa_passphrase": E2EEUtils.encrypt(self.invalid_password)} resp = client.post(self.base_url.format(_user_1["address"]), json=req_param) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": PERSONAL_INFO_RSA_PASSPHRASE_PATTERN_MSG + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": PERSONAL_INFO_RSA_PASSPHRASE_PATTERN_MSG, } diff --git a/tests/test_app_routers_block_number_GET.py b/tests/test_app_routers_block_number_GET.py index edf51aeb..1240f52e 100644 --- a/tests/test_app_routers_block_number_GET.py +++ b/tests/test_app_routers_block_number_GET.py @@ -17,11 +17,10 @@ SPDX-License-Identifier: Apache-2.0 """ from datetime import datetime - from unittest import mock from unittest.mock import MagicMock -from app.exceptions import ServiceUnavailableError +from app.exceptions import ServiceUnavailableError from app.model.db import Node @@ -41,9 +40,7 @@ def test_normal_1(self, client, db): # assertion assert resp.status_code == 200 - assert resp.json() == { - "block_number": 100 - } + assert resp.json() == {"block_number": 100} ########################################################################### # Error Case @@ -51,7 +48,10 @@ def test_normal_1(self, client, db): # # Unable to connect ibet - @mock.patch("web3.eth.BaseEth.get_block_number", MagicMock(side_effect=ServiceUnavailableError(""))) + @mock.patch( + "web3.eth.BaseEth.get_block_number", + MagicMock(side_effect=ServiceUnavailableError("")), + ) def test_error_1(self, client, db): # request target api resp = client.get(self.apiurl) @@ -59,9 +59,6 @@ def test_error_1(self, client, db): # assertion assert resp.status_code == 503 assert resp.json() == { - "meta": { - "code": 1, - "title": "ServiceUnavailableError" - }, - "detail": "" + "meta": {"code": 1, "title": "ServiceUnavailableError"}, + "detail": "", } diff --git a/tests/test_app_routers_blockchain_explorer_block_data_GET.py b/tests/test_app_routers_blockchain_explorer_block_data_GET.py index 5be848e3..89fdaf46 100644 --- a/tests/test_app_routers_blockchain_explorer_block_data_GET.py +++ b/tests/test_app_routers_blockchain_explorer_block_data_GET.py @@ -21,10 +21,7 @@ from fastapi.testclient import TestClient from sqlalchemy.orm import Session -from app.model.db import ( - IDXBlockData, - IDXBlockDataBlockNumber -) +from app.model.db import IDXBlockData, IDXBlockDataBlockNumber from config import CHAIN_ID @@ -34,64 +31,64 @@ class TestListBlockData: # Test data block_0 = { - 'number': 0, - 'difficulty': 1, - 'proof_of_authority_data': '0x0000000000000000000000000000000000000000000000000000000000000000f89af8549447a847fbdf801154253593851ac9a2e7753235349403ee8c85944b16dfa517cb0ddefe123c7341a5349435d56a7515e824be4122f033d60063d035573a0c94c25d04978fd86ee604feb88f3c635d555eb6d42db8410000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c0', - 'gas_limit': 800000000, - 'gas_used': 0, - 'hash': '0x307166a396b99259ed2072f4b99d850e332db4ef4c72656870680728944ad445', - 'logs_bloom': '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', - 'miner': '0x0000000000000000000000000000000000000000', - 'mix_hash': '0x63746963616c2062797a616e74696e65206661756c7420746f6c6572616e6365', - 'nonce': '0x0000000000000000', - 'parent_hash': '0x0000000000000000000000000000000000000000000000000000000000000000', - 'receipts_root': '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', - 'sha3_uncles': '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', - 'size': 698, - 'state_root': '0x260aa025c613224aaa46e2134b6469f3d956c07949a6ca23143936c574838995', - 'timestamp': 1524130695, - 'transactions': [], - 'transactions_root': '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + "number": 0, + "difficulty": 1, + "proof_of_authority_data": "0x0000000000000000000000000000000000000000000000000000000000000000f89af8549447a847fbdf801154253593851ac9a2e7753235349403ee8c85944b16dfa517cb0ddefe123c7341a5349435d56a7515e824be4122f033d60063d035573a0c94c25d04978fd86ee604feb88f3c635d555eb6d42db8410000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c0", + "gas_limit": 800000000, + "gas_used": 0, + "hash": "0x307166a396b99259ed2072f4b99d850e332db4ef4c72656870680728944ad445", + "logs_bloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "miner": "0x0000000000000000000000000000000000000000", + "mix_hash": "0x63746963616c2062797a616e74696e65206661756c7420746f6c6572616e6365", + "nonce": "0x0000000000000000", + "parent_hash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "receipts_root": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", + "sha3_uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", + "size": 698, + "state_root": "0x260aa025c613224aaa46e2134b6469f3d956c07949a6ca23143936c574838995", + "timestamp": 1524130695, + "transactions": [], + "transactions_root": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", } block_1 = { - 'number': 1, - 'difficulty': 1, - 'proof_of_authority_data': '0xd983010907846765746889676f312e31332e3135856c696e7578000000000000f90164f8549403ee8c85944b16dfa517cb0ddefe123c7341a5349435d56a7515e824be4122f033d60063d035573a0c9447a847fbdf801154253593851ac9a2e77532353494c25d04978fd86ee604feb88f3c635d555eb6d42db841d6b123b02f015f4f0b0d47648e22c043dca3f803e6498084522c07ccbea58f8c39e498f6c8c604abb406dc323246c30525cc0dd01c39bcadbb608733bdf3f08300f8c9b84186503892a4b314f2b8aba73b1a7434c69bd95695ac285d5db6d15f879b5dbbf83471502e13eb1d0fce4d2e7ea41be91e8ecf744f0eeb8c808fb2e4a7833377f901b84141f6e74ea7f1365fa01ab90318c066f05b65fe82a2fd856203407653aa242c5875bd016f68d169951aec61958f4ad9654ecc1c8edc686e55c601e3db45f4cc8a01b8414e3259ec82771a0c83d0b5db72c0199549efa80736e6e1f892c50504d187eb505f784cb8623ce475195fe1287ceb85bccf703fca919da23940ce29e4f9f1a7ba01', - 'gas_limit': 800000000, - 'gas_used': 0, - 'hash': '0xa4852f7e1b8ce036b057087e54492524796e0a68bba07a1c110605cf2cb8c01d', - 'logs_bloom': '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', - 'miner': '0x0000000000000000000000000000000000000000', - 'mix_hash': '0x63746963616c2062797a616e74696e65206661756c7420746f6c6572616e6365', - 'nonce': '0x0000000000000000', - 'parent_hash': '0x307166a396b99259ed2072f4b99d850e332db4ef4c72656870680728944ad445', - 'receipts_root': '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', - 'sha3_uncles': '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', - 'size': 902, - 'state_root': '0x260aa025c613224aaa46e2134b6469f3d956c07949a6ca23143936c574838995', - 'timestamp': 1638960161, - 'transactions': [], - 'transactions_root': '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + "number": 1, + "difficulty": 1, + "proof_of_authority_data": "0xd983010907846765746889676f312e31332e3135856c696e7578000000000000f90164f8549403ee8c85944b16dfa517cb0ddefe123c7341a5349435d56a7515e824be4122f033d60063d035573a0c9447a847fbdf801154253593851ac9a2e77532353494c25d04978fd86ee604feb88f3c635d555eb6d42db841d6b123b02f015f4f0b0d47648e22c043dca3f803e6498084522c07ccbea58f8c39e498f6c8c604abb406dc323246c30525cc0dd01c39bcadbb608733bdf3f08300f8c9b84186503892a4b314f2b8aba73b1a7434c69bd95695ac285d5db6d15f879b5dbbf83471502e13eb1d0fce4d2e7ea41be91e8ecf744f0eeb8c808fb2e4a7833377f901b84141f6e74ea7f1365fa01ab90318c066f05b65fe82a2fd856203407653aa242c5875bd016f68d169951aec61958f4ad9654ecc1c8edc686e55c601e3db45f4cc8a01b8414e3259ec82771a0c83d0b5db72c0199549efa80736e6e1f892c50504d187eb505f784cb8623ce475195fe1287ceb85bccf703fca919da23940ce29e4f9f1a7ba01", + "gas_limit": 800000000, + "gas_used": 0, + "hash": "0xa4852f7e1b8ce036b057087e54492524796e0a68bba07a1c110605cf2cb8c01d", + "logs_bloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "miner": "0x0000000000000000000000000000000000000000", + "mix_hash": "0x63746963616c2062797a616e74696e65206661756c7420746f6c6572616e6365", + "nonce": "0x0000000000000000", + "parent_hash": "0x307166a396b99259ed2072f4b99d850e332db4ef4c72656870680728944ad445", + "receipts_root": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", + "sha3_uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", + "size": 902, + "state_root": "0x260aa025c613224aaa46e2134b6469f3d956c07949a6ca23143936c574838995", + "timestamp": 1638960161, + "transactions": [], + "transactions_root": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", } block_2 = { - 'number': 2, - 'difficulty': 1, - 'proof_of_authority_data': '0xd983010907846765746889676f312e31332e3135856c696e7578000000000000f90164f8549403ee8c85944b16dfa517cb0ddefe123c7341a5349435d56a7515e824be4122f033d60063d035573a0c9447a847fbdf801154253593851ac9a2e77532353494c25d04978fd86ee604feb88f3c635d555eb6d42db8416ac645ecda42d11985f8d00d25664e336e8588d3bf595a88eb78ef200e5aa0f732a4822141420fba7ccf33248ed5a45038334c5e50561779e427a4fe4b04b08a00f8c9b8415568d4c4a3edcafaed146a43dc7046d9fcd31d5f6d64f8dcf581ba473b868f5145129066188ffef9b8a9e9065d13fa96a81f1196bad98393a70f6461245c097a01b841ea249f9f16bc3c5a13de6df4be7b6933b4908395d1517f7099cc7718ec438a8744aaa356584a3929d1dec2d596268ddbd29d476954d2080b94f82b07b223492300b841804f0f78afa930c7249a81cc3a7a2810098803c6f6cb4c2ed3778c1a0c35962e57c8a1328f670362cfbe3f30e58cac7d78f9059e379bd9c195afecb27b907faf01', - 'gas_limit': 800000000, - 'gas_used': 0, - 'hash': '0x8aade0ef6b0c8a2854b7d71503fe74b8a1edc13e95f7f117467ec2a327ea6f99', - 'logs_bloom': '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', - 'miner': '0x0000000000000000000000000000000000000000', - 'mix_hash': '0x63746963616c2062797a616e74696e65206661756c7420746f6c6572616e6365', - 'nonce': '0x0000000000000000', - 'parent_hash': '0xa4852f7e1b8ce036b057087e54492524796e0a68bba07a1c110605cf2cb8c01d', - 'receipts_root': '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', - 'sha3_uncles': '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', - 'size': 902, - 'state_root': '0x260aa025c613224aaa46e2134b6469f3d956c07949a6ca23143936c574838995', - 'timestamp': 1638960172, - 'transactions': [], - 'transactions_root': '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + "number": 2, + "difficulty": 1, + "proof_of_authority_data": "0xd983010907846765746889676f312e31332e3135856c696e7578000000000000f90164f8549403ee8c85944b16dfa517cb0ddefe123c7341a5349435d56a7515e824be4122f033d60063d035573a0c9447a847fbdf801154253593851ac9a2e77532353494c25d04978fd86ee604feb88f3c635d555eb6d42db8416ac645ecda42d11985f8d00d25664e336e8588d3bf595a88eb78ef200e5aa0f732a4822141420fba7ccf33248ed5a45038334c5e50561779e427a4fe4b04b08a00f8c9b8415568d4c4a3edcafaed146a43dc7046d9fcd31d5f6d64f8dcf581ba473b868f5145129066188ffef9b8a9e9065d13fa96a81f1196bad98393a70f6461245c097a01b841ea249f9f16bc3c5a13de6df4be7b6933b4908395d1517f7099cc7718ec438a8744aaa356584a3929d1dec2d596268ddbd29d476954d2080b94f82b07b223492300b841804f0f78afa930c7249a81cc3a7a2810098803c6f6cb4c2ed3778c1a0c35962e57c8a1328f670362cfbe3f30e58cac7d78f9059e379bd9c195afecb27b907faf01", + "gas_limit": 800000000, + "gas_used": 0, + "hash": "0x8aade0ef6b0c8a2854b7d71503fe74b8a1edc13e95f7f117467ec2a327ea6f99", + "logs_bloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "miner": "0x0000000000000000000000000000000000000000", + "mix_hash": "0x63746963616c2062797a616e74696e65206661756c7420746f6c6572616e6365", + "nonce": "0x0000000000000000", + "parent_hash": "0xa4852f7e1b8ce036b057087e54492524796e0a68bba07a1c110605cf2cb8c01d", + "receipts_root": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", + "sha3_uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", + "size": 902, + "state_root": "0x260aa025c613224aaa46e2134b6469f3d956c07949a6ca23143936c574838995", + "timestamp": 1638960172, + "transactions": [], + "transactions_root": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", } @staticmethod @@ -103,7 +100,7 @@ def filter_response_item(block_data): "timestamp": block_data.get("timestamp"), "gas_limit": block_data.get("gas_limit"), "gas_used": block_data.get("gas_used"), - "size": block_data.get("size") + "size": block_data.get("size"), } @staticmethod @@ -157,7 +154,7 @@ def test_normal_1_1(self, client: TestClient, db: Session): "count": 0, "offset": None, "limit": None, - "total": 0 + "total": 0, } assert response_data["block_data"] == [] @@ -181,12 +178,12 @@ def test_normal_1_2(self, client: TestClient, db: Session): "count": 3, "offset": None, "limit": None, - "total": 3 + "total": 3, } assert response_data["block_data"] == [ self.filter_response_item(self.block_0), self.filter_response_item(self.block_1), - self.filter_response_item(self.block_2) + self.filter_response_item(self.block_2), ] # Normal_2_1 @@ -211,11 +208,11 @@ def test_normal_2_1(self, client: TestClient, db: Session): "count": 2, "offset": None, "limit": None, - "total": 3 + "total": 3, } assert response_data["block_data"] == [ self.filter_response_item(self.block_1), - self.filter_response_item(self.block_2) + self.filter_response_item(self.block_2), ] # Normal_2_2 @@ -240,11 +237,11 @@ def test_normal_2_2(self, client: TestClient, db: Session): "count": 2, "offset": None, "limit": None, - "total": 3 + "total": 3, } assert response_data["block_data"] == [ self.filter_response_item(self.block_0), - self.filter_response_item(self.block_1) + self.filter_response_item(self.block_1), ] # Normal_3_1 @@ -269,11 +266,11 @@ def test_normal_3_1(self, client: TestClient, db: Session): "count": 3, "offset": 1, "limit": None, - "total": 3 + "total": 3, } assert response_data["block_data"] == [ self.filter_response_item(self.block_1), - self.filter_response_item(self.block_2) + self.filter_response_item(self.block_2), ] # Normal_3_2 @@ -298,11 +295,9 @@ def test_normal_3_2(self, client: TestClient, db: Session): "count": 3, "offset": None, "limit": 1, - "total": 3 + "total": 3, } - assert response_data["block_data"] == [ - self.filter_response_item(self.block_0) - ] + assert response_data["block_data"] == [self.filter_response_item(self.block_0)] # Normal_4 # sort_order @@ -326,12 +321,12 @@ def test_normal_4(self, client: TestClient, db: Session): "count": 3, "offset": None, "limit": None, - "total": 3 + "total": 3, } assert response_data["block_data"] == [ self.filter_response_item(self.block_2), self.filter_response_item(self.block_1), - self.filter_response_item(self.block_0) + self.filter_response_item(self.block_0), ] ########################################################################### @@ -348,11 +343,8 @@ def test_error_1(self, client: TestClient, db: Session): # Assertion assert resp.status_code == 404 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'NotFound' - }, - 'detail': 'This URL is not available in the current settings' + "meta": {"code": 1, "title": "NotFound"}, + "detail": "This URL is not available in the current settings", } # Error_2 @@ -364,43 +356,40 @@ def test_error_2(self, client: TestClient, db: Session): "offset": -1, "limit": -1, "from_block_number": -1, - "to_block_number": -1 + "to_block_number": -1, } resp = client.get(self.apiurl, params=params) # Assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['query', 'offset'], - 'msg': 'ensure this value is greater than or equal to 0', - 'type': 'value_error.number.not_ge', - 'ctx': {'limit_value': 0} + "loc": ["query", "offset"], + "msg": "ensure this value is greater than or equal to 0", + "type": "value_error.number.not_ge", + "ctx": {"limit_value": 0}, }, { - 'loc': ['query', 'limit'], - 'msg': 'ensure this value is greater than or equal to 0', - 'type': 'value_error.number.not_ge', - 'ctx': {'limit_value': 0} + "loc": ["query", "limit"], + "msg": "ensure this value is greater than or equal to 0", + "type": "value_error.number.not_ge", + "ctx": {"limit_value": 0}, }, { - 'loc': ['query', 'from_block_number'], - 'msg': 'ensure this value is greater than or equal to 0', - 'type': 'value_error.number.not_ge', - 'ctx': {'limit_value': 0} + "loc": ["query", "from_block_number"], + "msg": "ensure this value is greater than or equal to 0", + "type": "value_error.number.not_ge", + "ctx": {"limit_value": 0}, }, { - 'loc': ['query', 'to_block_number'], - 'msg': 'ensure this value is greater than or equal to 0', - 'type': 'value_error.number.not_ge', - 'ctx': {'limit_value': 0} - } - ] + "loc": ["query", "to_block_number"], + "msg": "ensure this value is greater than or equal to 0", + "type": "value_error.number.not_ge", + "ctx": {"limit_value": 0}, + }, + ], } # Error_3 @@ -413,16 +402,14 @@ def test_error_3(self, client: TestClient, db: Session): self.insert_block_data_block_number(db, latest_block_number=2) # Request target API - with mock.patch("app.routers.bc_explorer.BC_EXPLORER_ENABLED", True),\ - mock.patch("app.routers.bc_explorer.BLOCK_RESPONSE_LIMIT", 2): + with mock.patch( + "app.routers.bc_explorer.BC_EXPLORER_ENABLED", True + ), mock.patch("app.routers.bc_explorer.BLOCK_RESPONSE_LIMIT", 2): resp = client.get(self.apiurl) # Assertion assert resp.status_code == 400 assert resp.json() == { - 'meta': { - 'code': 4, - 'title': 'ResponseLimitExceededError' - }, - 'detail': 'Search results exceed the limit' + "meta": {"code": 4, "title": "ResponseLimitExceededError"}, + "detail": "Search results exceed the limit", } diff --git a/tests/test_app_routers_blockchain_explorer_block_data_{block_number}_GET.py b/tests/test_app_routers_blockchain_explorer_block_data_{block_number}_GET.py index 9bddf99b..0657d160 100644 --- a/tests/test_app_routers_blockchain_explorer_block_data_{block_number}_GET.py +++ b/tests/test_app_routers_blockchain_explorer_block_data_{block_number}_GET.py @@ -25,70 +25,69 @@ class TestGetBlockData: - # API to be tested apiurl = "/blockchain_explorer/block_data/{}" # Test data block_0 = { - 'number': 0, - 'difficulty': 1, - 'proof_of_authority_data': '0x0000000000000000000000000000000000000000000000000000000000000000f89af8549447a847fbdf801154253593851ac9a2e7753235349403ee8c85944b16dfa517cb0ddefe123c7341a5349435d56a7515e824be4122f033d60063d035573a0c94c25d04978fd86ee604feb88f3c635d555eb6d42db8410000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c0', - 'gas_limit': 800000000, - 'gas_used': 0, - 'hash': '0x307166a396b99259ed2072f4b99d850e332db4ef4c72656870680728944ad445', - 'logs_bloom': '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', - 'miner': '0x0000000000000000000000000000000000000000', - 'mix_hash': '0x63746963616c2062797a616e74696e65206661756c7420746f6c6572616e6365', - 'nonce': '0x0000000000000000', - 'parent_hash': '0x0000000000000000000000000000000000000000000000000000000000000000', - 'receipts_root': '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', - 'sha3_uncles': '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', - 'size': 698, - 'state_root': '0x260aa025c613224aaa46e2134b6469f3d956c07949a6ca23143936c574838995', - 'timestamp': 1524130695, - 'transactions': [], - 'transactions_root': '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + "number": 0, + "difficulty": 1, + "proof_of_authority_data": "0x0000000000000000000000000000000000000000000000000000000000000000f89af8549447a847fbdf801154253593851ac9a2e7753235349403ee8c85944b16dfa517cb0ddefe123c7341a5349435d56a7515e824be4122f033d60063d035573a0c94c25d04978fd86ee604feb88f3c635d555eb6d42db8410000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c0", + "gas_limit": 800000000, + "gas_used": 0, + "hash": "0x307166a396b99259ed2072f4b99d850e332db4ef4c72656870680728944ad445", + "logs_bloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "miner": "0x0000000000000000000000000000000000000000", + "mix_hash": "0x63746963616c2062797a616e74696e65206661756c7420746f6c6572616e6365", + "nonce": "0x0000000000000000", + "parent_hash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "receipts_root": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", + "sha3_uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", + "size": 698, + "state_root": "0x260aa025c613224aaa46e2134b6469f3d956c07949a6ca23143936c574838995", + "timestamp": 1524130695, + "transactions": [], + "transactions_root": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", } block_1 = { - 'number': 1, - 'difficulty': 1, - 'proof_of_authority_data': '0xd983010907846765746889676f312e31332e3135856c696e7578000000000000f90164f8549403ee8c85944b16dfa517cb0ddefe123c7341a5349435d56a7515e824be4122f033d60063d035573a0c9447a847fbdf801154253593851ac9a2e77532353494c25d04978fd86ee604feb88f3c635d555eb6d42db841d6b123b02f015f4f0b0d47648e22c043dca3f803e6498084522c07ccbea58f8c39e498f6c8c604abb406dc323246c30525cc0dd01c39bcadbb608733bdf3f08300f8c9b84186503892a4b314f2b8aba73b1a7434c69bd95695ac285d5db6d15f879b5dbbf83471502e13eb1d0fce4d2e7ea41be91e8ecf744f0eeb8c808fb2e4a7833377f901b84141f6e74ea7f1365fa01ab90318c066f05b65fe82a2fd856203407653aa242c5875bd016f68d169951aec61958f4ad9654ecc1c8edc686e55c601e3db45f4cc8a01b8414e3259ec82771a0c83d0b5db72c0199549efa80736e6e1f892c50504d187eb505f784cb8623ce475195fe1287ceb85bccf703fca919da23940ce29e4f9f1a7ba01', - 'gas_limit': 800000000, - 'gas_used': 0, - 'hash': '0xa4852f7e1b8ce036b057087e54492524796e0a68bba07a1c110605cf2cb8c01d', - 'logs_bloom': '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', - 'miner': '0x0000000000000000000000000000000000000000', - 'mix_hash': '0x63746963616c2062797a616e74696e65206661756c7420746f6c6572616e6365', - 'nonce': '0x0000000000000000', - 'parent_hash': '0x307166a396b99259ed2072f4b99d850e332db4ef4c72656870680728944ad445', - 'receipts_root': '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', - 'sha3_uncles': '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', - 'size': 902, - 'state_root': '0x260aa025c613224aaa46e2134b6469f3d956c07949a6ca23143936c574838995', - 'timestamp': 1638960161, - 'transactions': [], - 'transactions_root': '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + "number": 1, + "difficulty": 1, + "proof_of_authority_data": "0xd983010907846765746889676f312e31332e3135856c696e7578000000000000f90164f8549403ee8c85944b16dfa517cb0ddefe123c7341a5349435d56a7515e824be4122f033d60063d035573a0c9447a847fbdf801154253593851ac9a2e77532353494c25d04978fd86ee604feb88f3c635d555eb6d42db841d6b123b02f015f4f0b0d47648e22c043dca3f803e6498084522c07ccbea58f8c39e498f6c8c604abb406dc323246c30525cc0dd01c39bcadbb608733bdf3f08300f8c9b84186503892a4b314f2b8aba73b1a7434c69bd95695ac285d5db6d15f879b5dbbf83471502e13eb1d0fce4d2e7ea41be91e8ecf744f0eeb8c808fb2e4a7833377f901b84141f6e74ea7f1365fa01ab90318c066f05b65fe82a2fd856203407653aa242c5875bd016f68d169951aec61958f4ad9654ecc1c8edc686e55c601e3db45f4cc8a01b8414e3259ec82771a0c83d0b5db72c0199549efa80736e6e1f892c50504d187eb505f784cb8623ce475195fe1287ceb85bccf703fca919da23940ce29e4f9f1a7ba01", + "gas_limit": 800000000, + "gas_used": 0, + "hash": "0xa4852f7e1b8ce036b057087e54492524796e0a68bba07a1c110605cf2cb8c01d", + "logs_bloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "miner": "0x0000000000000000000000000000000000000000", + "mix_hash": "0x63746963616c2062797a616e74696e65206661756c7420746f6c6572616e6365", + "nonce": "0x0000000000000000", + "parent_hash": "0x307166a396b99259ed2072f4b99d850e332db4ef4c72656870680728944ad445", + "receipts_root": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", + "sha3_uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", + "size": 902, + "state_root": "0x260aa025c613224aaa46e2134b6469f3d956c07949a6ca23143936c574838995", + "timestamp": 1638960161, + "transactions": [], + "transactions_root": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", } block_2 = { - 'number': 2, - 'difficulty': 1, - 'proof_of_authority_data': '0xd983010907846765746889676f312e31332e3135856c696e7578000000000000f90164f8549403ee8c85944b16dfa517cb0ddefe123c7341a5349435d56a7515e824be4122f033d60063d035573a0c9447a847fbdf801154253593851ac9a2e77532353494c25d04978fd86ee604feb88f3c635d555eb6d42db8416ac645ecda42d11985f8d00d25664e336e8588d3bf595a88eb78ef200e5aa0f732a4822141420fba7ccf33248ed5a45038334c5e50561779e427a4fe4b04b08a00f8c9b8415568d4c4a3edcafaed146a43dc7046d9fcd31d5f6d64f8dcf581ba473b868f5145129066188ffef9b8a9e9065d13fa96a81f1196bad98393a70f6461245c097a01b841ea249f9f16bc3c5a13de6df4be7b6933b4908395d1517f7099cc7718ec438a8744aaa356584a3929d1dec2d596268ddbd29d476954d2080b94f82b07b223492300b841804f0f78afa930c7249a81cc3a7a2810098803c6f6cb4c2ed3778c1a0c35962e57c8a1328f670362cfbe3f30e58cac7d78f9059e379bd9c195afecb27b907faf01', - 'gas_limit': 800000000, - 'gas_used': 0, - 'hash': '0x8aade0ef6b0c8a2854b7d71503fe74b8a1edc13e95f7f117467ec2a327ea6f99', - 'logs_bloom': '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', - 'miner': '0x0000000000000000000000000000000000000000', - 'mix_hash': '0x63746963616c2062797a616e74696e65206661756c7420746f6c6572616e6365', - 'nonce': '0x0000000000000000', - 'parent_hash': '0xa4852f7e1b8ce036b057087e54492524796e0a68bba07a1c110605cf2cb8c01d', - 'receipts_root': '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', - 'sha3_uncles': '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', - 'size': 902, - 'state_root': '0x260aa025c613224aaa46e2134b6469f3d956c07949a6ca23143936c574838995', - 'timestamp': 1638960172, - 'transactions': [], - 'transactions_root': '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', + "number": 2, + "difficulty": 1, + "proof_of_authority_data": "0xd983010907846765746889676f312e31332e3135856c696e7578000000000000f90164f8549403ee8c85944b16dfa517cb0ddefe123c7341a5349435d56a7515e824be4122f033d60063d035573a0c9447a847fbdf801154253593851ac9a2e77532353494c25d04978fd86ee604feb88f3c635d555eb6d42db8416ac645ecda42d11985f8d00d25664e336e8588d3bf595a88eb78ef200e5aa0f732a4822141420fba7ccf33248ed5a45038334c5e50561779e427a4fe4b04b08a00f8c9b8415568d4c4a3edcafaed146a43dc7046d9fcd31d5f6d64f8dcf581ba473b868f5145129066188ffef9b8a9e9065d13fa96a81f1196bad98393a70f6461245c097a01b841ea249f9f16bc3c5a13de6df4be7b6933b4908395d1517f7099cc7718ec438a8744aaa356584a3929d1dec2d596268ddbd29d476954d2080b94f82b07b223492300b841804f0f78afa930c7249a81cc3a7a2810098803c6f6cb4c2ed3778c1a0c35962e57c8a1328f670362cfbe3f30e58cac7d78f9059e379bd9c195afecb27b907faf01", + "gas_limit": 800000000, + "gas_used": 0, + "hash": "0x8aade0ef6b0c8a2854b7d71503fe74b8a1edc13e95f7f117467ec2a327ea6f99", + "logs_bloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "miner": "0x0000000000000000000000000000000000000000", + "mix_hash": "0x63746963616c2062797a616e74696e65206661756c7420746f6c6572616e6365", + "nonce": "0x0000000000000000", + "parent_hash": "0xa4852f7e1b8ce036b057087e54492524796e0a68bba07a1c110605cf2cb8c01d", + "receipts_root": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", + "sha3_uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", + "size": 902, + "state_root": "0x260aa025c613224aaa46e2134b6469f3d956c07949a6ca23143936c574838995", + "timestamp": 1638960172, + "transactions": [], + "transactions_root": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", } @staticmethod @@ -147,8 +146,8 @@ def test_error_1(self, client: TestClient, db: Session): # Assertion assert resp.status_code == 404 assert resp.json() == { - 'meta': {'code': 1, 'title': 'NotFound'}, - 'detail': 'This URL is not available in the current settings' + "meta": {"code": 1, "title": "NotFound"}, + "detail": "This URL is not available in the current settings", } # Error_2 @@ -161,8 +160,8 @@ def test_error_2(self, client: TestClient, db: Session): # Assertion assert resp.status_code == 404 assert resp.json() == { - 'meta': {'code': 1, 'title': 'NotFound'}, - 'detail': 'block data not found' + "meta": {"code": 1, "title": "NotFound"}, + "detail": "block data not found", } # Error_3 @@ -175,16 +174,13 @@ def test_error_3(self, client: TestClient, db: Session): # Assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['path', 'block_number'], - 'msg': 'ensure this value is greater than or equal to 0', - 'type': 'value_error.number.not_ge', - 'ctx': {'limit_value': 0} + "loc": ["path", "block_number"], + "msg": "ensure this value is greater than or equal to 0", + "type": "value_error.number.not_ge", + "ctx": {"limit_value": 0}, } - ] + ], } diff --git a/tests/test_app_routers_blockchain_explorer_tx_data_GET.py b/tests/test_app_routers_blockchain_explorer_tx_data_GET.py index 2f3df122..04d3e4ac 100644 --- a/tests/test_app_routers_blockchain_explorer_tx_data_GET.py +++ b/tests/test_app_routers_blockchain_explorer_tx_data_GET.py @@ -40,7 +40,7 @@ class TestListTxData: "input": "0x5ccef3e7000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000010313634393237303331302e383734303400000000000000000000000000000000", "nonce": 86942, "transaction_index": 0, - "value": 0 + "value": 0, } A_tx_2 = { "block_hash": "0x077e42cfe8bc9577b85a6347136c2d38a2b165e7b31bb340c33d302565b900b6", @@ -53,7 +53,7 @@ class TestListTxData: "input": "0x5ccef3e7000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000011313634393237303331322e383235303432000000000000000000000000000000", "nonce": 86943, "transaction_index": 0, - "value": 0 + "value": 0, } B_tx_1 = { "block_hash": "0x6698ebc4866223855dbea153eec7a9455682fd6d2f8451746102afb320412a6b", @@ -66,7 +66,7 @@ class TestListTxData: "input": "0x5ccef3e7000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000011313635323937363632372e363337373738000000000000000000000000000000", "nonce": 199601, "transaction_index": 0, - "value": 0 + "value": 0, } @staticmethod @@ -77,7 +77,7 @@ def filter_response_item(tx_data): "block_number": tx_data.get("block_number"), "transaction_index": tx_data.get("transaction_index"), "from_address": tx_data.get("from_address"), - "to_address": tx_data.get("to_address") + "to_address": tx_data.get("to_address"), } @staticmethod @@ -119,12 +119,12 @@ def test_normal_1(self, client: TestClient, db: Session): "count": 3, "offset": None, "limit": None, - "total": 3 + "total": 3, } assert response_data["tx_data"] == [ self.filter_response_item(self.B_tx_1), self.filter_response_item(self.A_tx_2), - self.filter_response_item(self.A_tx_1) + self.filter_response_item(self.A_tx_1), ] # Normal_2_1 @@ -147,11 +147,9 @@ def test_normal_2_1(self, client: TestClient, db: Session): "count": 1, "offset": None, "limit": None, - "total": 3 + "total": 3, } - assert response_data["tx_data"] == [ - self.filter_response_item(self.A_tx_2) - ] + assert response_data["tx_data"] == [self.filter_response_item(self.A_tx_2)] # Normal_2_2 # Query parameter: from_address @@ -173,11 +171,11 @@ def test_normal_2_2(self, client: TestClient, db: Session): "count": 2, "offset": None, "limit": None, - "total": 3 + "total": 3, } assert response_data["tx_data"] == [ self.filter_response_item(self.A_tx_2), - self.filter_response_item(self.A_tx_1) + self.filter_response_item(self.A_tx_1), ] # Normal_2_3 @@ -200,11 +198,9 @@ def test_normal_2_3(self, client: TestClient, db: Session): "count": 1, "offset": None, "limit": None, - "total": 3 + "total": 3, } - assert response_data["tx_data"] == [ - self.filter_response_item(self.B_tx_1) - ] + assert response_data["tx_data"] == [self.filter_response_item(self.B_tx_1)] # Normal_3_1 # Pagination: offset @@ -226,11 +222,11 @@ def test_normal_3_1(self, client: TestClient, db: Session): "count": 3, "offset": 1, "limit": None, - "total": 3 + "total": 3, } assert response_data["tx_data"] == [ self.filter_response_item(self.A_tx_2), - self.filter_response_item(self.A_tx_1) + self.filter_response_item(self.A_tx_1), ] # Normal_3_2 @@ -253,11 +249,9 @@ def test_normal_3_2(self, client: TestClient, db: Session): "count": 3, "offset": None, "limit": 1, - "total": 3 + "total": 3, } - assert response_data["tx_data"] == [ - self.filter_response_item(self.B_tx_1) - ] + assert response_data["tx_data"] == [self.filter_response_item(self.B_tx_1)] ########################################################################### # Error @@ -273,11 +267,8 @@ def test_error_1(self, client: TestClient, db: Session): # Assertion assert resp.status_code == 404 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'NotFound' - }, - 'detail': 'This URL is not available in the current settings' + "meta": {"code": 1, "title": "NotFound"}, + "detail": "This URL is not available in the current settings", } # Error_2_1 @@ -285,40 +276,33 @@ def test_error_1(self, client: TestClient, db: Session): def test_error_2_1(self, client: TestClient, db: Session): # Request target API with mock.patch("app.routers.bc_explorer.BC_EXPLORER_ENABLED", True): - params = { - "offset": -1, - "limit": -1, - "block_number": -1 - } + params = {"offset": -1, "limit": -1, "block_number": -1} resp = client.get(self.apiurl, params=params) # Assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['query', 'offset'], - 'msg': 'ensure this value is greater than or equal to 0', - 'type': 'value_error.number.not_ge', - 'ctx': {'limit_value': 0} + "loc": ["query", "offset"], + "msg": "ensure this value is greater than or equal to 0", + "type": "value_error.number.not_ge", + "ctx": {"limit_value": 0}, }, { - 'loc': ['query', 'limit'], - 'msg': 'ensure this value is greater than or equal to 0', - 'type': 'value_error.number.not_ge', - 'ctx': {'limit_value': 0} + "loc": ["query", "limit"], + "msg": "ensure this value is greater than or equal to 0", + "type": "value_error.number.not_ge", + "ctx": {"limit_value": 0}, }, { - 'loc': ['query', 'block_number'], - 'msg': 'ensure this value is greater than or equal to 0', - 'type': 'value_error.number.not_ge', - 'ctx': {'limit_value': 0} - } - ] + "loc": ["query", "block_number"], + "msg": "ensure this value is greater than or equal to 0", + "type": "value_error.number.not_ge", + "ctx": {"limit_value": 0}, + }, + ], } # Error_2_2 @@ -326,31 +310,25 @@ def test_error_2_1(self, client: TestClient, db: Session): def test_error_2_2(self, client: TestClient, db: Session): # Request target API with mock.patch("app.routers.bc_explorer.BC_EXPLORER_ENABLED", True): - params = { - "from_address": "abcd", - "to_address": "abcd" - } + params = {"from_address": "abcd", "to_address": "abcd"} resp = client.get(self.apiurl, params=params) # Assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['from_address'], - 'msg': 'from_address is not a valid address', - 'type': 'value_error' + "loc": ["from_address"], + "msg": "from_address is not a valid address", + "type": "value_error", }, { - 'loc': ['to_address'], - 'msg': 'to_address is not a valid address', - 'type': 'value_error' - } - ] + "loc": ["to_address"], + "msg": "to_address is not a valid address", + "type": "value_error", + }, + ], } # Error_3 @@ -361,16 +339,14 @@ def test_error_3(self, client: TestClient, db: Session): self.insert_tx_data(db, self.B_tx_1) # Request target API - with mock.patch("app.routers.bc_explorer.BC_EXPLORER_ENABLED", True), \ - mock.patch("app.routers.bc_explorer.TX_RESPONSE_LIMIT", 2): + with mock.patch( + "app.routers.bc_explorer.BC_EXPLORER_ENABLED", True + ), mock.patch("app.routers.bc_explorer.TX_RESPONSE_LIMIT", 2): resp = client.get(self.apiurl) # Assertion assert resp.status_code == 400 assert resp.json() == { - 'meta': { - 'code': 4, - 'title': 'ResponseLimitExceededError' - }, - 'detail': 'Search results exceed the limit' + "meta": {"code": 4, "title": "ResponseLimitExceededError"}, + "detail": "Search results exceed the limit", } diff --git a/tests/test_app_routers_blockchain_explorer_tx_data_{hash}_GET.py b/tests/test_app_routers_blockchain_explorer_tx_data_{hash}_GET.py index 47366516..20ba5d1f 100644 --- a/tests/test_app_routers_blockchain_explorer_tx_data_{hash}_GET.py +++ b/tests/test_app_routers_blockchain_explorer_tx_data_{hash}_GET.py @@ -22,14 +22,10 @@ from fastapi.testclient import TestClient from sqlalchemy.orm import Session -from app.model.db import ( - IDXTxData, - Token -) +from app.model.db import IDXTxData, Token class TestGetTxData: - # API to be tested apiurl = "/blockchain_explorer/tx_data/{}" @@ -45,7 +41,7 @@ class TestGetTxData: "input": "0x5ccef3e7000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000011313635323937363632372e363337373738000000000000000000000000000000", "nonce": 199601, "transaction_index": 0, - "value": 0 + "value": 0, } @staticmethod @@ -87,24 +83,28 @@ def test_normal_1(self, client: TestClient, db: Session): # Request target API with mock.patch("app.routers.bc_explorer.BC_EXPLORER_ENABLED", True): - resp = client.get(self.apiurl.format("0x403f9cea4db07aecf71a440c45ae415569cb218bb1a7f4d3a2d83004e29d1644")) + resp = client.get( + self.apiurl.format( + "0x403f9cea4db07aecf71a440c45ae415569cb218bb1a7f4d3a2d83004e29d1644" + ) + ) # Assertion assert resp.status_code == 200 assert resp.json() == { - 'hash': '0x403f9cea4db07aecf71a440c45ae415569cb218bb1a7f4d3a2d83004e29d1644', - 'block_hash': '0x6698ebc4866223855dbea153eec7a9455682fd6d2f8451746102afb320412a6b', - 'block_number': 10407084, - 'transaction_index': 0, - 'from_address': '0x8456ac4FEc4869A16ad5C3584306181Af6410682', - 'to_address': '0xECeB9FdBd2CF677Be5fA8B1ceEb53e53D582f0Eb', - 'contract_name': None, - 'contract_function': None, - 'contract_parameters': None, - 'gas': 6000000, - 'gas_price': 0, - 'value': 0, - 'nonce': 199601 + "hash": "0x403f9cea4db07aecf71a440c45ae415569cb218bb1a7f4d3a2d83004e29d1644", + "block_hash": "0x6698ebc4866223855dbea153eec7a9455682fd6d2f8451746102afb320412a6b", + "block_number": 10407084, + "transaction_index": 0, + "from_address": "0x8456ac4FEc4869A16ad5C3584306181Af6410682", + "to_address": "0xECeB9FdBd2CF677Be5fA8B1ceEb53e53D582f0Eb", + "contract_name": None, + "contract_function": None, + "contract_parameters": None, + "gas": 6000000, + "gas_price": 0, + "value": 0, + "nonce": 199601, } # Normal_2 @@ -114,30 +114,34 @@ def test_normal_2(self, client: TestClient, db: Session): token_info = { "token_address": to_checksum_address(self.tx_data.get("to_address")), - "type": "IbetShare" + "type": "IbetShare", } self.insert_token_data(db, token_info) # Request target API with mock.patch("app.routers.bc_explorer.BC_EXPLORER_ENABLED", True): - resp = client.get(self.apiurl.format("0x403f9cea4db07aecf71a440c45ae415569cb218bb1a7f4d3a2d83004e29d1644")) + resp = client.get( + self.apiurl.format( + "0x403f9cea4db07aecf71a440c45ae415569cb218bb1a7f4d3a2d83004e29d1644" + ) + ) # Assertion assert resp.status_code == 200 assert resp.json() == { - 'hash': '0x403f9cea4db07aecf71a440c45ae415569cb218bb1a7f4d3a2d83004e29d1644', - 'block_hash': '0x6698ebc4866223855dbea153eec7a9455682fd6d2f8451746102afb320412a6b', - 'block_number': 10407084, - 'transaction_index': 0, - 'from_address': '0x8456ac4FEc4869A16ad5C3584306181Af6410682', - 'to_address': '0xECeB9FdBd2CF677Be5fA8B1ceEb53e53D582f0Eb', - 'contract_name': 'IbetShare', - 'contract_function': 'approveTransfer', - 'contract_parameters': {'_index': 1, '_data': '1652976627.637778'}, - 'gas': 6000000, - 'gas_price': 0, - 'value': 0, - 'nonce': 199601 + "hash": "0x403f9cea4db07aecf71a440c45ae415569cb218bb1a7f4d3a2d83004e29d1644", + "block_hash": "0x6698ebc4866223855dbea153eec7a9455682fd6d2f8451746102afb320412a6b", + "block_number": 10407084, + "transaction_index": 0, + "from_address": "0x8456ac4FEc4869A16ad5C3584306181Af6410682", + "to_address": "0xECeB9FdBd2CF677Be5fA8B1ceEb53e53D582f0Eb", + "contract_name": "IbetShare", + "contract_function": "approveTransfer", + "contract_parameters": {"_index": 1, "_data": "1652976627.637778"}, + "gas": 6000000, + "gas_price": 0, + "value": 0, + "nonce": 199601, } ########################################################################### @@ -149,16 +153,17 @@ def test_normal_2(self, client: TestClient, db: Session): def test_error_1(self, client: TestClient, db: Session): # Request target API with mock.patch("app.routers.bc_explorer.BC_EXPLORER_ENABLED", False): - resp = client.get(self.apiurl.format("0x403f9cea4db07aecf71a440c45ae415569cb218bb1a7f4d3a2d83004e29d1644")) + resp = client.get( + self.apiurl.format( + "0x403f9cea4db07aecf71a440c45ae415569cb218bb1a7f4d3a2d83004e29d1644" + ) + ) # Assertion assert resp.status_code == 404 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'NotFound' - }, - 'detail': 'This URL is not available in the current settings' + "meta": {"code": 1, "title": "NotFound"}, + "detail": "This URL is not available in the current settings", } # Error_2 @@ -166,11 +171,15 @@ def test_error_1(self, client: TestClient, db: Session): def test_error_2(self, client: TestClient, db: Session): # Request target API with mock.patch("app.routers.bc_explorer.BC_EXPLORER_ENABLED", True): - resp = client.get(self.apiurl.format("0x403f9cea4db07aecf71a440c45ae415569cb218bb1a7f4d3a2d83004e29d1644")) + resp = client.get( + self.apiurl.format( + "0x403f9cea4db07aecf71a440c45ae415569cb218bb1a7f4d3a2d83004e29d1644" + ) + ) # Assertion assert resp.status_code == 404 assert resp.json() == { - 'meta': {'code': 1, 'title': 'NotFound'}, - 'detail': 'block data not found' + "meta": {"code": 1, "title": "NotFound"}, + "detail": "block data not found", } diff --git a/tests/test_app_routers_bond_bulk_transfer_GET.py b/tests/test_app_routers_bond_bulk_transfer_GET.py index 152f90e6..235ce119 100644 --- a/tests/test_app_routers_bond_bulk_transfer_GET.py +++ b/tests/test_app_routers_bond_bulk_transfer_GET.py @@ -17,15 +17,11 @@ SPDX-License-Identifier: Apache-2.0 """ from datetime import datetime -import pytest +import pytest import pytz -from app.model.db import ( - Account, - TokenType, - BulkTransferUpload -) +from app.model.db import Account, BulkTransferUpload, TokenType from config import TZ from tests.account_config import config_eth_account @@ -39,20 +35,22 @@ class TestAppRoutersBondBulkTransferGET: upload_issuer_list = [ { "address": config_eth_account("user1")["address"], - "keyfile": config_eth_account("user1")["keyfile_json"] - }, { + "keyfile": config_eth_account("user1")["keyfile_json"], + }, + { "address": config_eth_account("user2")["address"], - "keyfile": config_eth_account("user2")["keyfile_json"] - }, { + "keyfile": config_eth_account("user2")["keyfile_json"], + }, + { "address": config_eth_account("user3")["address"], - "keyfile": config_eth_account("user3")["keyfile_json"] - } + "keyfile": config_eth_account("user3")["keyfile_json"], + }, ] upload_id_list = [ "0c961f7d-e1ad-40e5-988b-cca3d6009643", # 0: under progress "de778f46-864e-4ec0-b566-21bd31cf63ff", # 1: succeeded - "cf33d48f-9e6e-4a36-a55e-5bbcbda69c80" # 2: failed + "cf33d48f-9e6e-4a36-a55e-5bbcbda69c80", # 2: failed ] ########################################################################### @@ -84,7 +82,7 @@ def test_normal_1(self, client, db): # request target API resp = client.get( self.test_url, - headers={"issuer-address": self.upload_issuer_list[1]["address"]} + headers={"issuer-address": self.upload_issuer_list[1]["address"]}, ) # assertion @@ -95,7 +93,10 @@ def test_normal_1(self, client, db): "token_type": TokenType.IBET_STRAIGHT_BOND.value, "upload_id": self.upload_id_list[1], "status": 1, - "created": pytz.timezone("UTC").localize(utc_now).astimezone(local_tz).isoformat() + "created": pytz.timezone("UTC") + .localize(utc_now) + .astimezone(local_tz) + .isoformat(), } ] assert resp.json() == assumed_response @@ -116,24 +117,27 @@ def test_normal_2(self, client, db): db.add(bulk_transfer_upload) # request target API - resp = client.get( - self.test_url - ) + resp = client.get(self.test_url) # assertion assert resp.status_code == 200 assumed_response = [] for i in range(0, 3): - assumed_response.append({ - "issuer_address": self.upload_issuer_list[i]["address"], - "token_type": TokenType.IBET_STRAIGHT_BOND.value, - "upload_id": self.upload_id_list[i], - "status": i, - "created": pytz.timezone("UTC").localize(utc_now).astimezone(local_tz).isoformat() - }) + assumed_response.append( + { + "issuer_address": self.upload_issuer_list[i]["address"], + "token_type": TokenType.IBET_STRAIGHT_BOND.value, + "upload_id": self.upload_id_list[i], + "status": i, + "created": pytz.timezone("UTC") + .localize(utc_now) + .astimezone(local_tz) + .isoformat(), + } + ) - sorted_resp = sorted(resp.json(), key=lambda x: x['upload_id']) - sorted_assumed = sorted(assumed_response, key=lambda x: x['upload_id']) + sorted_resp = sorted(resp.json(), key=lambda x: x["upload_id"]) + sorted_assumed = sorted(assumed_response, key=lambda x: x["upload_id"]) assert sorted_resp == sorted_assumed ########################################################################### @@ -145,23 +149,17 @@ def test_normal_2(self, client, db): # invalid type : issuer-address def test_error_1(self, client, db): # request target API - resp = client.get( - self.test_url, - headers={"issuer-address": "DUMMY ADDRESS"} - ) + resp = client.get(self.test_url, headers={"issuer-address": "DUMMY ADDRESS"}) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } diff --git a/tests/test_app_routers_bond_bulk_transfer_POST.py b/tests/test_app_routers_bond_bulk_transfer_POST.py index 39f38466..730b559b 100644 --- a/tests/test_app_routers_bond_bulk_transfer_POST.py +++ b/tests/test_app_routers_bond_bulk_transfer_POST.py @@ -21,10 +21,10 @@ from app.model.db import ( Account, AuthToken, + BulkTransfer, + BulkTransferUpload, Token, TokenType, - BulkTransfer, - BulkTransferUpload ) from app.utils.e2ee_utils import E2EEUtils from tests.account_config import config_eth_account @@ -53,13 +53,13 @@ class TestAppRoutersBondBulkTransferPOST: "0x55e20Fa9F4Fa854Ef06081734872b734c105916b", "0x1d2E98AD049e978B08113fD282BD42948F265DDa", "0x2413a63D91eb10e1472a18aD4b9628fBE4aac8B8", - "0x6f9486251F4034C251ecb8Fa0f087CDDb3cDe6d7" + "0x6f9486251F4034C251ecb8Fa0f087CDDb3cDe6d7", ] upload_id_list = [ "0c961f7d-e1ad-40e5-988b-cca3d6009643", # 0: under progress "de778f46-864e-4ec0-b566-21bd31cf63ff", # 1: succeeded - "cf33d48f-9e6e-4a36-a55e-5bbcbda69c80" # 2: failed + "cf33d48f-9e6e-4a36-a55e-5bbcbda69c80", # 2: failed ] # @@ -87,37 +87,42 @@ def test_normal_1(self, client, db): "token_address": self.req_tokens[0], "from_address": self.from_address, "to_address": self.to_address, - "amount": 5 - }, { + "amount": 5, + }, + { "token_address": self.req_tokens[1], "from_address": self.from_address, "to_address": self.to_address, - "amount": 10 - } + "amount": 10, + }, ] resp = client.post( self.test_url, json=req_param, headers={ "issuer-address": self.admin_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 200 - bulk_transfer_upload = db.query(BulkTransferUpload). \ - filter(BulkTransferUpload.upload_id == resp.json()["upload_id"]). \ - all() + bulk_transfer_upload = ( + db.query(BulkTransferUpload) + .filter(BulkTransferUpload.upload_id == resp.json()["upload_id"]) + .all() + ) assert len(bulk_transfer_upload) == 1 assert bulk_transfer_upload[0].issuer_address == self.admin_address assert bulk_transfer_upload[0].status == 0 - bulk_transfer = db.query(BulkTransfer). \ - filter(BulkTransfer.upload_id == resp.json()["upload_id"]). \ - order_by(BulkTransfer.id). \ - all() + bulk_transfer = ( + db.query(BulkTransfer) + .filter(BulkTransfer.upload_id == resp.json()["upload_id"]) + .order_by(BulkTransfer.id) + .all() + ) assert len(bulk_transfer) == 2 assert bulk_transfer[0].issuer_address == self.admin_address assert bulk_transfer[0].token_address == self.req_tokens[0] @@ -167,37 +172,42 @@ def test_normal_2(self, client, db): "token_address": self.req_tokens[0], "from_address": self.from_address, "to_address": self.to_address, - "amount": 5 - }, { + "amount": 5, + }, + { "token_address": self.req_tokens[1], "from_address": self.from_address, "to_address": self.to_address, - "amount": 10 - } + "amount": 10, + }, ] resp = client.post( self.test_url, json=req_param, headers={ "issuer-address": self.admin_address, - "auth-token": "test_auth_token" - } + "auth-token": "test_auth_token", + }, ) # assertion assert resp.status_code == 200 - bulk_transfer_upload = db.query(BulkTransferUpload). \ - filter(BulkTransferUpload.upload_id == resp.json()["upload_id"]). \ - all() + bulk_transfer_upload = ( + db.query(BulkTransferUpload) + .filter(BulkTransferUpload.upload_id == resp.json()["upload_id"]) + .all() + ) assert len(bulk_transfer_upload) == 1 assert bulk_transfer_upload[0].issuer_address == self.admin_address assert bulk_transfer_upload[0].status == 0 - bulk_transfer = db.query(BulkTransfer). \ - filter(BulkTransfer.upload_id == resp.json()["upload_id"]). \ - order_by(BulkTransfer.id). \ - all() + bulk_transfer = ( + db.query(BulkTransfer) + .filter(BulkTransfer.upload_id == resp.json()["upload_id"]) + .order_by(BulkTransfer.id) + .all() + ) assert len(bulk_transfer) == 2 assert bulk_transfer[0].issuer_address == self.admin_address assert bulk_transfer[0].token_address == self.req_tokens[0] @@ -223,14 +233,16 @@ def test_normal_2(self, client, db): # invalid type def test_error_1(self, client, db): _token_address_int = 10 # integer - _from_address_long = "0xd9F55747DE740297ff1eEe537aBE0f8d73B7D7811" # long address + _from_address_long = ( + "0xd9F55747DE740297ff1eEe537aBE0f8d73B7D7811" # long address + ) _to_address_short = "0xd9F55747DE740297ff1eEe537aBE0f8d73B7D78" # short address req_param = [ { "token_address": _token_address_int, "from_address": _from_address_long, "to_address": _to_address_short, - "amount": 0 + "amount": 0, }, ] @@ -238,56 +250,49 @@ def test_error_1(self, client, db): resp = client.post( self.test_url, json=req_param, - headers={"issuer-address": self.admin_address} + headers={"issuer-address": self.admin_address}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", 0, "token_address"], "msg": "token_address is not a valid address", - "type": "value_error" - }, { + "type": "value_error", + }, + { "loc": ["body", 0, "from_address"], "msg": "from_address is not a valid address", - "type": "value_error" - }, { + "type": "value_error", + }, + { "loc": ["body", 0, "to_address"], "msg": "to_address is not a valid address", - "type": "value_error" - }, { - "ctx": { - "limit_value": 1 - }, - "loc": [ - "body", - 0, - "amount" - ], + "type": "value_error", + }, + { + "ctx": {"limit_value": 1}, + "loc": ["body", 0, "amount"], "msg": "ensure this value is greater than or equal to 1", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, - ] + ], } # # RequestValidationError # invalid type(max values) def test_error_2(self, client, db): - # request target API req_param = [ { "token_address": self.req_tokens[0], "from_address": self.from_address, "to_address": self.to_address, - "amount": 1_000_000_000_001 + "amount": 1_000_000_000_001, } ] resp = client.post( @@ -295,30 +300,21 @@ def test_error_2(self, client, db): json=req_param, headers={ "issuer-address": self.admin_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "ctx": { - "limit_value": 1_000_000_000_000 - }, - "loc": [ - "body", - 0, - "amount" - ], + "ctx": {"limit_value": 1_000_000_000_000}, + "loc": ["body", 0, "amount"], "msg": "ensure this value is less than or equal to 1000000000000", - "type": "value_error.number.not_le" + "type": "value_error.number.not_le", }, - ] + ], } # @@ -326,29 +322,24 @@ def test_error_2(self, client, db): # headers and body required def test_error_3(self, client, db): # request target API - resp = client.post( - self.test_url - ) + resp = client.post(self.test_url) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, { "loc": ["body"], "msg": "field required", - "type": "value_error.missing" - } - ] + "type": "value_error.missing", + }, + ], } # @@ -358,27 +349,20 @@ def test_error_4(self, client, db): # request target API req_param = [] resp = client.post( - self.test_url, - json=req_param, - headers={ - "issuer-address": "admin_address" - } + self.test_url, json=req_param, headers={"issuer-address": "admin_address"} ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -390,24 +374,20 @@ def test_error_5(self, client, db): resp = client.post( self.test_url, json=req_param, - headers={ - "issuer-address": self.admin_address, - "eoa-password": "password" - } + headers={"issuer-address": self.admin_address, "eoa-password": "password"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, - "detail": [{ - "loc": ["header", "eoa-password"], - "msg": "eoa-password is not a Base64-encoded encrypted data", - "type": "value_error" - }] + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ + { + "loc": ["header", "eoa-password"], + "msg": "eoa-password is not a Base64-encoded encrypted data", + "type": "value_error", + } + ], } # @@ -428,18 +408,15 @@ def test_error_6(self, client, db): json=req_param, headers={ "issuer-address": self.admin_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "list length must be at least one" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "list length must be at least one", } # @@ -452,31 +429,29 @@ def test_error_7(self, client, db): "token_address": self.req_tokens[0], "from_address": self.from_address, "to_address": self.to_address, - "amount": 5 - }, { + "amount": 5, + }, + { "token_address": self.req_tokens[1], "from_address": self.from_address, "to_address": self.to_address, - "amount": 10 - } + "amount": 10, + }, ] resp = client.post( self.test_url, json=req_param, headers={ "issuer-address": self.admin_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -496,7 +471,7 @@ def test_error_8(self, client, db): "token_address": self.req_tokens[0], "from_address": self.from_address, "to_address": self.to_address, - "amount": 10 + "amount": 10, } ] resp = client.post( @@ -504,17 +479,14 @@ def test_error_8(self, client, db): json=req_param, headers={ "issuer-address": self.admin_address, - "eoa-password": E2EEUtils.encrypt("password_test") - } + "eoa-password": E2EEUtils.encrypt("password_test"), + }, ) assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -534,7 +506,7 @@ def test_error_9(self, client, db): "token_address": self.req_tokens[0], "from_address": self.from_address, "to_address": self.to_address, - "amount": 10 + "amount": 10, } ] resp = client.post( @@ -542,17 +514,14 @@ def test_error_9(self, client, db): json=req_param, headers={ "issuer-address": self.admin_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": f"token not found: {self.req_tokens[0]}" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": f"token not found: {self.req_tokens[0]}", } # @@ -582,7 +551,7 @@ def test_error_10(self, client, db): "token_address": self.req_tokens[0], "from_address": self.from_address, "to_address": self.to_address, - "amount": 10 + "amount": 10, } ] resp = client.post( @@ -590,15 +559,12 @@ def test_error_10(self, client, db): json=req_param, headers={ "issuer-address": self.admin_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": f"this token is temporarily unavailable: {self.req_tokens[0]}" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": f"this token is temporarily unavailable: {self.req_tokens[0]}", } diff --git a/tests/test_app_routers_bond_bulk_transfer_{upload_id}_GET.py b/tests/test_app_routers_bond_bulk_transfer_{upload_id}_GET.py index 7e79b299..0f9669b0 100644 --- a/tests/test_app_routers_bond_bulk_transfer_{upload_id}_GET.py +++ b/tests/test_app_routers_bond_bulk_transfer_{upload_id}_GET.py @@ -16,7 +16,7 @@ SPDX-License-Identifier: Apache-2.0 """ -from app.model.db import Account, TokenType, BulkTransfer, BulkTransferUpload +from app.model.db import Account, BulkTransfer, BulkTransferUpload, TokenType from tests.account_config import config_eth_account @@ -27,20 +27,22 @@ class TestAppRoutersBondBulkTransferGET: upload_issuer_list = [ { "address": config_eth_account("user1")["address"], - "keyfile": config_eth_account("user1")["keyfile_json"] - }, { + "keyfile": config_eth_account("user1")["keyfile_json"], + }, + { "address": config_eth_account("user2")["address"], - "keyfile": config_eth_account("user2")["keyfile_json"] - }, { + "keyfile": config_eth_account("user2")["keyfile_json"], + }, + { "address": config_eth_account("user3")["address"], - "keyfile": config_eth_account("user3")["keyfile_json"] - } + "keyfile": config_eth_account("user3")["keyfile_json"], + }, ] upload_id_list = [ "0c961f7d-e1ad-40e5-988b-cca3d6009643", # 0: under progress "de778f46-864e-4ec0-b566-21bd31cf63ff", # 1: succeeded - "cf33d48f-9e6e-4a36-a55e-5bbcbda69c80" # 2: failed + "cf33d48f-9e6e-4a36-a55e-5bbcbda69c80", # 2: failed ] bulk_transfer_token = "0xbB4138520af85fAfdDAACc7F0AabfE188334D0ca" @@ -82,7 +84,7 @@ def test_normal_1(self, client, db): # request target API resp = client.get( self.test_url.format(self.upload_id_list[1]), - headers={"issuer-address": self.upload_issuer_list[1]["address"]} + headers={"issuer-address": self.upload_issuer_list[1]["address"]}, ) # assertion @@ -96,14 +98,13 @@ def test_normal_1(self, client, db): "from_address": self.upload_issuer_list[1]["address"], "to_address": self.upload_issuer_list[2]["address"], "amount": 11, - "status": 1 + "status": 1, } ] assert resp.json() == assumed_response # def test_normal_2(self, client, db): - for i in range(0, 3): # prepare data : BulkTransferUpload bulk_transfer_upload = BulkTransferUpload() @@ -141,7 +142,7 @@ def test_normal_2(self, client, db): "from_address": self.upload_issuer_list[1]["address"], "to_address": self.upload_issuer_list[2]["address"], "amount": 10, - "status": 0 + "status": 0, } ] assert resp.json() == assumed_response @@ -157,40 +158,32 @@ def test_error_1(self, client, db): # request target API resp = client.get( self.test_url.format(self.upload_id_list[0]), - headers={"issuer-address": "DUMMY ADDRESS"} + headers={"issuer-address": "DUMMY ADDRESS"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # # Upload id Not Found def test_error_2(self, client, db): # request target API - resp = client.get( - self.test_url.format("DUMMY UPLOAD ID") - ) + resp = client.get(self.test_url.format("DUMMY UPLOAD ID")) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, + "meta": {"code": 1, "title": "NotFound"}, "detail": "bulk transfer not found", } @@ -228,15 +221,12 @@ def test_error_3(self, client, db): # request target API resp = client.get( self.test_url.format(self.upload_id_list[2]), - headers={"issuer-address": self.upload_issuer_list[0]["address"]} + headers={"issuer-address": self.upload_issuer_list[0]["address"]}, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "bulk transfer not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "bulk transfer not found", } diff --git a/tests/test_app_routers_bond_lock_events_GET.py b/tests/test_app_routers_bond_lock_events_GET.py index 092c3090..c64c5c4f 100644 --- a/tests/test_app_routers_bond_lock_events_GET.py +++ b/tests/test_app_routers_bond_lock_events_GET.py @@ -19,22 +19,15 @@ from datetime import datetime from unittest import mock from unittest.mock import ANY, MagicMock + import pytest from sqlalchemy.orm import Session -from app.model.db import ( - IDXLock, - IDXUnlock, - Token, - TokenType -) -from app.model.blockchain import ( - IbetStraightBondContract -) +from app.model.blockchain import IbetStraightBondContract +from app.model.db import IDXLock, IDXUnlock, Token, TokenType class TestAppRoutersBondLockEvents: - # target API endpoint base_url = "/bond/tokens/{token_address}/lock_events" @@ -144,7 +137,7 @@ def get_contract_mock_data(token_name_list: list[str]): "recipient_address": None, "value": 1, "data": {"message": "locked_1"}, - "block_timestamp": ANY + "block_timestamp": ANY, } expected_lock_2 = { "category": "Lock", @@ -158,7 +151,7 @@ def get_contract_mock_data(token_name_list: list[str]): "recipient_address": None, "value": 1, "data": {"message": "locked_2"}, - "block_timestamp": ANY + "block_timestamp": ANY, } expected_unlock_1 = { "category": "Unlock", @@ -172,7 +165,7 @@ def get_contract_mock_data(token_name_list: list[str]): "recipient_address": other_account_address_1, "value": 1, "data": {"message": "unlocked_1"}, - "block_timestamp": ANY + "block_timestamp": ANY, } expected_unlock_2 = { "category": "Unlock", @@ -186,7 +179,7 @@ def get_contract_mock_data(token_name_list: list[str]): "recipient_address": other_account_address_2, "value": 1, "data": {"message": "unlocked_2"}, - "block_timestamp": ANY + "block_timestamp": ANY, } ########################################################################### @@ -219,7 +212,7 @@ def test_normal_1(self, client, db): "limit": None, "total": 0, }, - "events": [] + "events": [], } # Normal_2 @@ -242,18 +235,13 @@ def test_normal_2(self, mock_IbetStraightBondContract_get, client, db): # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 4, - "offset": None, - "limit": None, - "total": 4 - }, + "result_set": {"count": 4, "offset": None, "limit": None, "total": 4}, "events": [ self.expected_unlock_2, self.expected_unlock_1, self.expected_lock_2, - self.expected_lock_1 - ] + self.expected_lock_1, + ], } # Normal_3 @@ -272,13 +260,8 @@ def test_normal_3(self, mock_IbetStraightBondContract_get, client, db): # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 0, - 'offset': None, - 'limit': None, - 'total': 0 - }, - 'events': [] + "result_set": {"count": 0, "offset": None, "limit": None, "total": 0}, + "events": [], } # Normal_4 @@ -296,24 +279,19 @@ def test_normal_4(self, mock_IbetStraightBondContract_get, client, db): # request target api resp = client.get( self.base_url.format(token_address=self.token_address_1), - headers={"issuer-address": self.issuer_address} + headers={"issuer-address": self.issuer_address}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 4, - "offset": None, - "limit": None, - "total": 4 - }, + "result_set": {"count": 4, "offset": None, "limit": None, "total": 4}, "events": [ self.expected_unlock_2, self.expected_unlock_1, self.expected_lock_2, - self.expected_lock_1 - ] + self.expected_lock_1, + ], } # Normal_5_1 @@ -331,22 +309,14 @@ def test_normal_5_1(self, mock_IbetStraightBondContract_get, client, db): # request target api resp = client.get( self.base_url.format(token_address=self.token_address_1), - params={"category": "Lock"} + params={"category": "Lock"}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 2, - "offset": None, - "limit": None, - "total": 4 - }, - "events": [ - self.expected_lock_2, - self.expected_lock_1 - ] + "result_set": {"count": 2, "offset": None, "limit": None, "total": 4}, + "events": [self.expected_lock_2, self.expected_lock_1], } # Normal_5_2 @@ -364,22 +334,14 @@ def test_normal_5_2(self, mock_IbetStraightBondContract_get, client, db): # request target api resp = client.get( self.base_url.format(token_address=self.token_address_1), - params={"account_address": self.account_address_1} + params={"account_address": self.account_address_1}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 2, - "offset": None, - "limit": None, - "total": 4 - }, - "events": [ - self.expected_unlock_1, - self.expected_lock_1 - ] + "result_set": {"count": 2, "offset": None, "limit": None, "total": 4}, + "events": [self.expected_unlock_1, self.expected_lock_1], } # Normal_5_3 @@ -397,22 +359,14 @@ def test_normal_5_3(self, mock_IbetStraightBondContract_get, client, db): # request target api resp = client.get( self.base_url.format(token_address=self.token_address_1), - params={"lock_address": self.lock_address_1} + params={"lock_address": self.lock_address_1}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 2, - 'offset': None, - 'limit': None, - 'total': 4 - }, - 'events': [ - self.expected_unlock_1, - self.expected_lock_1 - ] + "result_set": {"count": 2, "offset": None, "limit": None, "total": 4}, + "events": [self.expected_unlock_1, self.expected_lock_1], } # Normal_5_4 @@ -430,81 +384,112 @@ def test_normal_5_4(self, mock_IbetStraightBondContract_get, client, db): # request target api resp = client.get( self.base_url.format(token_address=self.token_address_1), - params={"recipient_address": self.other_account_address_2} + params={"recipient_address": self.other_account_address_2}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 1, - 'offset': None, - 'limit': None, - 'total': 4 - }, - 'events': [ - self.expected_unlock_2 - ] + "result_set": {"count": 1, "offset": None, "limit": None, "total": 4}, + "events": [self.expected_unlock_2], } # Normal_6 # Sort - @pytest.mark.parametrize("sort_item, sort_order, data, expect", [ - # ( - # "{sort_item}", {sort_order}, - # {data used to contract mock}, - # {expected result} - # ), - ( - "account_address", 0, - get_contract_mock_data([token_name_1, token_name_1, token_name_1, token_name_1]), - [expected_unlock_1, expected_lock_1, expected_unlock_2, expected_lock_2] - ), - ( - "lock_address", 0, - get_contract_mock_data([token_name_1, token_name_1, token_name_1, token_name_1]), - [expected_unlock_1, expected_lock_1, expected_unlock_2, expected_lock_2] - ), - ( - "recipient_address", 0, - get_contract_mock_data([token_name_1, token_name_1, token_name_1, token_name_1]), - [expected_unlock_1, expected_unlock_2, expected_lock_2, expected_lock_1] - ), - ( - "recipient_address", 1, - get_contract_mock_data([token_name_1, token_name_1, token_name_1, token_name_1]), - [expected_lock_2, expected_lock_1, expected_unlock_2, expected_unlock_1] - ), - ( - "value", 0, - get_contract_mock_data([token_name_1, token_name_1, token_name_1, token_name_1]), - [expected_unlock_2, expected_unlock_1, expected_lock_2, expected_lock_1] - ), - ]) + @pytest.mark.parametrize( + "sort_item, sort_order, data, expect", + [ + # ( + # "{sort_item}", {sort_order}, + # {data used to contract mock}, + # {expected result} + # ), + ( + "account_address", + 0, + get_contract_mock_data( + [token_name_1, token_name_1, token_name_1, token_name_1] + ), + [ + expected_unlock_1, + expected_lock_1, + expected_unlock_2, + expected_lock_2, + ], + ), + ( + "lock_address", + 0, + get_contract_mock_data( + [token_name_1, token_name_1, token_name_1, token_name_1] + ), + [ + expected_unlock_1, + expected_lock_1, + expected_unlock_2, + expected_lock_2, + ], + ), + ( + "recipient_address", + 0, + get_contract_mock_data( + [token_name_1, token_name_1, token_name_1, token_name_1] + ), + [ + expected_unlock_1, + expected_unlock_2, + expected_lock_2, + expected_lock_1, + ], + ), + ( + "recipient_address", + 1, + get_contract_mock_data( + [token_name_1, token_name_1, token_name_1, token_name_1] + ), + [ + expected_lock_2, + expected_lock_1, + expected_unlock_2, + expected_unlock_1, + ], + ), + ( + "value", + 0, + get_contract_mock_data( + [token_name_1, token_name_1, token_name_1, token_name_1] + ), + [ + expected_unlock_2, + expected_unlock_1, + expected_lock_2, + expected_lock_1, + ], + ), + ], + ) def test_normal_6(self, sort_item, sort_order, data, expect, client, db): # prepare data self.setup_data(db=db) # request target api - with mock.patch("app.model.blockchain.token.IbetStraightBondContract.get", MagicMock(side_effect=data)): + with mock.patch( + "app.model.blockchain.token.IbetStraightBondContract.get", + MagicMock(side_effect=data), + ): resp = client.get( self.base_url.format(token_address=self.token_address_1), - params={ - "sort_item": sort_item, - "sort_order": sort_order - } + params={"sort_item": sort_item, "sort_order": sort_order}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 4, - 'offset': None, - 'limit': None, - 'total': 4 - }, - 'events': expect + "result_set": {"count": 4, "offset": None, "limit": None, "total": 4}, + "events": expect, } # Normal_7 @@ -522,24 +507,14 @@ def test_normal_7(self, mock_IbetStraightBondContract_get, client, db): # request target api resp = client.get( self.base_url.format(token_address=self.token_address_1), - params={ - "offset": 1, - "limit": 1 - } + params={"offset": 1, "limit": 1}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 4, - 'offset': 1, - 'limit': 1, - 'total': 4 - }, - 'events': [ - self.expected_unlock_1 - ] + "result_set": {"count": 4, "offset": 1, "limit": 1, "total": 4}, + "events": [self.expected_unlock_1], } # ########################################################################### @@ -555,23 +530,20 @@ def test_error_1_1(self, client, db): self.base_url.format(token_address=self.token_address_1), headers={ "issuer-address": "test", - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # Error_1_2 @@ -586,38 +558,43 @@ def test_error_1_2(self, client, db): "sort_item": "test", "offset": "test", "limit": "test", - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['query', 'offset'], - 'msg': 'value is not a valid integer', - 'type': 'type_error.integer' + "loc": ["query", "offset"], + "msg": "value is not a valid integer", + "type": "type_error.integer", }, { - 'loc': ['query', 'limit'], - 'msg': 'value is not a valid integer', - 'type': 'type_error.integer' + "loc": ["query", "limit"], + "msg": "value is not a valid integer", + "type": "type_error.integer", }, { - 'loc': ['query', 'category'], - 'msg': "value is not a valid enumeration member; permitted: 'Lock', 'Unlock'", - 'type': 'type_error.enum', - 'ctx': {'enum_values': ['Lock', 'Unlock']} + "loc": ["query", "category"], + "msg": "value is not a valid enumeration member; permitted: 'Lock', 'Unlock'", + "type": "type_error.enum", + "ctx": {"enum_values": ["Lock", "Unlock"]}, }, { - 'loc': ['query', 'sort_item'], - 'msg': "value is not a valid enumeration member; permitted: 'account_address', 'lock_address', 'recipient_address', 'value', 'block_timestamp'", - 'type': 'type_error.enum', - 'ctx': {'enum_values': ['account_address', 'lock_address', 'recipient_address', 'value', 'block_timestamp']} - } - ] + "loc": ["query", "sort_item"], + "msg": "value is not a valid enumeration member; permitted: 'account_address', 'lock_address', 'recipient_address', 'value', 'block_timestamp'", + "type": "type_error.enum", + "ctx": { + "enum_values": [ + "account_address", + "lock_address", + "recipient_address", + "value", + "block_timestamp", + ] + }, + }, + ], } diff --git a/tests/test_app_routers_bond_tokens_GET.py b/tests/test_app_routers_bond_tokens_GET.py index abc20dbb..92f9fe87 100644 --- a/tests/test_app_routers_bond_tokens_GET.py +++ b/tests/test_app_routers_bond_tokens_GET.py @@ -16,16 +16,13 @@ SPDX-License-Identifier: Apache-2.0 """ -import pytz from unittest import mock +import pytz from web3.datastructures import AttributeDict from app.model.blockchain import IbetStraightBondContract -from app.model.db import ( - Token, - TokenType -) +from app.model.db import Token, TokenType from config import TZ from tests.account_config import config_eth_account @@ -62,7 +59,12 @@ def test_normal_2(self, mock_get, client, db): token.abi = "abi_test1" db.add(token) db.commit() - _issue_datetime = pytz.timezone("UTC").localize(token.created).astimezone(self.local_tz).isoformat() + _issue_datetime = ( + pytz.timezone("UTC") + .localize(token.created) + .astimezone(self.local_tz) + .isoformat() + ) mock_token = IbetStraightBondContract() mock_token.issuer_address = token.issuer_address @@ -72,7 +74,9 @@ def test_normal_2(self, mock_get, client, db): mock_token.total_supply = 10000 mock_token.contact_information = "contactInformation_test1" mock_token.privacy_policy = "privacyPolicy_test1" - mock_token.tradable_exchange_contract_address = "0x1234567890abCdFe1234567890ABCdFE12345678" + mock_token.tradable_exchange_contract_address = ( + "0x1234567890abCdFe1234567890ABCdFE12345678" + ) mock_token.status = True mock_token.face_value = 200 mock_token.redemption_date = "redemptionDate_test1" @@ -84,21 +88,27 @@ def test_normal_2(self, mock_get, client, db): mock_token.transferable = True mock_token.is_offering = False mock_token.is_redeemed = False - mock_token.personal_info_contract_address = "0x1234567890aBcDFE1234567890abcDFE12345679" + mock_token.personal_info_contract_address = ( + "0x1234567890aBcDFE1234567890abcDFE12345679" + ) mock_token.interest_payment_date = [ - "interestPaymentDate1_test1", "interestPaymentDate2_test1", - "interestPaymentDate3_test1", "interestPaymentDate4_test1", - "interestPaymentDate5_test1", "interestPaymentDate6_test1", - "interestPaymentDate7_test1", "interestPaymentDate8_test1", - "interestPaymentDate9_test1", "interestPaymentDate10_test1", - "interestPaymentDate11_test1", "interestPaymentDate12_test1", + "interestPaymentDate1_test1", + "interestPaymentDate2_test1", + "interestPaymentDate3_test1", + "interestPaymentDate4_test1", + "interestPaymentDate5_test1", + "interestPaymentDate6_test1", + "interestPaymentDate7_test1", + "interestPaymentDate8_test1", + "interestPaymentDate9_test1", + "interestPaymentDate10_test1", + "interestPaymentDate11_test1", + "interestPaymentDate12_test1", ] mock_token.transfer_approval_required = True mock_token.memo = "memo_test1" - mock_get.side_effect = [ - AttributeDict(mock_token.__dict__) - ] + mock_get.side_effect = [AttributeDict(mock_token.__dict__)] resp = client.get(self.apiurl) @@ -125,12 +135,18 @@ def test_normal_2(self, mock_get, client, db): "is_redeemed": False, "personal_info_contract_address": "0x1234567890aBcDFE1234567890abcDFE12345679", "interest_payment_date": [ - "interestPaymentDate1_test1", "interestPaymentDate2_test1", - "interestPaymentDate3_test1", "interestPaymentDate4_test1", - "interestPaymentDate5_test1", "interestPaymentDate6_test1", - "interestPaymentDate7_test1", "interestPaymentDate8_test1", - "interestPaymentDate9_test1", "interestPaymentDate10_test1", - "interestPaymentDate11_test1", "interestPaymentDate12_test1", + "interestPaymentDate1_test1", + "interestPaymentDate2_test1", + "interestPaymentDate3_test1", + "interestPaymentDate4_test1", + "interestPaymentDate5_test1", + "interestPaymentDate6_test1", + "interestPaymentDate7_test1", + "interestPaymentDate8_test1", + "interestPaymentDate9_test1", + "interestPaymentDate10_test1", + "interestPaymentDate11_test1", + "interestPaymentDate12_test1", ], "issue_datetime": _issue_datetime, "token_status": 1, @@ -160,7 +176,12 @@ def test_normal_3(self, mock_get, client, db): token_1.abi = "abi_test1" db.add(token_1) db.commit() - _issue_datetime_1 = pytz.timezone("UTC").localize(token_1.created).astimezone(self.local_tz).isoformat() + _issue_datetime_1 = ( + pytz.timezone("UTC") + .localize(token_1.created) + .astimezone(self.local_tz) + .isoformat() + ) mock_token_1 = IbetStraightBondContract() mock_token_1.issuer_address = token_1.issuer_address @@ -170,7 +191,9 @@ def test_normal_3(self, mock_get, client, db): mock_token_1.total_supply = 10000 mock_token_1.contact_information = "contactInformation_test1" mock_token_1.privacy_policy = "privacyPolicy_test1" - mock_token_1.tradable_exchange_contract_address = "0x1234567890abCdFe1234567890ABCdFE12345678" + mock_token_1.tradable_exchange_contract_address = ( + "0x1234567890abCdFe1234567890ABCdFE12345678" + ) mock_token_1.status = True mock_token_1.face_value = 200 mock_token_1.redemption_date = "redemptionDate_test1" @@ -182,14 +205,22 @@ def test_normal_3(self, mock_get, client, db): mock_token_1.transferable = True mock_token_1.is_offering = False mock_token_1.is_redeemed = False - mock_token_1.personal_info_contract_address = "0x1234567890aBcDFE1234567890abcDFE12345679" + mock_token_1.personal_info_contract_address = ( + "0x1234567890aBcDFE1234567890abcDFE12345679" + ) mock_token_1.interest_payment_date = [ - "interestPaymentDate1_test1", "interestPaymentDate2_test1", - "interestPaymentDate3_test1", "interestPaymentDate4_test1", - "interestPaymentDate5_test1", "interestPaymentDate6_test1", - "interestPaymentDate7_test1", "interestPaymentDate8_test1", - "interestPaymentDate9_test1", "interestPaymentDate10_test1", - "interestPaymentDate11_test1", "interestPaymentDate12_test1", + "interestPaymentDate1_test1", + "interestPaymentDate2_test1", + "interestPaymentDate3_test1", + "interestPaymentDate4_test1", + "interestPaymentDate5_test1", + "interestPaymentDate6_test1", + "interestPaymentDate7_test1", + "interestPaymentDate8_test1", + "interestPaymentDate9_test1", + "interestPaymentDate10_test1", + "interestPaymentDate11_test1", + "interestPaymentDate12_test1", ] mock_token_1.transfer_approval_required = True mock_token_1.memo = "memo_test1" @@ -204,7 +235,12 @@ def test_normal_3(self, mock_get, client, db): token_2.token_status = 0 db.add(token_2) db.commit() - _issue_datetime_2 = pytz.timezone("UTC").localize(token_2.created).astimezone(self.local_tz).isoformat() + _issue_datetime_2 = ( + pytz.timezone("UTC") + .localize(token_2.created) + .astimezone(self.local_tz) + .isoformat() + ) mock_token_2 = IbetStraightBondContract() mock_token_2.issuer_address = token_2.issuer_address @@ -214,7 +250,9 @@ def test_normal_3(self, mock_get, client, db): mock_token_2.total_supply = 50000 mock_token_2.contact_information = "contactInformation_test2" mock_token_2.privacy_policy = "privacyPolicy_test2" - mock_token_2.tradable_exchange_contract_address = "0x1234567890AbcdfE1234567890abcdfE12345680" + mock_token_2.tradable_exchange_contract_address = ( + "0x1234567890AbcdfE1234567890abcdfE12345680" + ) mock_token_2.status = True mock_token_2.face_value = 600 mock_token_2.redemption_date = "redemptionDate_test2" @@ -226,21 +264,29 @@ def test_normal_3(self, mock_get, client, db): mock_token_2.transferable = False mock_token_2.is_offering = False mock_token_2.is_redeemed = False - mock_token_2.personal_info_contract_address = "0x1234567890abcdFE1234567890ABcdfE12345681" + mock_token_2.personal_info_contract_address = ( + "0x1234567890abcdFE1234567890ABcdfE12345681" + ) mock_token_2.interest_payment_date = [ - "interestPaymentDate1_test2", "interestPaymentDate2_test2", - "interestPaymentDate3_test2", "interestPaymentDate4_test2", - "interestPaymentDate5_test2", "interestPaymentDate6_test2", - "interestPaymentDate7_test2", "interestPaymentDate8_test2", - "interestPaymentDate9_test2", "interestPaymentDate10_test2", - "interestPaymentDate11_test2", "interestPaymentDate12_test2", + "interestPaymentDate1_test2", + "interestPaymentDate2_test2", + "interestPaymentDate3_test2", + "interestPaymentDate4_test2", + "interestPaymentDate5_test2", + "interestPaymentDate6_test2", + "interestPaymentDate7_test2", + "interestPaymentDate8_test2", + "interestPaymentDate9_test2", + "interestPaymentDate10_test2", + "interestPaymentDate11_test2", + "interestPaymentDate12_test2", ] mock_token_2.transfer_approval_required = False mock_token_2.memo = "memo_test2" mock_get.side_effect = [ AttributeDict(mock_token_1.__dict__), - AttributeDict(mock_token_2.__dict__) + AttributeDict(mock_token_2.__dict__), ] resp = client.get(self.apiurl) @@ -268,12 +314,18 @@ def test_normal_3(self, mock_get, client, db): "is_redeemed": False, "personal_info_contract_address": "0x1234567890aBcDFE1234567890abcDFE12345679", "interest_payment_date": [ - "interestPaymentDate1_test1", "interestPaymentDate2_test1", - "interestPaymentDate3_test1", "interestPaymentDate4_test1", - "interestPaymentDate5_test1", "interestPaymentDate6_test1", - "interestPaymentDate7_test1", "interestPaymentDate8_test1", - "interestPaymentDate9_test1", "interestPaymentDate10_test1", - "interestPaymentDate11_test1", "interestPaymentDate12_test1", + "interestPaymentDate1_test1", + "interestPaymentDate2_test1", + "interestPaymentDate3_test1", + "interestPaymentDate4_test1", + "interestPaymentDate5_test1", + "interestPaymentDate6_test1", + "interestPaymentDate7_test1", + "interestPaymentDate8_test1", + "interestPaymentDate9_test1", + "interestPaymentDate10_test1", + "interestPaymentDate11_test1", + "interestPaymentDate12_test1", ], "issue_datetime": _issue_datetime_1, "token_status": 1, @@ -302,12 +354,18 @@ def test_normal_3(self, mock_get, client, db): "is_redeemed": False, "personal_info_contract_address": "0x1234567890abcdFE1234567890ABcdfE12345681", "interest_payment_date": [ - "interestPaymentDate1_test2", "interestPaymentDate2_test2", - "interestPaymentDate3_test2", "interestPaymentDate4_test2", - "interestPaymentDate5_test2", "interestPaymentDate6_test2", - "interestPaymentDate7_test2", "interestPaymentDate8_test2", - "interestPaymentDate9_test2", "interestPaymentDate10_test2", - "interestPaymentDate11_test2", "interestPaymentDate12_test2", + "interestPaymentDate1_test2", + "interestPaymentDate2_test2", + "interestPaymentDate3_test2", + "interestPaymentDate4_test2", + "interestPaymentDate5_test2", + "interestPaymentDate6_test2", + "interestPaymentDate7_test2", + "interestPaymentDate8_test2", + "interestPaymentDate9_test2", + "interestPaymentDate10_test2", + "interestPaymentDate11_test2", + "interestPaymentDate12_test2", ], "issue_datetime": _issue_datetime_2, "token_status": 0, @@ -358,7 +416,12 @@ def test_normal_5(self, mock_get, client, db): token_1.abi = "abi_test1" db.add(token_1) db.commit() - _issue_datetime = pytz.timezone("UTC").localize(token_1.created).astimezone(self.local_tz).isoformat() + _issue_datetime = ( + pytz.timezone("UTC") + .localize(token_1.created) + .astimezone(self.local_tz) + .isoformat() + ) mock_token = IbetStraightBondContract() mock_token.issuer_address = token_1.issuer_address @@ -368,7 +431,9 @@ def test_normal_5(self, mock_get, client, db): mock_token.total_supply = 10000 mock_token.contact_information = "contactInformation_test1" mock_token.privacy_policy = "privacyPolicy_test1" - mock_token.tradable_exchange_contract_address = "0x1234567890abCdFe1234567890ABCdFE12345678" + mock_token.tradable_exchange_contract_address = ( + "0x1234567890abCdFe1234567890ABCdFE12345678" + ) mock_token.status = True mock_token.face_value = 200 mock_token.redemption_date = "redemptionDate_test1" @@ -380,21 +445,27 @@ def test_normal_5(self, mock_get, client, db): mock_token.transferable = True mock_token.is_offering = False mock_token.is_redeemed = False - mock_token.personal_info_contract_address = "0x1234567890aBcDFE1234567890abcDFE12345679" + mock_token.personal_info_contract_address = ( + "0x1234567890aBcDFE1234567890abcDFE12345679" + ) mock_token.interest_payment_date = [ - "interestPaymentDate1_test1", "interestPaymentDate2_test1", - "interestPaymentDate3_test1", "interestPaymentDate4_test1", - "interestPaymentDate5_test1", "interestPaymentDate6_test1", - "interestPaymentDate7_test1", "interestPaymentDate8_test1", - "interestPaymentDate9_test1", "interestPaymentDate10_test1", - "interestPaymentDate11_test1", "interestPaymentDate12_test1", + "interestPaymentDate1_test1", + "interestPaymentDate2_test1", + "interestPaymentDate3_test1", + "interestPaymentDate4_test1", + "interestPaymentDate5_test1", + "interestPaymentDate6_test1", + "interestPaymentDate7_test1", + "interestPaymentDate8_test1", + "interestPaymentDate9_test1", + "interestPaymentDate10_test1", + "interestPaymentDate11_test1", + "interestPaymentDate12_test1", ] mock_token.transfer_approval_required = True mock_token.memo = "memo_test1" - mock_get.side_effect = [ - AttributeDict(mock_token.__dict__) - ] + mock_get.side_effect = [AttributeDict(mock_token.__dict__)] # No Target Data token_2 = Token() @@ -430,12 +501,18 @@ def test_normal_5(self, mock_get, client, db): "is_redeemed": False, "personal_info_contract_address": "0x1234567890aBcDFE1234567890abcDFE12345679", "interest_payment_date": [ - "interestPaymentDate1_test1", "interestPaymentDate2_test1", - "interestPaymentDate3_test1", "interestPaymentDate4_test1", - "interestPaymentDate5_test1", "interestPaymentDate6_test1", - "interestPaymentDate7_test1", "interestPaymentDate8_test1", - "interestPaymentDate9_test1", "interestPaymentDate10_test1", - "interestPaymentDate11_test1", "interestPaymentDate12_test1", + "interestPaymentDate1_test1", + "interestPaymentDate2_test1", + "interestPaymentDate3_test1", + "interestPaymentDate4_test1", + "interestPaymentDate5_test1", + "interestPaymentDate6_test1", + "interestPaymentDate7_test1", + "interestPaymentDate8_test1", + "interestPaymentDate9_test1", + "interestPaymentDate10_test1", + "interestPaymentDate11_test1", + "interestPaymentDate12_test1", ], "issue_datetime": _issue_datetime, "token_status": 1, @@ -465,7 +542,12 @@ def test_normal_6(self, mock_get, client, db): token_1.abi = "abi_test1" db.add(token_1) db.commit() - _issue_datetime_1 = pytz.timezone("UTC").localize(token_1.created).astimezone(self.local_tz).isoformat() + _issue_datetime_1 = ( + pytz.timezone("UTC") + .localize(token_1.created) + .astimezone(self.local_tz) + .isoformat() + ) mock_token_1 = IbetStraightBondContract() mock_token_1.issuer_address = token_1.issuer_address @@ -475,7 +557,9 @@ def test_normal_6(self, mock_get, client, db): mock_token_1.total_supply = 10000 mock_token_1.contact_information = "contactInformation_test1" mock_token_1.privacy_policy = "privacyPolicy_test1" - mock_token_1.tradable_exchange_contract_address = "0x1234567890abCdFe1234567890ABCdFE12345678" + mock_token_1.tradable_exchange_contract_address = ( + "0x1234567890abCdFe1234567890ABCdFE12345678" + ) mock_token_1.status = True mock_token_1.face_value = 200 mock_token_1.redemption_date = "redemptionDate_test1" @@ -487,14 +571,22 @@ def test_normal_6(self, mock_get, client, db): mock_token_1.transferable = True mock_token_1.is_offering = False mock_token_1.is_redeemed = False - mock_token_1.personal_info_contract_address = "0x1234567890aBcDFE1234567890abcDFE12345679" + mock_token_1.personal_info_contract_address = ( + "0x1234567890aBcDFE1234567890abcDFE12345679" + ) mock_token_1.interest_payment_date = [ - "interestPaymentDate1_test1", "interestPaymentDate2_test1", - "interestPaymentDate3_test1", "interestPaymentDate4_test1", - "interestPaymentDate5_test1", "interestPaymentDate6_test1", - "interestPaymentDate7_test1", "interestPaymentDate8_test1", - "interestPaymentDate9_test1", "interestPaymentDate10_test1", - "interestPaymentDate11_test1", "interestPaymentDate12_test1", + "interestPaymentDate1_test1", + "interestPaymentDate2_test1", + "interestPaymentDate3_test1", + "interestPaymentDate4_test1", + "interestPaymentDate5_test1", + "interestPaymentDate6_test1", + "interestPaymentDate7_test1", + "interestPaymentDate8_test1", + "interestPaymentDate9_test1", + "interestPaymentDate10_test1", + "interestPaymentDate11_test1", + "interestPaymentDate12_test1", ] mock_token_1.transfer_approval_required = True mock_token_1.memo = "memo_test1" @@ -509,7 +601,12 @@ def test_normal_6(self, mock_get, client, db): token_2.token_status = 0 db.add(token_2) db.commit() - _issue_datetime_2 = pytz.timezone("UTC").localize(token_2.created).astimezone(self.local_tz).isoformat() + _issue_datetime_2 = ( + pytz.timezone("UTC") + .localize(token_2.created) + .astimezone(self.local_tz) + .isoformat() + ) mock_token_2 = IbetStraightBondContract() mock_token_2.issuer_address = token_2.issuer_address @@ -519,7 +616,9 @@ def test_normal_6(self, mock_get, client, db): mock_token_2.total_supply = 50000 mock_token_2.contact_information = "contactInformation_test2" mock_token_2.privacy_policy = "privacyPolicy_test2" - mock_token_2.tradable_exchange_contract_address = "0x1234567890AbcdfE1234567890abcdfE12345680" + mock_token_2.tradable_exchange_contract_address = ( + "0x1234567890AbcdfE1234567890abcdfE12345680" + ) mock_token_2.status = True mock_token_2.face_value = 600 mock_token_2.redemption_date = "redemptionDate_test2" @@ -531,21 +630,29 @@ def test_normal_6(self, mock_get, client, db): mock_token_2.transferable = False mock_token_2.is_offering = False mock_token_2.is_redeemed = False - mock_token_2.personal_info_contract_address = "0x1234567890abcdFE1234567890ABcdfE12345681" + mock_token_2.personal_info_contract_address = ( + "0x1234567890abcdFE1234567890ABcdfE12345681" + ) mock_token_2.interest_payment_date = [ - "interestPaymentDate1_test2", "interestPaymentDate2_test2", - "interestPaymentDate3_test2", "interestPaymentDate4_test2", - "interestPaymentDate5_test2", "interestPaymentDate6_test2", - "interestPaymentDate7_test2", "interestPaymentDate8_test2", - "interestPaymentDate9_test2", "interestPaymentDate10_test2", - "interestPaymentDate11_test2", "interestPaymentDate12_test2", + "interestPaymentDate1_test2", + "interestPaymentDate2_test2", + "interestPaymentDate3_test2", + "interestPaymentDate4_test2", + "interestPaymentDate5_test2", + "interestPaymentDate6_test2", + "interestPaymentDate7_test2", + "interestPaymentDate8_test2", + "interestPaymentDate9_test2", + "interestPaymentDate10_test2", + "interestPaymentDate11_test2", + "interestPaymentDate12_test2", ] mock_token_2.transfer_approval_required = False mock_token_2.memo = "memo_test2" mock_get.side_effect = [ AttributeDict(mock_token_1.__dict__), - AttributeDict(mock_token_2.__dict__) + AttributeDict(mock_token_2.__dict__), ] # No Target Data @@ -582,12 +689,18 @@ def test_normal_6(self, mock_get, client, db): "is_redeemed": False, "personal_info_contract_address": "0x1234567890aBcDFE1234567890abcDFE12345679", "interest_payment_date": [ - "interestPaymentDate1_test1", "interestPaymentDate2_test1", - "interestPaymentDate3_test1", "interestPaymentDate4_test1", - "interestPaymentDate5_test1", "interestPaymentDate6_test1", - "interestPaymentDate7_test1", "interestPaymentDate8_test1", - "interestPaymentDate9_test1", "interestPaymentDate10_test1", - "interestPaymentDate11_test1", "interestPaymentDate12_test1", + "interestPaymentDate1_test1", + "interestPaymentDate2_test1", + "interestPaymentDate3_test1", + "interestPaymentDate4_test1", + "interestPaymentDate5_test1", + "interestPaymentDate6_test1", + "interestPaymentDate7_test1", + "interestPaymentDate8_test1", + "interestPaymentDate9_test1", + "interestPaymentDate10_test1", + "interestPaymentDate11_test1", + "interestPaymentDate12_test1", ], "issue_datetime": _issue_datetime_1, "token_status": 1, @@ -616,12 +729,18 @@ def test_normal_6(self, mock_get, client, db): "is_redeemed": False, "personal_info_contract_address": "0x1234567890abcdFE1234567890ABcdfE12345681", "interest_payment_date": [ - "interestPaymentDate1_test2", "interestPaymentDate2_test2", - "interestPaymentDate3_test2", "interestPaymentDate4_test2", - "interestPaymentDate5_test2", "interestPaymentDate6_test2", - "interestPaymentDate7_test2", "interestPaymentDate8_test2", - "interestPaymentDate9_test2", "interestPaymentDate10_test2", - "interestPaymentDate11_test2", "interestPaymentDate12_test2", + "interestPaymentDate1_test2", + "interestPaymentDate2_test2", + "interestPaymentDate3_test2", + "interestPaymentDate4_test2", + "interestPaymentDate5_test2", + "interestPaymentDate6_test2", + "interestPaymentDate7_test2", + "interestPaymentDate8_test2", + "interestPaymentDate9_test2", + "interestPaymentDate10_test2", + "interestPaymentDate11_test2", + "interestPaymentDate12_test2", ], "issue_datetime": _issue_datetime_2, "token_status": 0, @@ -644,13 +763,12 @@ def test_error_1(self, client, db): assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, - "detail": [{ - "loc": ["header", "issuer-address"], - "msg": "issuer-address is not a valid address", - "type": "value_error" - }] + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ + { + "loc": ["header", "issuer-address"], + "msg": "issuer-address is not a valid address", + "type": "value_error", + } + ], } diff --git a/tests/test_app_routers_bond_tokens_POST.py b/tests/test_app_routers_bond_tokens_POST.py index 04eca939..4adf0ba1 100644 --- a/tests/test_app_routers_bond_tokens_POST.py +++ b/tests/test_app_routers_bond_tokens_POST.py @@ -17,35 +17,29 @@ SPDX-License-Identifier: Apache-2.0 """ import hashlib -from unittest.mock import ( - ANY, - patch -) -from datetime import ( - datetime, - timezone -) +import random +import string +from datetime import datetime, timezone +from unittest.mock import ANY, patch from web3 import Web3 from web3.middleware import geth_poa_middleware import config -import string -import random from app.exceptions import SendTransactionError +from app.model.blockchain.token import IbetStraightBondContract +from app.model.blockchain.token_list import TokenListContract from app.model.db import ( + UTXO, Account, AuthToken, + IDXPosition, Token, TokenType, UpdateToken, - IDXPosition, - UTXO ) from app.utils.contract_utils import ContractUtils from app.utils.e2ee_utils import E2EEUtils -from app.model.blockchain.token import IbetStraightBondContract -from app.model.blockchain.token_list import TokenListContract from tests.account_config import config_eth_account web3 = Web3(Web3.HTTPProvider(config.WEB3_HTTP_PROVIDER)) @@ -77,23 +71,25 @@ def test_normal_1(self, client, db): # mock IbetStraightBondContract_create = patch( target="app.model.blockchain.token.IbetStraightBondContract.create", - return_value=("contract_address_test1", "abi_test1", "tx_hash_test1") + return_value=("contract_address_test1", "abi_test1", "tx_hash_test1"), ) TokenListContract_register = patch( target="app.model.blockchain.token_list.TokenListContract.register", - return_value=None + return_value=None, ) ContractUtils_get_block_by_transaction_hash = patch( target="app.utils.contract_utils.ContractUtils.get_block_by_transaction_hash", return_value={ "number": 12345, - "timestamp": datetime(2021, 4, 27, 12, 34, 56, tzinfo=timezone.utc).timestamp() - } + "timestamp": datetime( + 2021, 4, 27, 12, 34, 56, tzinfo=timezone.utc + ).timestamp(), + }, ) - with IbetStraightBondContract_create, \ - TokenListContract_register, \ - ContractUtils_get_block_by_transaction_hash: + with ( + IbetStraightBondContract_create + ), TokenListContract_register, ContractUtils_get_block_by_transaction_hash: # request target api req_param = { "name": "name_test1", @@ -106,28 +102,23 @@ def test_normal_1(self, client, db): json=req_param, headers={ "issuer-address": test_account["address"], - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion IbetStraightBondContract.create.assert_called_with( - args=[ - "name_test1", "", 10000, 200, "", 0, - "", "", "purpose_test1" - ], + args=["name_test1", "", 10000, 200, "", 0, "", "", "purpose_test1"], tx_from=test_account["address"], - private_key=ANY + private_key=ANY, ) TokenListContract.register.assert_called_with( token_address="contract_address_test1", token_template=TokenType.IBET_STRAIGHT_BOND.value, tx_from=test_account["address"], - private_key=ANY - ) - ContractUtils.get_block_by_transaction_hash( - tx_hash="tx_hash_test1" + private_key=ANY, ) + ContractUtils.get_block_by_transaction_hash(tx_hash="tx_hash_test1") assert resp.status_code == 200 assert resp.json()["token_address"] == "contract_address_test1" @@ -181,23 +172,25 @@ def test_normal_2(self, client, db): # mock IbetStraightBondContract_create = patch( target="app.model.blockchain.token.IbetStraightBondContract.create", - return_value=("contract_address_test1", "abi_test1", "tx_hash_test1") + return_value=("contract_address_test1", "abi_test1", "tx_hash_test1"), ) TokenListContract_register = patch( target="app.model.blockchain.token_list.TokenListContract.register", - return_value=None + return_value=None, ) ContractUtils_get_block_by_transaction_hash = patch( target="app.utils.contract_utils.ContractUtils.get_block_by_transaction_hash", return_value={ "number": 12345, - "timestamp": datetime(2021, 4, 27, 12, 34, 56, tzinfo=timezone.utc).timestamp() - } + "timestamp": datetime( + 2021, 4, 27, 12, 34, 56, tzinfo=timezone.utc + ).timestamp(), + }, ) - with IbetStraightBondContract_create, \ - TokenListContract_register, \ - ContractUtils_get_block_by_transaction_hash: + with ( + IbetStraightBondContract_create + ), TokenListContract_register, ContractUtils_get_block_by_transaction_hash: # request target api req_param = { "name": "name_test1", @@ -227,8 +220,8 @@ def test_normal_2(self, client, db): json=req_param, headers={ "issuer-address": test_account["address"], - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion @@ -242,10 +235,10 @@ def test_normal_2(self, client, db): 4000, "20211231", "return_amount_test1", - "purpose_test1" + "purpose_test1", ], tx_from=test_account["address"], - private_key=ANY + private_key=ANY, ) TokenListContract.register.assert_not_called() @@ -305,23 +298,25 @@ def test_normal_3(self, client, db): # mock IbetStraightBondContract_create = patch( target="app.model.blockchain.token.IbetStraightBondContract.create", - return_value=("contract_address_test1", "abi_test1", "tx_hash_test1") + return_value=("contract_address_test1", "abi_test1", "tx_hash_test1"), ) TokenListContract_register = patch( target="app.model.blockchain.token_list.TokenListContract.register", - return_value=None + return_value=None, ) ContractUtils_get_block_by_transaction_hash = patch( target="app.utils.contract_utils.ContractUtils.get_block_by_transaction_hash", return_value={ "number": 12345, - "timestamp": datetime(2021, 4, 27, 12, 34, 56, tzinfo=timezone.utc).timestamp() - } + "timestamp": datetime( + 2021, 4, 27, 12, 34, 56, tzinfo=timezone.utc + ).timestamp(), + }, ) - with IbetStraightBondContract_create, \ - TokenListContract_register, \ - ContractUtils_get_block_by_transaction_hash: + with ( + IbetStraightBondContract_create + ), TokenListContract_register, ContractUtils_get_block_by_transaction_hash: # request target api req_param = { "name": "name_test1", @@ -334,28 +329,23 @@ def test_normal_3(self, client, db): json=req_param, headers={ "issuer-address": test_account["address"], - "auth-token": "test_auth_token" - } + "auth-token": "test_auth_token", + }, ) # assertion IbetStraightBondContract.create.assert_called_with( - args=[ - "name_test1", "", 10000, 200, "", 0, - "", "", "purpose_test1" - ], + args=["name_test1", "", 10000, 200, "", 0, "", "", "purpose_test1"], tx_from=test_account["address"], - private_key=ANY + private_key=ANY, ) TokenListContract.register.assert_called_with( token_address="contract_address_test1", token_template=TokenType.IBET_STRAIGHT_BOND.value, tx_from=test_account["address"], - private_key=ANY - ) - ContractUtils.get_block_by_transaction_hash( - tx_hash="tx_hash_test1" + private_key=ANY, ) + ContractUtils.get_block_by_transaction_hash(tx_hash="tx_hash_test1") assert resp.status_code == 200 assert resp.json()["token_address"] == "contract_address_test1" @@ -401,29 +391,24 @@ def test_normal_3(self, client, db): # missing fields def test_error_1(self, client, db): # request target api - resp = client.post( - self.apiurl - ) + resp = client.post(self.apiurl) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, { "loc": ["body"], "msg": "field required", - "type": "value_error.missing" - } - ] + "type": "value_error.missing", + }, + ], } # @@ -457,7 +442,7 @@ def test_error_2_1(self, client, db): "1001", "1101", "1201", - "1231" + "1231", ], "tradable_exchange_contract_address": "0x0", "personal_info_contract_address": "0x0", @@ -465,52 +450,35 @@ def test_error_2_1(self, client, db): resp = client.post( self.apiurl, json=req_param, - headers={ - "issuer-address": test_account["address"] - } + headers={"issuer-address": test_account["address"]}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "loc": [ - "body", - "interest_rate" - ], + "loc": ["body", "interest_rate"], "msg": "interest_rate must be less than or equal to four decimal places", - "type": "value_error" + "type": "value_error", }, { - "loc": [ - "body", - "interest_payment_date" - ], + "loc": ["body", "interest_payment_date"], "msg": "list length of interest_payment_date must be less than 13", - "type": "value_error" + "type": "value_error", }, { - "loc": [ - "body", - "tradable_exchange_contract_address" - ], + "loc": ["body", "tradable_exchange_contract_address"], "msg": "tradable_exchange_contract_address is not a valid address", - "type": "value_error" + "type": "value_error", }, { - "loc": [ - "body", - "personal_info_contract_address" - ], + "loc": ["body", "personal_info_contract_address"], "msg": "personal_info_contract_address is not a valid address", - "type": "value_error" + "type": "value_error", }, - ] + ], } # @@ -530,27 +498,20 @@ def test_error_2_2(self, client, db): "purpose": "purpose_test1", } resp = client.post( - self.apiurl, - json=req_param, - headers={ - "issuer-address": "issuer-address" - } + self.apiurl, json=req_param, headers={"issuer-address": "issuer-address"} ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -583,22 +544,21 @@ def test_error_2_3(self, client, db): json=req_param, headers={ "issuer-address": test_account_1["address"], - "eoa-password": "password" - } + "eoa-password": "password", + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, - "detail": [{ - "loc": ["header", "eoa-password"], - "msg": "eoa-password is not a Base64-encoded encrypted data", - "type": "value_error" - }] + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ + { + "loc": ["header", "eoa-password"], + "msg": "eoa-password is not a Base64-encoded encrypted data", + "type": "value_error", + } + ], } # @@ -616,30 +576,23 @@ def test_error_2_4(self, client, db): "return_date": "20211231", "return_amount": "return_amount_test1", "purpose": "purpose_test1", - "is_redeemed": "invalid value" + "is_redeemed": "invalid value", } resp = client.post( - self.apiurl, - json=req_param, - headers={ - "issuer-address": "issuer-address" - } + self.apiurl, json=req_param, headers={"issuer-address": "issuer-address"} ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "is_redeemed"], "msg": "value could not be parsed to a boolean", - "type": "type_error.bool" + "type": "type_error.bool", } - ] + ], } # @@ -675,64 +628,39 @@ def test_error_2_5(self, client, db): resp = client.post( self.apiurl, json=req_param, - headers={ - "issuer-address": test_account["address"] - } + headers={"issuer-address": test_account["address"]}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "ctx": { - "limit_value": 0 - }, - "loc": [ - "body", - "total_supply" - ], + "ctx": {"limit_value": 0}, + "loc": ["body", "total_supply"], "msg": "ensure this value is greater than or equal to 0", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, { - "ctx": { - "limit_value": 0 - }, - "loc": [ - "body", - "face_value" - ], + "ctx": {"limit_value": 0}, + "loc": ["body", "face_value"], "msg": "ensure this value is greater than or equal to 0", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, { - "ctx": { - "limit_value": 0 - }, - "loc": [ - "body", - "redemption_value" - ], + "ctx": {"limit_value": 0}, + "loc": ["body", "redemption_value"], "msg": "ensure this value is greater than or equal to 0", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, { - "ctx": { - "limit_value": 0.0 - }, - "loc": [ - "body", - "interest_rate" - ], + "ctx": {"limit_value": 0.0}, + "loc": ["body", "interest_rate"], "msg": "ensure this value is greater than or equal to 0.0", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, - ] + ], } # @@ -768,80 +696,75 @@ def test_error_2_6(self, client, db): resp = client.post( self.apiurl, json=req_param, - headers={ - "issuer-address": test_account["address"] - } + headers={"issuer-address": test_account["address"]}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "loc": ["body", "name"], + "loc": ["body", "name"], "msg": "ensure this value has at most 100 characters", - "type": "value_error.any_str.max_length", - "ctx": {"limit_value": 100} + "type": "value_error.any_str.max_length", + "ctx": {"limit_value": 100}, }, { - "loc": ["body", "total_supply"], + "loc": ["body", "total_supply"], "msg": "ensure this value is less than or equal to 1000000000000", - "type": "value_error.number.not_le", - "ctx": {"limit_value": 1000000000000} + "type": "value_error.number.not_le", + "ctx": {"limit_value": 1000000000000}, }, { - "loc": ["body", "face_value"], + "loc": ["body", "face_value"], "msg": "ensure this value is less than or equal to 5000000000", - "type": "value_error.number.not_le", - "ctx": {"limit_value": 5000000000} + "type": "value_error.number.not_le", + "ctx": {"limit_value": 5000000000}, }, { "loc": ["body", "purpose"], "msg": "ensure this value has at most 2000 characters", "type": "value_error.any_str.max_length", - "ctx": {"limit_value": 2000} + "ctx": {"limit_value": 2000}, }, { - "loc": ["body", "symbol"], + "loc": ["body", "symbol"], "msg": "ensure this value has at most 100 characters", - "type": "value_error.any_str.max_length", - "ctx": {"limit_value": 100} + "type": "value_error.any_str.max_length", + "ctx": {"limit_value": 100}, }, { "loc": ["body", "redemption_value"], "msg": "ensure this value is less than or equal to 5000000000", - "type": "value_error.number.not_le", - "ctx": {"limit_value": 5000000000} + "type": "value_error.number.not_le", + "ctx": {"limit_value": 5000000000}, }, { - "loc": ["body", "return_amount"], + "loc": ["body", "return_amount"], "msg": "ensure this value has at most 2000 characters", - "type": "value_error.any_str.max_length", - "ctx": {"limit_value": 2000} + "type": "value_error.any_str.max_length", + "ctx": {"limit_value": 2000}, }, { - "loc": ["body", "interest_rate"], + "loc": ["body", "interest_rate"], "msg": "ensure this value is less than or equal to 100.0", - "type": "value_error.number.not_le", - "ctx": {"limit_value": 100.0} + "type": "value_error.number.not_le", + "ctx": {"limit_value": 100.0}, }, { - "loc": ["body", "contact_information"], + "loc": ["body", "contact_information"], "msg": "ensure this value has at most 2000 characters", - "type": "value_error.any_str.max_length", - "ctx": {"limit_value": 2000} + "type": "value_error.any_str.max_length", + "ctx": {"limit_value": 2000}, }, { - "loc": ["body", "privacy_policy"], + "loc": ["body", "privacy_policy"], "msg": "ensure this value has at most 5000 characters", - "type": "value_error.any_str.max_length", - "ctx": {"limit_value": 5000} - } - ] + "type": "value_error.any_str.max_length", + "ctx": {"limit_value": 5000}, + }, + ], } # @@ -862,40 +785,37 @@ def test_error_2_7(self, client, db): "interest_payment_date": ["invalid_date"], # update } resp = client.post( - self.apiurl, - json=req_param, - headers={ - "issuer-address": "issuer-address" - } + self.apiurl, json=req_param, headers={"issuer-address": "issuer-address"} ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - 'loc': ['body', 'redemption_date'], - 'msg': 'string does not match regex "^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$"', - 'type': 'value_error.str.regex', - 'ctx': {'pattern': '^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$'} + "loc": ["body", "redemption_date"], + "msg": 'string does not match regex "^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$"', + "type": "value_error.str.regex", + "ctx": { + "pattern": "^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$" + }, }, { - 'loc': ['body', 'return_date'], - 'msg': 'string does not match regex "^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$"', - 'type': 'value_error.str.regex', - 'ctx': {'pattern': '^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$'} + "loc": ["body", "return_date"], + "msg": 'string does not match regex "^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$"', + "type": "value_error.str.regex", + "ctx": { + "pattern": "^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$" + }, }, { - 'loc': ['body', 'interest_payment_date', 0], - 'msg': 'string does not match regex "^(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$"', - 'type': 'value_error.str.regex', - 'ctx': {'pattern': '^(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$'} - } - ] + "loc": ["body", "interest_payment_date", 0], + "msg": 'string does not match regex "^(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$"', + "type": "value_error.str.regex", + "ctx": {"pattern": "^(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$"}, + }, + ], } # @@ -928,18 +848,15 @@ def test_error_3_1(self, client, db): json=req_param, headers={ "issuer-address": test_account_2["address"], - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -971,18 +888,15 @@ def test_error_3_2(self, client, db): json=req_param, headers={ "issuer-address": test_account_1["address"], - "eoa-password": E2EEUtils.encrypt("password_test") - } + "eoa-password": E2EEUtils.encrypt("password_test"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -1002,7 +916,7 @@ def test_error_4_1(self, client, db): # mock IbetStraightBondContract_create = patch( target="app.model.blockchain.token.IbetStraightBondContract.create", - side_effect=SendTransactionError() + side_effect=SendTransactionError(), ) with IbetStraightBondContract_create: @@ -1023,18 +937,15 @@ def test_error_4_1(self, client, db): json=req_param, headers={ "issuer-address": test_account_1["address"], - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 2, - "title": "SendTransactionError" - }, - "detail": "failed to send transaction" + "meta": {"code": 2, "title": "SendTransactionError"}, + "detail": "failed to send transaction", } # @@ -1053,15 +964,14 @@ def test_error_5(self, client, db): # mock IbetStraightBondContract_create = patch( target="app.model.blockchain.token.IbetStraightBondContract.create", - return_value=("contract_address_test1", "abi_test1", "tx_hash_test1") + return_value=("contract_address_test1", "abi_test1", "tx_hash_test1"), ) TokenListContract_register = patch( target="app.model.blockchain.token_list.TokenListContract.register", - side_effect=SendTransactionError() + side_effect=SendTransactionError(), ) - with IbetStraightBondContract_create, \ - TokenListContract_register: + with IbetStraightBondContract_create, TokenListContract_register: # request target api req_param = { "name": "name_test1", @@ -1079,21 +989,18 @@ def test_error_5(self, client, db): json=req_param, headers={ "issuer-address": test_account["address"], - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 2, - "title": "SendTransactionError" - }, - "detail": "failed to register token address token list" + "meta": {"code": 2, "title": "SendTransactionError"}, + "detail": "failed to register token address token list", } def GetRandomStr(num): dat = string.digits + string.ascii_lowercase + string.ascii_uppercase - return ''.join([random.choice(dat) for i in range(num)]) + return "".join([random.choice(dat) for i in range(num)]) diff --git a/tests/test_app_routers_bond_tokens_{token_address}_GET.py b/tests/test_app_routers_bond_tokens_{token_address}_GET.py index 31390c0c..3e23aea6 100644 --- a/tests/test_app_routers_bond_tokens_{token_address}_GET.py +++ b/tests/test_app_routers_bond_tokens_{token_address}_GET.py @@ -16,15 +16,13 @@ SPDX-License-Identifier: Apache-2.0 """ -import pytz from unittest import mock -from config import TZ +import pytz + from app.model.blockchain import IbetStraightBondContract -from app.model.db import ( - Token, - TokenType -) +from app.model.db import Token, TokenType +from config import TZ class TestAppRoutersBondTokensTokenAddressGET: @@ -49,7 +47,12 @@ def test_normal_1(self, mock_get, client, db): token.abi = "abi_test1" db.add(token) db.commit() - _issue_datetime = pytz.timezone("UTC").localize(token.created).astimezone(self.local_tz).isoformat() + _issue_datetime = ( + pytz.timezone("UTC") + .localize(token.created) + .astimezone(self.local_tz) + .isoformat() + ) # request target API mock_token = IbetStraightBondContract() @@ -60,7 +63,9 @@ def test_normal_1(self, mock_get, client, db): mock_token.total_supply = 10000 mock_token.contact_information = "contactInformation_test1" mock_token.privacy_policy = "privacyPolicy_test1" - mock_token.tradable_exchange_contract_address = "0x1234567890abCdFe1234567890ABCdFE12345678" + mock_token.tradable_exchange_contract_address = ( + "0x1234567890abCdFe1234567890ABCdFE12345678" + ) mock_token.status = True mock_token.face_value = 200 mock_token.redemption_date = "redemptionDate_test1" @@ -72,14 +77,22 @@ def test_normal_1(self, mock_get, client, db): mock_token.transferable = True mock_token.is_offering = False mock_token.is_redeemed = False - mock_token.personal_info_contract_address = "0x1234567890aBcDFE1234567890abcDFE12345679" + mock_token.personal_info_contract_address = ( + "0x1234567890aBcDFE1234567890abcDFE12345679" + ) mock_token.interest_payment_date = [ - "interestPaymentDate1_test1", "interestPaymentDate2_test1", - "interestPaymentDate3_test1", "interestPaymentDate4_test1", - "interestPaymentDate5_test1", "interestPaymentDate6_test1", - "interestPaymentDate7_test1", "interestPaymentDate8_test1", - "interestPaymentDate9_test1", "interestPaymentDate10_test1", - "interestPaymentDate11_test1", "interestPaymentDate12_test1", + "interestPaymentDate1_test1", + "interestPaymentDate2_test1", + "interestPaymentDate3_test1", + "interestPaymentDate4_test1", + "interestPaymentDate5_test1", + "interestPaymentDate6_test1", + "interestPaymentDate7_test1", + "interestPaymentDate8_test1", + "interestPaymentDate9_test1", + "interestPaymentDate10_test1", + "interestPaymentDate11_test1", + "interestPaymentDate12_test1", ] mock_token.memo = "memo_test1" mock_token.transfer_approval_required = True @@ -111,12 +124,18 @@ def test_normal_1(self, mock_get, client, db): "is_redeemed": False, "personal_info_contract_address": "0x1234567890aBcDFE1234567890abcDFE12345679", "interest_payment_date": [ - "interestPaymentDate1_test1", "interestPaymentDate2_test1", - "interestPaymentDate3_test1", "interestPaymentDate4_test1", - "interestPaymentDate5_test1", "interestPaymentDate6_test1", - "interestPaymentDate7_test1", "interestPaymentDate8_test1", - "interestPaymentDate9_test1", "interestPaymentDate10_test1", - "interestPaymentDate11_test1", "interestPaymentDate12_test1", + "interestPaymentDate1_test1", + "interestPaymentDate2_test1", + "interestPaymentDate3_test1", + "interestPaymentDate4_test1", + "interestPaymentDate5_test1", + "interestPaymentDate6_test1", + "interestPaymentDate7_test1", + "interestPaymentDate8_test1", + "interestPaymentDate9_test1", + "interestPaymentDate10_test1", + "interestPaymentDate11_test1", + "interestPaymentDate12_test1", ], "issue_datetime": _issue_datetime, "token_status": 1, @@ -140,7 +159,12 @@ def test_normal_2(self, mock_get, client, db): token.abi = "abi_test1" db.add(token) db.commit() - _issue_datetime = pytz.timezone("UTC").localize(token.created).astimezone(self.local_tz).isoformat() + _issue_datetime = ( + pytz.timezone("UTC") + .localize(token.created) + .astimezone(self.local_tz) + .isoformat() + ) # request target API mock_token = IbetStraightBondContract() @@ -151,7 +175,9 @@ def test_normal_2(self, mock_get, client, db): mock_token.total_supply = 10000 mock_token.contact_information = "contactInformation_test1" mock_token.privacy_policy = "privacyPolicy_test1" - mock_token.tradable_exchange_contract_address = "0x1234567890abCdFe1234567890ABCdFE12345678" + mock_token.tradable_exchange_contract_address = ( + "0x1234567890abCdFe1234567890ABCdFE12345678" + ) mock_token.status = True mock_token.face_value = 200 mock_token.redemption_date = "redemptionDate_test1" @@ -163,14 +189,22 @@ def test_normal_2(self, mock_get, client, db): mock_token.transferable = True mock_token.is_offering = False mock_token.is_redeemed = False - mock_token.personal_info_contract_address = "0x1234567890aBcDFE1234567890abcDFE12345679" + mock_token.personal_info_contract_address = ( + "0x1234567890aBcDFE1234567890abcDFE12345679" + ) mock_token.interest_payment_date = [ - "interestPaymentDate1_test1", "interestPaymentDate2_test1", - "interestPaymentDate3_test1", "interestPaymentDate4_test1", - "interestPaymentDate5_test1", "interestPaymentDate6_test1", - "interestPaymentDate7_test1", "interestPaymentDate8_test1", - "interestPaymentDate9_test1", "interestPaymentDate10_test1", - "interestPaymentDate11_test1", "interestPaymentDate12_test1", + "interestPaymentDate1_test1", + "interestPaymentDate2_test1", + "interestPaymentDate3_test1", + "interestPaymentDate4_test1", + "interestPaymentDate5_test1", + "interestPaymentDate6_test1", + "interestPaymentDate7_test1", + "interestPaymentDate8_test1", + "interestPaymentDate9_test1", + "interestPaymentDate10_test1", + "interestPaymentDate11_test1", + "interestPaymentDate12_test1", ] mock_token.memo = "memo_test1" mock_token.transfer_approval_required = True @@ -202,12 +236,18 @@ def test_normal_2(self, mock_get, client, db): "is_redeemed": False, "personal_info_contract_address": "0x1234567890aBcDFE1234567890abcDFE12345679", "interest_payment_date": [ - "interestPaymentDate1_test1", "interestPaymentDate2_test1", - "interestPaymentDate3_test1", "interestPaymentDate4_test1", - "interestPaymentDate5_test1", "interestPaymentDate6_test1", - "interestPaymentDate7_test1", "interestPaymentDate8_test1", - "interestPaymentDate9_test1", "interestPaymentDate10_test1", - "interestPaymentDate11_test1", "interestPaymentDate12_test1", + "interestPaymentDate1_test1", + "interestPaymentDate2_test1", + "interestPaymentDate3_test1", + "interestPaymentDate4_test1", + "interestPaymentDate5_test1", + "interestPaymentDate6_test1", + "interestPaymentDate7_test1", + "interestPaymentDate8_test1", + "interestPaymentDate9_test1", + "interestPaymentDate10_test1", + "interestPaymentDate11_test1", + "interestPaymentDate12_test1", ], "issue_datetime": _issue_datetime, "token_status": 1, @@ -229,11 +269,8 @@ def test_error_1(self, client, db): assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # @@ -253,9 +290,6 @@ def test_error_2(self, client, db): assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } diff --git a/tests/test_app_routers_bond_tokens_{token_address}_POST.py b/tests/test_app_routers_bond_tokens_{token_address}_POST.py index 46c33c41..928b66b1 100644 --- a/tests/test_app_routers_bond_tokens_{token_address}_POST.py +++ b/tests/test_app_routers_bond_tokens_{token_address}_POST.py @@ -18,22 +18,14 @@ """ import hashlib from unittest import mock -from unittest.mock import ( - MagicMock, - ANY -) +from unittest.mock import ANY, MagicMock from web3 import Web3 from web3.middleware import geth_poa_middleware import config from app.exceptions import SendTransactionError -from app.model.db import ( - Account, - AuthToken, - Token, - TokenType -) +from app.model.db import Account, AuthToken, Token, TokenType from app.utils.e2ee_utils import E2EEUtils from tests.account_config import config_eth_account @@ -90,22 +82,20 @@ def test_normal_1(self, IbetStraightBondContract_mock, client, db): "contact_information": "問い合わせ先test", "privacy_policy": "プライバシーポリシーtest", "transfer_approval_required": True, - "memo": "m" * 10000 + "memo": "m" * 10000, } resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion IbetStraightBondContract_mock.assert_any_call( - data=req_param, - tx_from=_issuer_address, - private_key=ANY + data=req_param, tx_from=_issuer_address, private_key=ANY ) assert resp.status_code == 200 assert resp.json() is None @@ -144,8 +134,8 @@ def test_normal_2(self, IbetStraightBondContract_mock, client, db): json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion @@ -200,22 +190,20 @@ def test_normal_3(self, IbetStraightBondContract_mock, client, db): "contact_information": "問い合わせ先test", "privacy_policy": "プライバシーポリシーtest", "transfer_approval_required": True, - "memo": "memo_test1" + "memo": "memo_test1", } resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "auth-token": "test_auth_token" - } + "auth-token": "test_auth_token", + }, ) # assertion IbetStraightBondContract_mock.assert_any_call( - data=req_param, - tx_from=_issuer_address, - private_key=ANY + data=req_param, tx_from=_issuer_address, private_key=ANY ) assert resp.status_code == 200 assert resp.json() is None @@ -236,27 +224,19 @@ def test_error_1(self, client, db): resp = client.post( self.base_url.format(_token_address), json=req_param, - headers={ - "issuer-address": "" - } + headers={"issuer-address": ""}, ) assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "loc": [ - "body", - "interest_rate" - ], + "loc": ["body", "interest_rate"], "msg": "interest_rate must be rounded to 4 decimal places", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -267,33 +247,38 @@ def test_error_2_1(self, client, db): # request target API req_param = { - "interest_payment_date": ["0101", "0102", "0103", "0104", "0105", "0106", "0107", "0108", "0109", "0110", - "0111", "0112", "0113"], + "interest_payment_date": [ + "0101", + "0102", + "0103", + "0104", + "0105", + "0106", + "0107", + "0108", + "0109", + "0110", + "0111", + "0112", + "0113", + ], } resp = client.post( self.base_url.format(_token_address), json=req_param, - headers={ - "issuer-address": "" - } + headers={"issuer-address": ""}, ) assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "loc": [ - "body", - "interest_payment_date" - ], + "loc": ["body", "interest_payment_date"], "msg": "list length of interest_payment_date must be less than 13", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -304,32 +289,25 @@ def test_error_2_2(self, client, db): # request target API req_param = { - "interest_payment_date": [ - "01010" - ], + "interest_payment_date": ["01010"], } resp = client.post( self.base_url.format(_token_address), json=req_param, - headers={ - "issuer-address": "" - } + headers={"issuer-address": ""}, ) assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - 'loc': ['body', 'interest_payment_date', 0], - 'msg': 'string does not match regex "^(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$"', - 'type': 'value_error.str.regex', - 'ctx': {'pattern': '^(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$'} + "loc": ["body", "interest_payment_date", 0], + "msg": 'string does not match regex "^(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$"', + "type": "value_error.str.regex", + "ctx": {"pattern": "^(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$"}, } - ] + ], } # @@ -338,33 +316,23 @@ def test_error_4(self, client, db): _token_address = "0x82b1c9374aB625380bd498a3d9dF4033B8A0E3Bb" # request target API - req_param = { - "tradable_exchange_contract_address": "invalid_address" - } + req_param = {"tradable_exchange_contract_address": "invalid_address"} resp = client.post( self.base_url.format(_token_address), json=req_param, - headers={ - "issuer-address": "" - } + headers={"issuer-address": ""}, ) assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "loc": [ - "body", - "tradable_exchange_contract_address" - ], + "loc": ["body", "tradable_exchange_contract_address"], "msg": "tradable_exchange_contract_address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -373,33 +341,23 @@ def test_error_5(self, client, db): _token_address = "0x82b1c9374aB625380bd498a3d9dF4033B8A0E3Bb" # request target API - req_param = { - "personal_info_contract_address": "invalid_address" - } + req_param = {"personal_info_contract_address": "invalid_address"} resp = client.post( self.base_url.format(_token_address), json=req_param, - headers={ - "issuer-address": "" - } + headers={"issuer-address": ""}, ) assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "loc": [ - "body", - "personal_info_contract_address" - ], + "loc": ["body", "personal_info_contract_address"], "msg": "personal_info_contract_address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -408,29 +366,24 @@ def test_error_6(self, client, db): _token_address = "0x82b1c9374aB625380bd498a3d9dF4033B8A0E3Bb" # request target API - resp = client.post( - self.base_url.format(_token_address) - ) + resp = client.post(self.base_url.format(_token_address)) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, { "loc": ["body"], "msg": "field required", - "type": "value_error.missing" - } - ] + "type": "value_error.missing", + }, + ], } # @@ -445,25 +398,20 @@ def test_error_7(self, client, db): resp = client.post( self.base_url.format(_token_address), json=req_param, - headers={ - "issuer-address": "issuer-address" - } + headers={"issuer-address": "issuer-address"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -489,29 +437,25 @@ def test_error_8(self, client, db): "contact_information": "問い合わせ先test", "privacy_policy": "プライバシーポリシーtest", "transfer_approval_required": True, - "memo": "memo_test1" + "memo": "memo_test1", } resp = client.post( self.base_url.format(_token_address), json=req_param, - headers={ - "issuer-address": _issuer_address, - "eoa-password": "password" - } + headers={"issuer-address": _issuer_address, "eoa-password": "password"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, - "detail": [{ - "loc": ["header", "eoa-password"], - "msg": "eoa-password is not a Base64-encoded encrypted data", - "type": "value_error" - }] + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ + { + "loc": ["header", "eoa-password"], + "msg": "eoa-password is not a Base64-encoded encrypted data", + "type": "value_error", + } + ], } # @@ -542,54 +486,33 @@ def test_error_9(self, client, db): resp = client.post( self.base_url.format(_token_address), json=req_param, - headers={ - "issuer-address": _issuer_address, - "eoa-password": "password" - } + headers={"issuer-address": _issuer_address, "eoa-password": "password"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "ctx": { - "limit_value": 0 - }, - "loc": [ - "body", - "face_value" - ], + "ctx": {"limit_value": 0}, + "loc": ["body", "face_value"], "msg": "ensure this value is greater than or equal to 0", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, { - "ctx": { - "limit_value": 0.0000 - }, - "loc": [ - "body", - "interest_rate" - ], + "ctx": {"limit_value": 0.0000}, + "loc": ["body", "interest_rate"], "msg": "ensure this value is greater than or equal to 0.0", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, { - "ctx": { - "limit_value": 0 - }, - "loc": [ - "body", - "redemption_value" - ], + "ctx": {"limit_value": 0}, + "loc": ["body", "redemption_value"], "msg": "ensure this value is greater than or equal to 0", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, - ] + ], } # @@ -620,54 +543,33 @@ def test_error_10(self, client, db): resp = client.post( self.base_url.format(_token_address), json=req_param, - headers={ - "issuer-address": _issuer_address, - "eoa-password": "password" - } + headers={"issuer-address": _issuer_address, "eoa-password": "password"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "ctx": { - "limit_value": 5_000_000_000 - }, - "loc": [ - "body", - "face_value" - ], + "ctx": {"limit_value": 5_000_000_000}, + "loc": ["body", "face_value"], "msg": "ensure this value is less than or equal to 5000000000", - "type": "value_error.number.not_le" + "type": "value_error.number.not_le", }, { - "ctx": { - "limit_value": 100.0000 - }, - "loc": [ - "body", - "interest_rate" - ], + "ctx": {"limit_value": 100.0000}, + "loc": ["body", "interest_rate"], "msg": "ensure this value is less than or equal to 100.0", - "type": "value_error.number.not_le" + "type": "value_error.number.not_le", }, { - "ctx": { - "limit_value": 5_000_000_000 - }, - "loc": [ - "body", - "redemption_value" - ], + "ctx": {"limit_value": 5_000_000_000}, + "loc": ["body", "redemption_value"], "msg": "ensure this value is less than or equal to 5000000000", - "type": "value_error.number.not_le" + "type": "value_error.number.not_le", }, - ] + ], } # @@ -697,18 +599,15 @@ def test_error_11(self, IbetStraightBondContract_mock, client, db): json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -737,18 +636,15 @@ def test_error_12(self, IbetStraightBondContract_mock, client, db): json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password_test") - } + "eoa-password": E2EEUtils.encrypt("password_test"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -777,18 +673,15 @@ def test_error_13(self, IbetStraightBondContract_mock, client, db): json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # @@ -822,24 +715,23 @@ def test_error_14(self, client, db): json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } # # Send Transaction Error - @mock.patch("app.model.blockchain.token.IbetStraightBondContract.update", - MagicMock(side_effect=SendTransactionError())) + @mock.patch( + "app.model.blockchain.token.IbetStraightBondContract.update", + MagicMock(side_effect=SendTransactionError()), + ) def test_error_15(self, client, db): test_account = config_eth_account("user1") _issuer_address = test_account["address"] @@ -868,16 +760,13 @@ def test_error_15(self, client, db): json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 2, - "title": "SendTransactionError" - }, - "detail": "failed to send transaction" + "meta": {"code": 2, "title": "SendTransactionError"}, + "detail": "failed to send transaction", } diff --git a/tests/test_app_routers_bond_tokens_{token_address}_additional_issue_GET.py b/tests/test_app_routers_bond_tokens_{token_address}_additional_issue_GET.py index 1c341f62..a2f5f27e 100644 --- a/tests/test_app_routers_bond_tokens_{token_address}_additional_issue_GET.py +++ b/tests/test_app_routers_bond_tokens_{token_address}_additional_issue_GET.py @@ -22,17 +22,17 @@ import config from app.model.db import ( + IDXIssueRedeem, + IDXIssueRedeemEventType, + IDXIssueRedeemSortItem, Token, TokenType, - IDXIssueRedeem, - IDXIssueRedeemEventType, IDXIssueRedeemSortItem ) local_tz = timezone(config.TZ) class TestAppRoutersBondTokensTokenAddressAdditionalIssueGET: - # target API endpoint base_url = "/bond/tokens/{}/additional_issue" @@ -48,9 +48,9 @@ class TestAppRoutersBondTokensTokenAddressAdditionalIssueGET: test_amount = [10, 20, 30] test_block_timestamp = [ - datetime.strptime("2022/01/02 15:20:30", '%Y/%m/%d %H:%M:%S'), # JST 2022/01/03 - datetime.strptime("2022/01/01 15:20:30", '%Y/%m/%d %H:%M:%S'), # JST 2022/01/02 - datetime.strptime("2022/01/02 00:20:30", '%Y/%m/%d %H:%M:%S'), # JST 2022/01/02 + datetime.strptime("2022/01/02 15:20:30", "%Y/%m/%d %H:%M:%S"), # JST 2022/01/03 + datetime.strptime("2022/01/01 15:20:30", "%Y/%m/%d %H:%M:%S"), # JST 2022/01/02 + datetime.strptime("2022/01/02 00:20:30", "%Y/%m/%d %H:%M:%S"), # JST 2022/01/02 ] test_block_timestamp_str = [ "2022-01-03T00:20:30+09:00", @@ -86,20 +86,13 @@ def test_normal_1(self, client, db): db.add(_record) # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 0, - 'offset': None, - 'limit': None, - 'total': 0 - }, - 'history': [] + "result_set": {"count": 0, "offset": None, "limit": None, "total": 0}, + "history": [], } # Normal_2 @@ -146,45 +139,38 @@ def test_normal_2(self, client, db): db.add(_record) # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 3, - 'offset': None, - 'limit': None, - 'total': 3 - }, - 'history': [ + "result_set": {"count": 3, "offset": None, "limit": None, "total": 3}, + "history": [ { - 'transaction_hash': self.test_transaction_hash, - 'token_address': self.test_token_address, - 'locked_address': self.test_locked_address, - 'target_address': self.test_target_address, - 'amount': self.test_amount[0], - 'block_timestamp': self.test_block_timestamp_str[0] + "transaction_hash": self.test_transaction_hash, + "token_address": self.test_token_address, + "locked_address": self.test_locked_address, + "target_address": self.test_target_address, + "amount": self.test_amount[0], + "block_timestamp": self.test_block_timestamp_str[0], }, { - 'transaction_hash': self.test_transaction_hash, - 'token_address': self.test_token_address, - 'locked_address': self.test_locked_address, - 'target_address': self.test_target_address, - 'amount': self.test_amount[2], - 'block_timestamp': self.test_block_timestamp_str[2] + "transaction_hash": self.test_transaction_hash, + "token_address": self.test_token_address, + "locked_address": self.test_locked_address, + "target_address": self.test_target_address, + "amount": self.test_amount[2], + "block_timestamp": self.test_block_timestamp_str[2], }, { - 'transaction_hash': self.test_transaction_hash, - 'token_address': self.test_token_address, - 'locked_address': self.test_locked_address, - 'target_address': self.test_target_address, - 'amount': self.test_amount[1], - 'block_timestamp': self.test_block_timestamp_str[1] - } - ] + "transaction_hash": self.test_transaction_hash, + "token_address": self.test_token_address, + "locked_address": self.test_locked_address, + "target_address": self.test_target_address, + "amount": self.test_amount[1], + "block_timestamp": self.test_block_timestamp_str[1], + }, + ], } # Normal_3 @@ -235,45 +221,40 @@ def test_normal_3(self, client, db): self.base_url.format(self.test_token_address), params={ "sort_item": IDXIssueRedeemSortItem.BLOCK_TIMESTAMP.value, - "sort_order": 0 - } + "sort_order": 0, + }, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 3, - 'offset': None, - 'limit': None, - 'total': 3 - }, - 'history': [ + "result_set": {"count": 3, "offset": None, "limit": None, "total": 3}, + "history": [ { - 'transaction_hash': self.test_transaction_hash, - 'token_address': self.test_token_address, - 'locked_address': self.test_locked_address, - 'target_address': self.test_target_address, - 'amount': self.test_amount[1], - 'block_timestamp': self.test_block_timestamp_str[1] + "transaction_hash": self.test_transaction_hash, + "token_address": self.test_token_address, + "locked_address": self.test_locked_address, + "target_address": self.test_target_address, + "amount": self.test_amount[1], + "block_timestamp": self.test_block_timestamp_str[1], }, { - 'transaction_hash': self.test_transaction_hash, - 'token_address': self.test_token_address, - 'locked_address': self.test_locked_address, - 'target_address': self.test_target_address, - 'amount': self.test_amount[2], - 'block_timestamp': self.test_block_timestamp_str[2] + "transaction_hash": self.test_transaction_hash, + "token_address": self.test_token_address, + "locked_address": self.test_locked_address, + "target_address": self.test_target_address, + "amount": self.test_amount[2], + "block_timestamp": self.test_block_timestamp_str[2], }, { - 'transaction_hash': self.test_transaction_hash, - 'token_address': self.test_token_address, - 'locked_address': self.test_locked_address, - 'target_address': self.test_target_address, - 'amount': self.test_amount[0], - 'block_timestamp': self.test_block_timestamp_str[0] - } - ] + "transaction_hash": self.test_transaction_hash, + "token_address": self.test_token_address, + "locked_address": self.test_locked_address, + "target_address": self.test_target_address, + "amount": self.test_amount[0], + "block_timestamp": self.test_block_timestamp_str[0], + }, + ], } # Normal_4 @@ -322,31 +303,23 @@ def test_normal_4(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "offset": 1, - "limit": 1 - } + params={"offset": 1, "limit": 1}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 3, - 'offset': 1, - 'limit': 1, - 'total': 3 - }, - 'history': [ + "result_set": {"count": 3, "offset": 1, "limit": 1, "total": 3}, + "history": [ { - 'transaction_hash': self.test_transaction_hash, - 'token_address': self.test_token_address, - 'locked_address': self.test_locked_address, - 'target_address': self.test_target_address, - 'amount': self.test_amount[2], - 'block_timestamp': self.test_block_timestamp_str[2] + "transaction_hash": self.test_transaction_hash, + "token_address": self.test_token_address, + "locked_address": self.test_locked_address, + "target_address": self.test_target_address, + "amount": self.test_amount[2], + "block_timestamp": self.test_block_timestamp_str[2], } - ] + ], } ########################################################################### @@ -357,18 +330,13 @@ def test_normal_4(self, client, db): # NotFound def test_error_1(self, client, db): # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # Error_2 @@ -386,18 +354,13 @@ def test_error_2(self, client, db): db.add(_token) # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } # Error_3 @@ -407,33 +370,28 @@ def test_error_3(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "sort_item": "block_timestamp12345" - } + params={"sort_item": "block_timestamp12345"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['query', 'sort_item'], - 'msg': "value is not a valid enumeration member; permitted: 'block_timestamp', 'locked_address', 'target_address', 'amount'", - 'type': 'type_error.enum', - 'ctx': { - 'enum_values': [ - 'block_timestamp', - 'locked_address', - 'target_address', - 'amount' + "loc": ["query", "sort_item"], + "msg": "value is not a valid enumeration member; permitted: 'block_timestamp', 'locked_address', 'target_address', 'amount'", + "type": "type_error.enum", + "ctx": { + "enum_values": [ + "block_timestamp", + "locked_address", + "target_address", + "amount", ] - } + }, } - ] + ], } # Error_4_1 @@ -442,27 +400,21 @@ def test_error_3(self, client, db): def test_error_4_1(self, client, db): # request target API resp = client.get( - self.base_url.format(self.test_token_address), - params={ - "sort_order": -1 - } + self.base_url.format(self.test_token_address), params={"sort_order": -1} ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "ctx": {"limit_value": 0}, "loc": ["query", "sort_order"], "msg": "ensure this value is greater than or equal to 0", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", } - ] + ], } # Error_4_2 @@ -471,25 +423,19 @@ def test_error_4_1(self, client, db): def test_error_4_2(self, client, db): # request target API resp = client.get( - self.base_url.format(self.test_token_address), - params={ - "sort_order": 2 - } + self.base_url.format(self.test_token_address), params={"sort_order": 2} ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "ctx": {"limit_value": 1}, "loc": ["query", "sort_order"], "msg": "ensure this value is less than or equal to 1", - "type": "value_error.number.not_le" + "type": "value_error.number.not_le", } - ] + ], } diff --git a/tests/test_app_routers_bond_tokens_{token_address}_additional_issue_POST.py b/tests/test_app_routers_bond_tokens_{token_address}_additional_issue_POST.py index 28f75929..b4de4ad3 100644 --- a/tests/test_app_routers_bond_tokens_{token_address}_additional_issue_POST.py +++ b/tests/test_app_routers_bond_tokens_{token_address}_additional_issue_POST.py @@ -20,14 +20,9 @@ from unittest import mock from unittest.mock import ANY, MagicMock -from app.model.db import ( - Account, - AuthToken, - Token, - TokenType -) -from app.utils.e2ee_utils import E2EEUtils from app.exceptions import SendTransactionError +from app.model.db import Account, AuthToken, Token, TokenType +from app.utils.e2ee_utils import E2EEUtils from tests.account_config import config_eth_account @@ -67,24 +62,19 @@ def test_normal_1(self, IbetStraightBondContract_mock, client, db): IbetStraightBondContract_mock.side_effect = [None] # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion IbetStraightBondContract_mock.assert_any_call( - data=req_param, - tx_from=_issuer_address, - private_key=ANY + data=req_param, tx_from=_issuer_address, private_key=ANY ) assert resp.status_code == 200 @@ -124,24 +114,19 @@ def test_normal_2(self, IbetStraightBondContract_mock, client, db): IbetStraightBondContract_mock.side_effect = [None] # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "auth-token": "test_auth_token" - } + "auth-token": "test_auth_token", + }, ) # assertion IbetStraightBondContract_mock.assert_any_call( - data=req_param, - tx_from=_issuer_address, - private_key=ANY + data=req_param, tx_from=_issuer_address, private_key=ANY ) assert resp.status_code == 200 @@ -169,37 +154,28 @@ def test_error_1(self, client, db): db.add(token) # request target API - req_param = { - "account_address": "0x0", - "amount": 10 - } + req_param = {"account_address": "0x0", "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "loc": [ - "body", - "account_address" - ], + "loc": ["body", "account_address"], "msg": "account_address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -220,40 +196,29 @@ def test_error_2(self, client, db): db.add(token) # request target API - req_param = { - "account_address": _issuer_address, - "amount": 0 - } + req_param = {"account_address": _issuer_address, "amount": 0} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "ctx": { - "limit_value": 1 - }, - "loc": [ - "body", - "amount" - ], + "ctx": {"limit_value": 1}, + "loc": ["body", "amount"], "msg": "ensure this value is greater than or equal to 1", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, - ] + ], } # @@ -274,40 +239,29 @@ def test_error_3(self, client, db): db.add(token) # request target API - req_param = { - "account_address": _issuer_address, - "amount": 1_000_000_000_001 - } + req_param = {"account_address": _issuer_address, "amount": 1_000_000_000_001} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "ctx": { - "limit_value": 1_000_000_000_000 - }, - "loc": [ - "body", - "amount" - ], + "ctx": {"limit_value": 1_000_000_000_000}, + "loc": ["body", "amount"], "msg": "ensure this value is less than or equal to 1000000000000", - "type": "value_error.number.not_le" + "type": "value_error.number.not_le", }, - ] + ], } # @@ -316,29 +270,24 @@ def test_error_4(self, client, db): _token_address = "token_address_test" # request target API - resp = client.post( - self.base_url.format(_token_address) - ) + resp = client.post(self.base_url.format(_token_address)) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, { "loc": ["body"], "msg": "field required", - "type": "value_error.missing" - } - ] + "type": "value_error.missing", + }, + ], } # @@ -349,33 +298,25 @@ def test_error_5(self, client, db): _token_address = "token_address_test" # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, - headers={ - "issuer-address": "issuer-address" - } + headers={"issuer-address": "issuer-address"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -394,30 +335,23 @@ def test_error_6(self, client, db): db.add(account) # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, - headers={ - "issuer-address": _issuer_address, - "eoa-password": "password" - } + headers={"issuer-address": _issuer_address, "eoa-password": "password"}, ) assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, - "detail": [{ - "loc": ["header", "eoa-password"], - "msg": "eoa-password is not a Base64-encoded encrypted data", - "type": "value_error" - }] + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ + { + "loc": ["header", "eoa-password"], + "msg": "eoa-password is not a Base64-encoded encrypted data", + "type": "value_error", + } + ], } # @@ -438,28 +372,22 @@ def test_error_7(self, client, db): db.add(token) # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -478,26 +406,20 @@ def test_error_8(self, client, db): db.add(account) # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password_test") - } + "eoa-password": E2EEUtils.encrypt("password_test"), + }, ) assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -516,26 +438,20 @@ def test_error_9(self, client, db): db.add(account) # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # @@ -563,33 +479,29 @@ def test_error_10(self, client, db): db.add(token) # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } # # Send Transaction Error - @mock.patch("app.model.blockchain.token.IbetStraightBondContract.additional_issue", - MagicMock(side_effect=SendTransactionError())) + @mock.patch( + "app.model.blockchain.token.IbetStraightBondContract.additional_issue", + MagicMock(side_effect=SendTransactionError()), + ) def test_error_11(self, client, db): test_account = config_eth_account("user1") _issuer_address = test_account["address"] @@ -612,25 +524,19 @@ def test_error_11(self, client, db): db.add(token) # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 2, - "title": "SendTransactionError" - }, - "detail": "failed to send transaction" + "meta": {"code": 2, "title": "SendTransactionError"}, + "detail": "failed to send transaction", } diff --git a/tests/test_app_routers_bond_tokens_{token_address}_additional_issue_batch_GET.py b/tests/test_app_routers_bond_tokens_{token_address}_additional_issue_batch_GET.py index 378144c6..cc837f4f 100644 --- a/tests/test_app_routers_bond_tokens_{token_address}_additional_issue_batch_GET.py +++ b/tests/test_app_routers_bond_tokens_{token_address}_additional_issue_batch_GET.py @@ -20,10 +20,10 @@ from unittest import mock from app.model.db import ( + BatchIssueRedeemProcessingCategory, + BatchIssueRedeemUpload, Token, TokenType, - BatchIssueRedeemUpload, - BatchIssueRedeemProcessingCategory ) from tests.account_config import config_eth_account @@ -53,21 +53,13 @@ def test_normal_1(self, client, db): db.add(token) # request target API - resp = client.get( - self.base_url.format(token_address), - headers={} - ) + resp = client.get(self.base_url.format(token_address), headers={}) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 0, - "limit": None, - "offset": None, - "total": 0 - }, - "uploads": [] - } + "result_set": {"count": 0, "limit": None, "offset": None, "total": 0}, + "uploads": [], + } # # 1 record @@ -90,35 +82,28 @@ def test_normal_2(self, client, db): additional_issue_upload1.token_address = token_address additional_issue_upload1.issuer_address = issuer_address additional_issue_upload1.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload1.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload1.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload1.processed = False db.add(additional_issue_upload1) # request target API - resp = client.get( - self.base_url.format(token_address), - headers={} - ) + resp = client.get(self.base_url.format(token_address), headers={}) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 1, - "limit": None, - "offset": None, - "total": 1 - }, - "uploads": - [ + "result_set": {"count": 1, "limit": None, "offset": None, "total": 1}, + "uploads": [ { "issuer_address": issuer_address, "processed": False, "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, } - ] + ], } # @@ -143,7 +128,9 @@ def test_normal_3_1(self, client, db): additional_issue_upload1.token_address = token_address additional_issue_upload1.issuer_address = issuer_address additional_issue_upload1.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload1.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload1.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload1.processed = True db.add(additional_issue_upload1) @@ -152,7 +139,9 @@ def test_normal_3_1(self, client, db): additional_issue_upload2.token_address = token_address additional_issue_upload2.issuer_address = issuer_address additional_issue_upload2.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload2.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload2.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload2.processed = False db.add(additional_issue_upload2) @@ -161,7 +150,9 @@ def test_normal_3_1(self, client, db): additional_issue_upload3.token_address = token_address additional_issue_upload3.issuer_address = issuer_address additional_issue_upload3.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload3.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload3.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload3.processed = False db.add(additional_issue_upload3) @@ -170,7 +161,9 @@ def test_normal_3_1(self, client, db): additional_issue_upload4.token_address = token_address additional_issue_upload4.issuer_address = issuer_address additional_issue_upload4.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload4.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload4.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload4.processed = False db.add(additional_issue_upload4) @@ -179,24 +172,18 @@ def test_normal_3_1(self, client, db): additional_issue_upload5.token_address = "other_token" additional_issue_upload5.issuer_address = issuer_address additional_issue_upload5.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload5.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload5.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload5.processed = False db.add(additional_issue_upload5) # request target API - resp = client.get( - self.base_url.format(token_address), - headers={} - ) + resp = client.get(self.base_url.format(token_address), headers={}) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 4, - "limit": None, - "offset": None, - "total": 4 - }, + "result_set": {"count": 4, "limit": None, "offset": None, "total": 4}, "uploads": [ { "issuer_address": issuer_address, @@ -204,7 +191,7 @@ def test_normal_3_1(self, client, db): "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -212,7 +199,7 @@ def test_normal_3_1(self, client, db): "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -220,7 +207,7 @@ def test_normal_3_1(self, client, db): "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -228,9 +215,9 @@ def test_normal_3_1(self, client, db): "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY - } - ] + "created": mock.ANY, + }, + ], } # @@ -255,7 +242,9 @@ def test_normal_3_2(self, client, db): additional_issue_upload1.token_address = token_address additional_issue_upload1.issuer_address = issuer_address additional_issue_upload1.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload1.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload1.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload1.processed = True db.add(additional_issue_upload1) @@ -264,7 +253,9 @@ def test_normal_3_2(self, client, db): additional_issue_upload2.token_address = token_address additional_issue_upload2.issuer_address = issuer_address additional_issue_upload2.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload2.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload2.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload2.processed = False db.add(additional_issue_upload2) @@ -273,7 +264,9 @@ def test_normal_3_2(self, client, db): additional_issue_upload3.token_address = token_address additional_issue_upload3.issuer_address = "other_issuer" additional_issue_upload3.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload3.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload3.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload3.processed = False db.add(additional_issue_upload3) @@ -282,7 +275,9 @@ def test_normal_3_2(self, client, db): additional_issue_upload4.token_address = token_address additional_issue_upload4.issuer_address = "other_issuer" additional_issue_upload4.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload4.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload4.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload4.processed = False db.add(additional_issue_upload4) @@ -291,26 +286,21 @@ def test_normal_3_2(self, client, db): additional_issue_upload5.token_address = "other_token" additional_issue_upload5.issuer_address = issuer_address additional_issue_upload5.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload5.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload5.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload5.processed = False db.add(additional_issue_upload5) # request target API resp = client.get( self.base_url.format(token_address), - headers={ - "issuer-address": issuer_address - } + headers={"issuer-address": issuer_address}, ) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 2, - "limit": None, - "offset": None, - "total": 2 - }, + "result_set": {"count": 2, "limit": None, "offset": None, "total": 2}, "uploads": [ { "issuer_address": issuer_address, @@ -318,7 +308,7 @@ def test_normal_3_2(self, client, db): "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -326,10 +316,10 @@ def test_normal_3_2(self, client, db): "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY - } - ] - } + "created": mock.ANY, + }, + ], + } # # Multi record (status) @@ -353,7 +343,9 @@ def test_normal_3_3(self, client, db): additional_issue_upload1.token_address = token_address additional_issue_upload1.issuer_address = issuer_address additional_issue_upload1.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload1.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload1.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload1.processed = True db.add(additional_issue_upload1) @@ -362,7 +354,9 @@ def test_normal_3_3(self, client, db): additional_issue_upload2.token_address = token_address additional_issue_upload2.issuer_address = issuer_address additional_issue_upload2.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload2.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload2.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload2.processed = False db.add(additional_issue_upload2) @@ -371,7 +365,9 @@ def test_normal_3_3(self, client, db): additional_issue_upload3.token_address = token_address additional_issue_upload3.issuer_address = issuer_address additional_issue_upload3.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload3.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload3.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload3.processed = False db.add(additional_issue_upload3) @@ -380,7 +376,9 @@ def test_normal_3_3(self, client, db): additional_issue_upload4.token_address = token_address additional_issue_upload4.issuer_address = issuer_address additional_issue_upload4.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload4.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload4.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload4.processed = False db.add(additional_issue_upload4) @@ -389,36 +387,27 @@ def test_normal_3_3(self, client, db): additional_issue_upload5.token_address = "other_token" additional_issue_upload5.issuer_address = issuer_address additional_issue_upload5.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload5.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload5.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload5.processed = False db.add(additional_issue_upload5) # request target API - req_param = { - "processed": False - } - resp = client.get( - self.base_url.format(token_address), - params=req_param - ) + req_param = {"processed": False} + resp = client.get(self.base_url.format(token_address), params=req_param) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 3, - "limit": None, - "offset": None, - "total": 4 - }, - "uploads": - [ + "result_set": {"count": 3, "limit": None, "offset": None, "total": 4}, + "uploads": [ { "issuer_address": issuer_address, "processed": False, "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -426,7 +415,7 @@ def test_normal_3_3(self, client, db): "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -434,9 +423,9 @@ def test_normal_3_3(self, client, db): "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY - } - ] + "created": mock.ANY, + }, + ], } # @@ -461,7 +450,9 @@ def test_normal_4(self, client, db): additional_issue_upload1.token_address = token_address additional_issue_upload1.issuer_address = issuer_address additional_issue_upload1.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload1.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload1.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload1.processed = True db.add(additional_issue_upload1) @@ -470,7 +461,9 @@ def test_normal_4(self, client, db): additional_issue_upload2.token_address = token_address additional_issue_upload2.issuer_address = issuer_address additional_issue_upload2.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload2.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload2.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload2.processed = False db.add(additional_issue_upload2) @@ -479,7 +472,9 @@ def test_normal_4(self, client, db): additional_issue_upload3.token_address = token_address additional_issue_upload3.issuer_address = issuer_address additional_issue_upload3.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload3.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload3.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload3.processed = False db.add(additional_issue_upload3) @@ -488,7 +483,9 @@ def test_normal_4(self, client, db): additional_issue_upload4.token_address = token_address additional_issue_upload4.issuer_address = issuer_address additional_issue_upload4.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload4.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload4.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload4.processed = False db.add(additional_issue_upload4) @@ -497,28 +494,19 @@ def test_normal_4(self, client, db): additional_issue_upload5.token_address = "other_token" additional_issue_upload5.issuer_address = issuer_address additional_issue_upload5.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload5.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload5.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload5.processed = False db.add(additional_issue_upload5) # request target API - req_param = { - "limit": 2, - "offset": 2 - } - resp = client.get( - self.base_url.format(token_address), - params=req_param - ) + req_param = {"limit": 2, "offset": 2} + resp = client.get(self.base_url.format(token_address), params=req_param) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 4, - "limit": 2, - "offset": 2, - "total": 4 - }, + "result_set": {"count": 4, "limit": 2, "offset": 2, "total": 4}, "uploads": [ { "issuer_address": issuer_address, @@ -526,7 +514,7 @@ def test_normal_4(self, client, db): "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -534,9 +522,9 @@ def test_normal_4(self, client, db): "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY - } - ] + "created": mock.ANY, + }, + ], } # @@ -561,7 +549,9 @@ def test_normal_5(self, client, db): additional_issue_upload1.token_address = token_address additional_issue_upload1.issuer_address = issuer_address additional_issue_upload1.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload1.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload1.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload1.processed = True db.add(additional_issue_upload1) @@ -570,7 +560,9 @@ def test_normal_5(self, client, db): additional_issue_upload2.token_address = token_address additional_issue_upload2.issuer_address = issuer_address additional_issue_upload2.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload2.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload2.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload2.processed = False db.add(additional_issue_upload2) @@ -579,7 +571,9 @@ def test_normal_5(self, client, db): additional_issue_upload3.token_address = token_address additional_issue_upload3.issuer_address = issuer_address additional_issue_upload3.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload3.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload3.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload3.processed = True db.add(additional_issue_upload3) @@ -588,7 +582,9 @@ def test_normal_5(self, client, db): additional_issue_upload4.token_address = token_address additional_issue_upload4.issuer_address = issuer_address additional_issue_upload4.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload4.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload4.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload4.processed = False db.add(additional_issue_upload4) @@ -597,27 +593,19 @@ def test_normal_5(self, client, db): additional_issue_upload5.token_address = "other_token" additional_issue_upload5.issuer_address = issuer_address additional_issue_upload5.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload5.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload5.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload5.processed = False db.add(additional_issue_upload5) # request target API - req_param = { - "sort_order": 0 - } - resp = client.get( - self.base_url.format(token_address), - params=req_param - ) + req_param = {"sort_order": 0} + resp = client.get(self.base_url.format(token_address), params=req_param) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 4, - "limit": None, - "offset": None, - "total": 4 - }, + "result_set": {"count": 4, "limit": None, "offset": None, "total": 4}, "uploads": [ { "issuer_address": issuer_address, @@ -625,7 +613,7 @@ def test_normal_5(self, client, db): "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -633,7 +621,7 @@ def test_normal_5(self, client, db): "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -641,7 +629,7 @@ def test_normal_5(self, client, db): "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -649,9 +637,9 @@ def test_normal_5(self, client, db): "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY - } - ] + "created": mock.ANY, + }, + ], } ########################################################################### @@ -677,13 +665,8 @@ def test_error_1(self, client, db): db.add(token) # request target API - req_param = { - "processed": "invalid_value" - } - resp = client.get( - self.base_url.format(token_address), - params=req_param - ) + req_param = {"processed": "invalid_value"} + resp = client.get(self.base_url.format(token_address), params=req_param) assert resp.status_code == 422 assert resp.json() == { @@ -691,10 +674,8 @@ def test_error_1(self, client, db): { "loc": ["query", "processed"], "msg": "value could not be parsed to a boolean", - "type": "type_error.bool" + "type": "type_error.bool", } ], - "meta": { - "code": 1, "title": "RequestValidationError" - } + "meta": {"code": 1, "title": "RequestValidationError"}, } diff --git a/tests/test_app_routers_bond_tokens_{token_address}_additional_issue_batch_POST.py b/tests/test_app_routers_bond_tokens_{token_address}_additional_issue_batch_POST.py index 31058f8f..b6962bab 100644 --- a/tests/test_app_routers_bond_tokens_{token_address}_additional_issue_batch_POST.py +++ b/tests/test_app_routers_bond_tokens_{token_address}_additional_issue_batch_POST.py @@ -20,10 +20,11 @@ from app.model.db import ( Account, + BatchIssueRedeem, + BatchIssueRedeemProcessingCategory, + BatchIssueRedeemUpload, Token, TokenType, - BatchIssueRedeemUpload, - BatchIssueRedeem, BatchIssueRedeemProcessingCategory ) from app.utils.e2ee_utils import E2EEUtils from tests.account_config import config_eth_account @@ -64,23 +65,20 @@ def test_normal_1(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 10 - } - ] + req_param = [{"account_address": test_account_1, "amount": 10}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion - upload: Optional[BatchIssueRedeemUpload] = db.query(BatchIssueRedeemUpload).first() + upload: Optional[BatchIssueRedeemUpload] = db.query( + BatchIssueRedeemUpload + ).first() assert upload.issuer_address == issuer_address assert upload.token_type == TokenType.IBET_STRAIGHT_BOND.value assert upload.token_address == token_address @@ -128,26 +126,22 @@ def test_normal_2(self, client, db): # request target API req_param = [ - { - "account_address": test_account_1, - "amount": 10 - }, - { - "account_address": test_account_2, - "amount": 20 - } + {"account_address": test_account_1, "amount": 10}, + {"account_address": test_account_2, "amount": 20}, ] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion - upload: Optional[BatchIssueRedeemUpload] = db.query(BatchIssueRedeemUpload).first() + upload: Optional[BatchIssueRedeemUpload] = db.query( + BatchIssueRedeemUpload + ).first() assert upload.issuer_address == issuer_address assert upload.token_type == TokenType.IBET_STRAIGHT_BOND.value assert upload.token_address == token_address @@ -207,24 +201,21 @@ def test_error_1_1(self, client, db): json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['body'], - 'msg': 'value is not a valid list', - 'type': 'type_error.list' + "loc": ["body"], + "msg": "value is not a valid list", + "type": "type_error.list", } - ] + ], } # Error_1_2 @@ -252,35 +243,27 @@ def test_error_1_2(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": "0x0", - "amount": 10 - } - ] + req_param = [{"account_address": "0x0", "amount": 10}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['body', 0, 'account_address'], - 'msg': 'account_address is not a valid address', - 'type': 'value_error' + "loc": ["body", 0, "account_address"], + "msg": "account_address is not a valid address", + "type": "value_error", } - ] + ], } # Error_1_3_1 @@ -310,36 +293,28 @@ def test_error_1_3_1(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 0 - } - ] + req_param = [{"account_address": test_account_1, "amount": 0}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['body', 0, 'amount'], - 'msg': 'ensure this value is greater than or equal to 1', - 'type': 'value_error.number.not_ge', - 'ctx': {'limit_value': 1} + "loc": ["body", 0, "amount"], + "msg": "ensure this value is greater than or equal to 1", + "type": "value_error.number.not_ge", + "ctx": {"limit_value": 1}, } - ] + ], } # Error_1_3_2 @@ -369,36 +344,28 @@ def test_error_1_3_2(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 1_000_000_000_001 - } - ] + req_param = [{"account_address": test_account_1, "amount": 1_000_000_000_001}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['body', 0, 'amount'], - 'msg': 'ensure this value is less than or equal to 1000000000000', - 'type': 'value_error.number.not_le', - 'ctx': {'limit_value': 1000000000000} + "loc": ["body", 0, "amount"], + "msg": "ensure this value is less than or equal to 1000000000000", + "type": "value_error.number.not_le", + "ctx": {"limit_value": 1000000000000}, } - ] + ], } # Error_1_4 @@ -428,32 +395,22 @@ def test_error_1_4(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 10 - } - ] + req_param = [{"account_address": test_account_1, "amount": 10}] resp = client.post( - self.base_url.format(token_address), - json=req_param, - headers=None + self.base_url.format(token_address), json=req_param, headers=None ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['header', 'issuer-address'], - 'msg': 'field required', - 'type': 'value_error.missing' + "loc": ["header", "issuer-address"], + "msg": "field required", + "type": "value_error.missing", } - ] + ], } # Error_1_5 @@ -483,35 +440,24 @@ def test_error_1_5(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 10 - } - ] + req_param = [{"account_address": test_account_1, "amount": 10}] resp = client.post( self.base_url.format(token_address), json=req_param, - headers={ - "issuer-address": issuer_address, - "eoa-password": "password" - } + headers={"issuer-address": issuer_address, "eoa-password": "password"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['header', 'eoa-password'], - 'msg': 'eoa-password is not a Base64-encoded encrypted data', - 'type': 'value_error' + "loc": ["header", "eoa-password"], + "msg": "eoa-password is not a Base64-encoded encrypted data", + "type": "value_error", } - ] + ], } # Error_1_6 @@ -545,18 +491,15 @@ def test_error_1_6(self, client, db): json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'InvalidParameterError' - }, - 'detail': 'list length must be at least one' + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "list length must be at least one", } # Error_1_7_1 @@ -586,29 +529,21 @@ def test_error_1_7_1(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 10 - } - ] + req_param = [{"account_address": test_account_1, "amount": 10}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'AuthorizationError' - }, - 'detail': 'issuer does not exist, or password mismatch' + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # Error_1_7_2 @@ -638,29 +573,21 @@ def test_error_1_7_2(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 10 - } - ] + req_param = [{"account_address": test_account_1, "amount": 10}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'AuthorizationError' - }, - 'detail': 'issuer does not exist, or password mismatch' + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # Error_1_8_1 @@ -683,29 +610,21 @@ def test_error_1_8_1(self, client, db): db.add(account) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 10 - } - ] + req_param = [{"account_address": test_account_1, "amount": 10}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'NotFound' - }, - 'detail': 'token not found' + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # Error_1_8_2 @@ -737,27 +656,19 @@ def test_error_1_8_2(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 10 - } - ] + req_param = [{"account_address": test_account_1, "amount": 10}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'InvalidParameterError' - }, - 'detail': 'this token is temporarily unavailable' + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } diff --git a/tests/test_app_routers_bond_tokens_{token_address}_additional_issue_batch_{batch_id}_GET.py b/tests/test_app_routers_bond_tokens_{token_address}_additional_issue_batch_{batch_id}_GET.py index 08a70c0b..ca3ef3c4 100644 --- a/tests/test_app_routers_bond_tokens_{token_address}_additional_issue_batch_{batch_id}_GET.py +++ b/tests/test_app_routers_bond_tokens_{token_address}_additional_issue_batch_{batch_id}_GET.py @@ -16,16 +16,15 @@ SPDX-License-Identifier: Apache-2.0 """ -from app.utils.e2ee_utils import E2EEUtils - from app.model.db import ( - TokenType, Account, - Token, - BatchIssueRedeemUpload, + BatchIssueRedeem, BatchIssueRedeemProcessingCategory, - BatchIssueRedeem + BatchIssueRedeemUpload, + Token, + TokenType, ) +from app.utils.e2ee_utils import E2EEUtils from tests.account_config import config_eth_account @@ -39,13 +38,8 @@ class TestAppRoutersBondTokensTokenAddressAdditionalIssueBatchBatchIdGET: ] account_list = [ - { - "address": config_eth_account("user1")["address"], - "amount": 1 - }, { - "address": config_eth_account("user2")["address"], - "amount": 2 - } + {"address": config_eth_account("user1")["address"], "amount": 1}, + {"address": config_eth_account("user2")["address"], "amount": 2}, ] ########################################################################### @@ -95,22 +89,20 @@ def test_normal_1(self, client, db): # request target API resp = client.get( self.base_url.format(test_token_address, self.upload_id_list[0]), - headers={ - "issuer-address": issuer_address - } + headers={"issuer-address": issuer_address}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'processed': True, - 'results': [ + "processed": True, + "results": [ { - 'account_address': self.account_list[0]["address"], - 'amount': self.account_list[0]["amount"], - 'status': 1 + "account_address": self.account_list[0]["address"], + "amount": self.account_list[0]["amount"], + "status": 1, } - ] + ], } # Normal_2 @@ -163,27 +155,25 @@ def test_normal_2(self, client, db): # request target API resp = client.get( self.base_url.format(test_token_address, self.upload_id_list[0]), - headers={ - "issuer-address": issuer_address - } + headers={"issuer-address": issuer_address}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'processed': True, - 'results': [ + "processed": True, + "results": [ { - 'account_address': self.account_list[0]["address"], - 'amount': self.account_list[0]["amount"], - 'status': 1 + "account_address": self.account_list[0]["address"], + "amount": self.account_list[0]["amount"], + "status": 1, }, { - 'account_address': self.account_list[1]["address"], - 'amount': self.account_list[1]["amount"], - 'status': 1 - } - ] + "account_address": self.account_list[1]["address"], + "amount": self.account_list[1]["amount"], + "status": 1, + }, + ], } ######################################################################### @@ -226,17 +216,12 @@ def test_error_1(self, client, db): # request target API resp = client.get( self.base_url.format(test_token_address, self.upload_id_list[0]), - headers={ - "issuer-address": issuer_address - } + headers={"issuer-address": issuer_address}, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "batch not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "batch not found", } diff --git a/tests/test_app_routers_bond_tokens_{token_address}_holders_GET.py b/tests/test_app_routers_bond_tokens_{token_address}_holders_GET.py index 5d88a677..5ca132b3 100644 --- a/tests/test_app_routers_bond_tokens_{token_address}_holders_GET.py +++ b/tests/test_app_routers_bond_tokens_{token_address}_holders_GET.py @@ -18,11 +18,11 @@ """ from app.model.db import ( Account, + IDXLockedPosition, + IDXPersonalInfo, + IDXPosition, Token, TokenType, - IDXPosition, - IDXLockedPosition, - IDXPersonalInfo ) from tests.account_config import config_eth_account @@ -58,9 +58,7 @@ def test_normal_1(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion @@ -102,14 +100,18 @@ def test_normal_2(self, client, db): # prepare data: Locked Position _locked_position = IDXLockedPosition() _locked_position.token_address = _token_address - _locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + _locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) _locked_position.account_address = _account_address_1 _locked_position.value = 5 db.add(_locked_position) _locked_position = IDXLockedPosition() _locked_position.token_address = _token_address - _locked_position.lock_address = "0x1234567890123456789012345678900000000002" # lock address 2 + _locked_position.lock_address = ( + "0x1234567890123456789012345678900000000002" # lock address 2 + ) _locked_position.account_address = _account_address_1 _locked_position.value = 5 db.add(_locked_position) @@ -126,16 +128,14 @@ def test_normal_2(self, client, db): "email": "email_test1", "birth": "birth_test1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } db.add(idx_personal_info_1) # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion @@ -151,13 +151,13 @@ def test_normal_2(self, client, db): "email": "email_test1", "birth": "birth_test1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, }, "balance": 10, "exchange_balance": 11, "exchange_commitment": 12, "pending_transfer": 5, - "locked": 10 + "locked": 10, } ] @@ -195,14 +195,18 @@ def test_normal_3_1(self, client, db): idx_locked_position = IDXLockedPosition() idx_locked_position.token_address = _token_address - idx_locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + idx_locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) idx_locked_position.account_address = _account_address_1 idx_locked_position.value = 5 db.add(idx_locked_position) idx_locked_position = IDXLockedPosition() idx_locked_position.token_address = _token_address - idx_locked_position.lock_address = "0x1234567890123456789012345678900000000002" # lock address 2 + idx_locked_position.lock_address = ( + "0x1234567890123456789012345678900000000002" # lock address 2 + ) idx_locked_position.account_address = _account_address_1 idx_locked_position.value = 5 db.add(idx_locked_position) @@ -218,7 +222,7 @@ def test_normal_3_1(self, client, db): "email": "email_test1", "birth": "birth_test1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } db.add(idx_personal_info_1) @@ -234,14 +238,18 @@ def test_normal_3_1(self, client, db): idx_locked_position = IDXLockedPosition() idx_locked_position.token_address = _token_address - idx_locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + idx_locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) idx_locked_position.account_address = _account_address_2 idx_locked_position.value = 10 db.add(idx_locked_position) idx_locked_position = IDXLockedPosition() idx_locked_position.token_address = _token_address - idx_locked_position.lock_address = "0x1234567890123456789012345678900000000002" # lock address 2 + idx_locked_position.lock_address = ( + "0x1234567890123456789012345678900000000002" # lock address 2 + ) idx_locked_position.account_address = _account_address_2 idx_locked_position.value = 10 db.add(idx_locked_position) @@ -258,14 +266,18 @@ def test_normal_3_1(self, client, db): idx_locked_position = IDXLockedPosition() idx_locked_position.token_address = _token_address - idx_locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + idx_locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) idx_locked_position.account_address = _account_address_3 idx_locked_position.value = 15 db.add(idx_locked_position) idx_locked_position = IDXLockedPosition() idx_locked_position.token_address = _token_address - idx_locked_position.lock_address = "0x1234567890123456789012345678900000000002" # lock address 2 + idx_locked_position.lock_address = ( + "0x1234567890123456789012345678900000000002" # lock address 2 + ) idx_locked_position.account_address = _account_address_3 idx_locked_position.value = 15 db.add(idx_locked_position) @@ -287,9 +299,7 @@ def test_normal_3_1(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion @@ -305,13 +315,13 @@ def test_normal_3_1(self, client, db): "email": "email_test1", "birth": "birth_test1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, }, "balance": 10, "exchange_balance": 11, "exchange_commitment": 12, "pending_transfer": 5, - "locked": 10 + "locked": 10, }, { "account_address": _account_address_2, @@ -323,13 +333,13 @@ def test_normal_3_1(self, client, db): "email": None, "birth": None, "is_corporate": None, - "tax_category": None + "tax_category": None, }, "balance": 20, "exchange_balance": 21, "exchange_commitment": 22, "pending_transfer": 10, - "locked": 20 + "locked": 20, }, { "account_address": _account_address_3, @@ -341,14 +351,14 @@ def test_normal_3_1(self, client, db): "email": "email_test3", "birth": "birth_test3", "is_corporate": None, - "tax_category": None + "tax_category": None, }, "balance": 99, "exchange_balance": 99, "exchange_commitment": 99, "pending_transfer": 99, - "locked": 30 - } + "locked": 30, + }, ] # @@ -398,7 +408,9 @@ def test_normal_3_2(self, client, db): idx_locked_position = IDXLockedPosition() idx_locked_position.token_address = _token_address - idx_locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + idx_locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) idx_locked_position.account_address = _account_address_2 idx_locked_position.value = 0 db.add(idx_locked_position) @@ -416,7 +428,9 @@ def test_normal_3_2(self, client, db): idx_locked_position = IDXLockedPosition() idx_locked_position.token_address = _token_address - idx_locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + idx_locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) idx_locked_position.account_address = _account_address_3 idx_locked_position.value = 0 db.add(idx_locked_position) @@ -424,9 +438,7 @@ def test_normal_3_2(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion @@ -443,13 +455,13 @@ def test_normal_3_2(self, client, db): "email": None, "birth": None, "is_corporate": None, - "tax_category": None + "tax_category": None, }, "balance": 0, "exchange_balance": 0, "exchange_commitment": 12, "pending_transfer": 5, - "locked": 0 + "locked": 0, }, { "account_address": _account_address_2, @@ -461,14 +473,14 @@ def test_normal_3_2(self, client, db): "email": None, "birth": None, "is_corporate": None, - "tax_category": None + "tax_category": None, }, "balance": 20, "exchange_balance": 21, "exchange_commitment": 0, "pending_transfer": 0, - "locked": 0 - } + "locked": 0, + }, ] # @@ -515,7 +527,7 @@ def test_normal_3_3(self, client, db): "email": "email_test1", "birth": "birth_test1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } db.add(idx_personal_info_1) @@ -554,12 +566,8 @@ def test_normal_3_3(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - }, - params={ - "include_former_holder": "true" - } + headers={"issuer-address": _issuer_address}, + params={"include_former_holder": "true"}, ) # assertion @@ -576,13 +584,13 @@ def test_normal_3_3(self, client, db): "email": "email_test1", "birth": "birth_test1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, }, "balance": 0, "exchange_balance": 0, "exchange_commitment": 12, "pending_transfer": 5, - "locked": 0 + "locked": 0, }, { "account_address": _account_address_2, @@ -594,13 +602,13 @@ def test_normal_3_3(self, client, db): "email": None, "birth": None, "is_corporate": None, - "tax_category": None + "tax_category": None, }, "balance": 20, "exchange_balance": 21, "exchange_commitment": 0, "pending_transfer": 0, - "locked": 0 + "locked": 0, }, { "account_address": _account_address_3, @@ -612,14 +620,14 @@ def test_normal_3_3(self, client, db): "email": "email_test3", "birth": "birth_test3", "is_corporate": None, - "tax_category": None + "tax_category": None, }, "balance": 0, "exchange_balance": 0, "exchange_commitment": 0, "pending_transfer": 0, - "locked": 0 - } + "locked": 0, + }, ] ########################################################################### @@ -633,24 +641,20 @@ def test_error_1(self, client, db): # request target API resp = client.get( - self.base_url.format(_token_address), - headers={ - "issuer-address": "0x0" - } + self.base_url.format(_token_address), headers={"issuer-address": "0x0"} ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, - "detail": [{ - "loc": ["header", "issuer-address"], - "msg": "issuer-address is not a valid address", - "type": "value_error" - }] + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ + { + "loc": ["header", "issuer-address"], + "msg": "issuer-address is not a valid address", + "type": "value_error", + } + ], } # @@ -663,19 +667,14 @@ def test_error_2(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "issuer does not exist" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "issuer does not exist", } # @@ -693,19 +692,14 @@ def test_error_3(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # @@ -732,17 +726,12 @@ def test_error_4(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } diff --git a/tests/test_app_routers_bond_tokens_{token_address}_holders_count_GET.py b/tests/test_app_routers_bond_tokens_{token_address}_holders_count_GET.py index 4deacb94..8cfc6815 100644 --- a/tests/test_app_routers_bond_tokens_{token_address}_holders_count_GET.py +++ b/tests/test_app_routers_bond_tokens_{token_address}_holders_count_GET.py @@ -16,13 +16,7 @@ SPDX-License-Identifier: Apache-2.0 """ -from app.model.db import ( - Account, - Token, - TokenType, - IDXPosition, - IDXLockedPosition -) +from app.model.db import Account, IDXLockedPosition, IDXPosition, Token, TokenType from tests.account_config import config_eth_account @@ -58,14 +52,12 @@ def test_normal_1_1(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 200 - assert resp.json() == {'count': 0} + assert resp.json() == {"count": 0} # # position is not None @@ -101,14 +93,12 @@ def test_normal_1_2(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 200 - assert resp.json() == {'count': 1} + assert resp.json() == {"count": 1} # # position is not None @@ -143,14 +133,18 @@ def test_normal_1_3(self, client, db): idx_locked_position = IDXLockedPosition() idx_locked_position.token_address = _token_address - idx_locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + idx_locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) idx_locked_position.account_address = _account_address_1 idx_locked_position.value = 5 db.add(idx_locked_position) idx_locked_position = IDXLockedPosition() idx_locked_position.token_address = _token_address - idx_locked_position.lock_address = "0x1234567890123456789012345678900000000002" # lock address 2 + idx_locked_position.lock_address = ( + "0x1234567890123456789012345678900000000002" # lock address 2 + ) idx_locked_position.account_address = _account_address_1 idx_locked_position.value = 5 db.add(idx_locked_position) @@ -158,14 +152,12 @@ def test_normal_1_3(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 200 - assert resp.json() == {'count': 1} + assert resp.json() == {"count": 1} # # position is not None (but zero) @@ -200,7 +192,9 @@ def test_normal_1_4(self, client, db): idx_locked_position = IDXLockedPosition() idx_locked_position.token_address = _token_address - idx_locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + idx_locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) idx_locked_position.account_address = _account_address_1 idx_locked_position.value = 0 db.add(idx_locked_position) @@ -208,14 +202,12 @@ def test_normal_1_4(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 200 - assert resp.json() == {'count': 0} + assert resp.json() == {"count": 0} # # Multiple records @@ -251,7 +243,9 @@ def test_normal_2(self, client, db): idx_locked_position = IDXLockedPosition() idx_locked_position.token_address = _token_address - idx_locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + idx_locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) idx_locked_position.account_address = _account_address_1 idx_locked_position.value = 5 db.add(idx_locked_position) @@ -267,7 +261,9 @@ def test_normal_2(self, client, db): idx_locked_position = IDXLockedPosition() idx_locked_position.token_address = _token_address - idx_locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + idx_locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) idx_locked_position.account_address = _account_address_2 idx_locked_position.value = 5 db.add(idx_locked_position) @@ -283,7 +279,9 @@ def test_normal_2(self, client, db): idx_locked_position = IDXLockedPosition() idx_locked_position.token_address = _token_address - idx_locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + idx_locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) idx_locked_position.account_address = _account_address_3 idx_locked_position.value = 5 db.add(idx_locked_position) @@ -291,14 +289,12 @@ def test_normal_2(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 200 - assert resp.json() == {'count': 3} + assert resp.json() == {"count": 3} ########################################################################### # Error Case @@ -312,24 +308,20 @@ def test_error_1(self, client, db): # request target API resp = client.get( - self.base_url.format(_token_address), - headers={ - "issuer-address": "0x0" - } + self.base_url.format(_token_address), headers={"issuer-address": "0x0"} ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, - "detail": [{ - "loc": ["header", "issuer-address"], - "msg": "issuer-address is not a valid address", - "type": "value_error" - }] + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ + { + "loc": ["header", "issuer-address"], + "msg": "issuer-address is not a valid address", + "type": "value_error", + } + ], } # @@ -343,19 +335,14 @@ def test_error_2(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "issuer does not exist" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "issuer does not exist", } # @@ -374,19 +361,14 @@ def test_error_3(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # @@ -414,17 +396,12 @@ def test_error_4(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } diff --git a/tests/test_app_routers_bond_tokens_{token_address}_holders_{account_address}_GET.py b/tests/test_app_routers_bond_tokens_{token_address}_holders_{account_address}_GET.py index 1bf76816..ac405912 100644 --- a/tests/test_app_routers_bond_tokens_{token_address}_holders_{account_address}_GET.py +++ b/tests/test_app_routers_bond_tokens_{token_address}_holders_{account_address}_GET.py @@ -18,11 +18,11 @@ """ from app.model.db import ( Account, + IDXLockedPosition, + IDXPersonalInfo, + IDXPosition, Token, TokenType, - IDXPosition, - IDXLockedPosition, - IDXPersonalInfo ) from tests.account_config import config_eth_account @@ -70,16 +70,14 @@ def test_normal_1_1(self, client, db): "email": "email_test1", "birth": "birth_test1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } db.add(idx_personal_info_1) # request target API resp = client.get( self.base_url.format(_token_address, _account_address_1), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion @@ -94,13 +92,13 @@ def test_normal_1_1(self, client, db): "email": "email_test1", "birth": "birth_test1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, }, "balance": 0, "exchange_balance": 0, "exchange_commitment": 0, "pending_transfer": 0, - "locked": 0 + "locked": 0, } # @@ -148,16 +146,14 @@ def test_normal_1_2(self, client, db): "email": "email_test1", "birth": "birth_test1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } db.add(idx_personal_info_1) # request target API resp = client.get( self.base_url.format(_token_address, _account_address_1), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion @@ -172,13 +168,13 @@ def test_normal_1_2(self, client, db): "email": "email_test1", "birth": "birth_test1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, }, "balance": 10, "exchange_balance": 11, "exchange_commitment": 12, "pending_transfer": 5, - "locked": 0 + "locked": 0, } # @@ -217,14 +213,18 @@ def test_normal_1_3(self, client, db): # prepare data: Locked Position _locked_position = IDXLockedPosition() _locked_position.token_address = _token_address - _locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + _locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) _locked_position.account_address = _account_address_1 _locked_position.value = 5 db.add(_locked_position) _locked_position = IDXLockedPosition() _locked_position.token_address = _token_address - _locked_position.lock_address = "0x1234567890123456789012345678900000000002" # lock address 2 + _locked_position.lock_address = ( + "0x1234567890123456789012345678900000000002" # lock address 2 + ) _locked_position.account_address = _account_address_1 _locked_position.value = 5 db.add(_locked_position) @@ -241,16 +241,14 @@ def test_normal_1_3(self, client, db): "email": "email_test1", "birth": "birth_test1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } db.add(idx_personal_info_1) # request target API resp = client.get( self.base_url.format(_token_address, _account_address_1), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion @@ -265,13 +263,13 @@ def test_normal_1_3(self, client, db): "email": "email_test1", "birth": "birth_test1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, }, "balance": 10, "exchange_balance": 11, "exchange_commitment": 12, "pending_transfer": 5, - "locked": 10 + "locked": 10, } # @@ -307,9 +305,7 @@ def test_normal_2_1(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address, _account_address_1), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion @@ -324,13 +320,13 @@ def test_normal_2_1(self, client, db): "email": None, "birth": None, "is_corporate": None, - "tax_category": None + "tax_category": None, }, "balance": 10, "exchange_balance": 11, "exchange_commitment": 12, "pending_transfer": 5, - "locked": 0 + "locked": 0, } # @@ -380,9 +376,7 @@ def test_normal_2_2(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address, _account_address_1), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion @@ -397,13 +391,13 @@ def test_normal_2_2(self, client, db): "email": "email_test1", "birth": "birth_test1", "is_corporate": None, - "tax_category": None + "tax_category": None, }, "balance": 10, "exchange_balance": 11, "exchange_commitment": 12, "pending_transfer": 5, - "locked": 0 + "locked": 0, } ########################################################################### @@ -419,23 +413,20 @@ def test_error_1(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address, _account_address_1), - headers={ - "issuer-address": "0x0" - } + headers={"issuer-address": "0x0"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, - "detail": [{ - "loc": ["header", "issuer-address"], - "msg": "issuer-address is not a valid address", - "type": "value_error" - }] + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ + { + "loc": ["header", "issuer-address"], + "msg": "issuer-address is not a valid address", + "type": "value_error", + } + ], } # @@ -449,19 +440,14 @@ def test_error_2(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address, _account_address_1), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "issuer does not exist" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "issuer does not exist", } # @@ -480,19 +466,14 @@ def test_error_3(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address, _account_address_1), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # @@ -520,17 +501,12 @@ def test_error_4(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address, _account_address_1), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } diff --git a/tests/test_app_routers_bond_tokens_{token_address}_personal_info_POST.py b/tests/test_app_routers_bond_tokens_{token_address}_personal_info_POST.py index a9c9448c..81e06a0f 100644 --- a/tests/test_app_routers_bond_tokens_{token_address}_personal_info_POST.py +++ b/tests/test_app_routers_bond_tokens_{token_address}_personal_info_POST.py @@ -19,18 +19,10 @@ import hashlib from unittest.mock import patch -from app.model.db import ( - Account, - AuthToken, - Token, - TokenType -) -from app.utils.e2ee_utils import E2EEUtils -from app.model.blockchain import ( - IbetStraightBondContract, - PersonalInfoContract -) from app.exceptions import SendTransactionError +from app.model.blockchain import IbetStraightBondContract, PersonalInfoContract +from app.model.db import Account, AuthToken, Token, TokenType +from app.utils.e2ee_utils import E2EEUtils from tests.account_config import config_eth_account @@ -70,21 +62,25 @@ def test_normal_1(self, client, db): # mock ibet_bond_contract = IbetStraightBondContract() - ibet_bond_contract.personal_info_contract_address = "personal_info_contract_address" + ibet_bond_contract.personal_info_contract_address = ( + "personal_info_contract_address" + ) IbetStraightBondContract_get = patch( target="app.model.blockchain.token.IbetStraightBondContract.get", - return_value=ibet_bond_contract + return_value=ibet_bond_contract, ) PersonalInfoContract_init = patch( target="app.model.blockchain.personal_info.PersonalInfoContract.__init__", - return_value=None + return_value=None, ) PersonalInfoContract_register_info = patch( target="app.model.blockchain.personal_info.PersonalInfoContract.register_info", - return_value=None + return_value=None, ) - with IbetStraightBondContract_get, PersonalInfoContract_init, PersonalInfoContract_register_info: + with ( + IbetStraightBondContract_get + ), PersonalInfoContract_init, PersonalInfoContract_register_info: # request target API req_param = { "account_address": _test_account_address, @@ -95,15 +91,15 @@ def test_normal_1(self, client, db): "email": "test_email", "birth": "test_birth", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } resp = client.post( self.test_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion @@ -112,12 +108,12 @@ def test_normal_1(self, client, db): PersonalInfoContract.__init__.assert_called_with( db=db, issuer_address=_issuer_address, - contract_address="personal_info_contract_address" + contract_address="personal_info_contract_address", ) PersonalInfoContract.register_info.assert_called_with( account_address=_test_account_address, data=req_param, - default_value=None + default_value=None, ) # @@ -149,21 +145,25 @@ def test_normal_2(self, client, db): # mock ibet_bond_contract = IbetStraightBondContract() - ibet_bond_contract.personal_info_contract_address = "personal_info_contract_address" + ibet_bond_contract.personal_info_contract_address = ( + "personal_info_contract_address" + ) IbetStraightBondContract_get = patch( target="app.model.blockchain.token.IbetStraightBondContract.get", - return_value=ibet_bond_contract + return_value=ibet_bond_contract, ) PersonalInfoContract_init = patch( target="app.model.blockchain.personal_info.PersonalInfoContract.__init__", - return_value=None + return_value=None, ) PersonalInfoContract_register_info = patch( target="app.model.blockchain.personal_info.PersonalInfoContract.register_info", - return_value=None + return_value=None, ) - with IbetStraightBondContract_get, PersonalInfoContract_init, PersonalInfoContract_register_info: + with ( + IbetStraightBondContract_get + ), PersonalInfoContract_init, PersonalInfoContract_register_info: # request target API req_param = { "account_address": _test_account_address, @@ -174,15 +174,15 @@ def test_normal_2(self, client, db): "email": None, "birth": None, "is_corporate": None, - "tax_category": None + "tax_category": None, } resp = client.post( self.test_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion @@ -191,12 +191,12 @@ def test_normal_2(self, client, db): PersonalInfoContract.__init__.assert_called_with( db=db, issuer_address=_issuer_address, - contract_address="personal_info_contract_address" + contract_address="personal_info_contract_address", ) PersonalInfoContract.register_info.assert_called_with( account_address=_test_account_address, data=req_param, - default_value=None + default_value=None, ) # @@ -234,21 +234,25 @@ def test_normal_3(self, client, db): # mock ibet_bond_contract = IbetStraightBondContract() - ibet_bond_contract.personal_info_contract_address = "personal_info_contract_address" + ibet_bond_contract.personal_info_contract_address = ( + "personal_info_contract_address" + ) IbetStraightBondContract_get = patch( target="app.model.blockchain.token.IbetStraightBondContract.get", - return_value=ibet_bond_contract + return_value=ibet_bond_contract, ) PersonalInfoContract_init = patch( target="app.model.blockchain.personal_info.PersonalInfoContract.__init__", - return_value=None + return_value=None, ) PersonalInfoContract_register_info = patch( target="app.model.blockchain.personal_info.PersonalInfoContract.register_info", - return_value=None + return_value=None, ) - with IbetStraightBondContract_get, PersonalInfoContract_init, PersonalInfoContract_register_info: + with ( + IbetStraightBondContract_get + ), PersonalInfoContract_init, PersonalInfoContract_register_info: # request target API req_param = { "account_address": _test_account_address, @@ -259,15 +263,15 @@ def test_normal_3(self, client, db): "email": "test_email", "birth": "test_birth", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } resp = client.post( self.test_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "auth-token": "test_auth_token" - } + "auth-token": "test_auth_token", + }, ) # assertion @@ -276,12 +280,12 @@ def test_normal_3(self, client, db): PersonalInfoContract.__init__.assert_called_with( db=db, issuer_address=_issuer_address, - contract_address="personal_info_contract_address" + contract_address="personal_info_contract_address", ) PersonalInfoContract.register_info.assert_called_with( account_address=_test_account_address, data=req_param, - default_value=None + default_value=None, ) ########################################################################### @@ -302,28 +306,24 @@ def test_error_1_1(self, client, db): _token_address = "0xd9F55747DE740297ff1eEe537aBE0f8d73B7D783" # request target API - resp = client.post( - self.test_url.format(_token_address) - ) + resp = client.post(self.test_url.format(_token_address)) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "field required", - "type": "value_error.missing" - }, { + "type": "value_error.missing", + }, + { "loc": ["body"], "msg": "field required", - "type": "value_error.missing" - } - ] + "type": "value_error.missing", + }, + ], } # @@ -349,35 +349,33 @@ def test_error_1_2(self, client, db): "email": None, "birth": None, "is_corporate": None, - "tax_category": None + "tax_category": None, } resp = client.post( self.test_url.format(_token_address, _test_account_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "account_address"], "msg": "none is not an allowed value", - "type": "type_error.none.not_allowed" - }, { + "type": "type_error.none.not_allowed", + }, + { "loc": ["body", "key_manager"], "msg": "none is not an allowed value", - "type": "type_error.none.not_allowed" - } - ] + "type": "type_error.none.not_allowed", + }, + ], } # @@ -403,34 +401,28 @@ def test_error_1_3(self, client, db): "email": "test_email", "birth": "test_birth", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } resp = client.post( self.test_url.format(_token_address, _test_account_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "loc": [ - "body", - "account_address" - ], + "loc": ["body", "account_address"], "msg": "account_address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -452,31 +444,28 @@ def test_error_1_4(self, client, db): "email": "test_email", "birth": "test_birth", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } resp = client.post( self.test_url.format(_token_address), json=req_param, headers={ "issuer-address": "test_issuer_address", - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -502,31 +491,28 @@ def test_error_1_5(self, client, db): "email": "test_email", "birth": "test_birth", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } resp = client.post( self.test_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": "not_encrypted_password" - } + "eoa-password": "not_encrypted_password", + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "eoa-password"], "msg": "eoa-password is not a Base64-encoded encrypted data", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -552,25 +538,22 @@ def test_error_2_1(self, client, db): "email": "test_email", "birth": "test_birth", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } resp = client.post( self.test_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -603,25 +586,22 @@ def test_error_2_2(self, client, db): "email": "test_email", "birth": "test_birth", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } resp = client.post( self.test_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("mismatch_password") - } + "eoa-password": E2EEUtils.encrypt("mismatch_password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -654,25 +634,22 @@ def test_error_3(self, client, db): "email": "test_email", "birth": "test_birth", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } resp = client.post( self.test_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # @@ -714,25 +691,22 @@ def test_error_4(self, client, db): "email": "test_email", "birth": "test_birth", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } resp = client.post( self.test_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } # @@ -764,21 +738,25 @@ def test_error_5(self, client, db): # mock ibet_bond_contract = IbetStraightBondContract() - ibet_bond_contract.personal_info_contract_address = "personal_info_contract_address" + ibet_bond_contract.personal_info_contract_address = ( + "personal_info_contract_address" + ) IbetStraightBondContract_get = patch( target="app.model.blockchain.token.IbetStraightBondContract.get", - return_value=ibet_bond_contract + return_value=ibet_bond_contract, ) PersonalInfoContract_init = patch( target="app.model.blockchain.personal_info.PersonalInfoContract.__init__", - return_value=None + return_value=None, ) PersonalInfoContract_register_info = patch( target="app.model.blockchain.personal_info.PersonalInfoContract.register_info", - side_effect=SendTransactionError() + side_effect=SendTransactionError(), ) - with IbetStraightBondContract_get, PersonalInfoContract_init, PersonalInfoContract_register_info: + with ( + IbetStraightBondContract_get + ), PersonalInfoContract_init, PersonalInfoContract_register_info: # request target API req_param = { "account_address": _test_account_address, @@ -789,23 +767,20 @@ def test_error_5(self, client, db): "email": "test_email", "birth": "test_birth", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } resp = client.post( self.test_url.format(_token_address, _test_account_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 2, - "title": "SendTransactionError" - }, - "detail": "failed to register personal information" + "meta": {"code": 2, "title": "SendTransactionError"}, + "detail": "failed to register personal information", } diff --git a/tests/test_app_routers_bond_tokens_{token_address}_personal_info_batch_GET.py b/tests/test_app_routers_bond_tokens_{token_address}_personal_info_batch_GET.py index 406f1abc..16f3a55d 100644 --- a/tests/test_app_routers_bond_tokens_{token_address}_personal_info_batch_GET.py +++ b/tests/test_app_routers_bond_tokens_{token_address}_personal_info_batch_GET.py @@ -19,10 +19,10 @@ from unittest import mock from app.model.db import ( - TokenType, - Token, BatchRegisterPersonalInfoUpload, - BatchRegisterPersonalInfoUploadStatus + BatchRegisterPersonalInfoUploadStatus, + Token, + TokenType, ) from tests.account_config import config_eth_account @@ -37,7 +37,7 @@ class TestAppRoutersBondTokensTokenAddressPersonalInfoBatchGET: "0f33d48f-9e6e-4a36-a55e-5bbcbda69c80", "1c961f7d-e1ad-40e5-988b-cca3d6009643", "1e778f46-864e-4ec0-b566-21bd31cf63ff", - "1f33d48f-9e6e-4a36-a55e-5bbcbda69c80" + "1f33d48f-9e6e-4a36-a55e-5bbcbda69c80", ] ########################################################################### @@ -64,21 +64,14 @@ def test_normal_1(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address, self.upload_id_list[0]), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 0, - 'offset': None, - 'limit': None, - 'total': 0 - }, - 'uploads': [] + "result_set": {"count": 0, "offset": None, "limit": None, "total": 0}, + "uploads": [], } # Normal_2 @@ -108,37 +101,33 @@ def test_normal_2(self, client, db): batch_register_upload = BatchRegisterPersonalInfoUpload() batch_register_upload.issuer_address = _issuer_address batch_register_upload.upload_id = self.upload_id_list[1] - batch_register_upload.status = BatchRegisterPersonalInfoUploadStatus.PENDING.value + batch_register_upload.status = ( + BatchRegisterPersonalInfoUploadStatus.PENDING.value + ) db.add(batch_register_upload) # request target API resp = client.get( self.base_url.format(_token_address, self.upload_id_list[0]), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 2, - 'offset': None, - 'limit': None, - 'total': 2 - }, - 'uploads': [ + "result_set": {"count": 2, "offset": None, "limit": None, "total": 2}, + "uploads": [ { - 'batch_id': self.upload_id_list[1], - 'status': BatchRegisterPersonalInfoUploadStatus.PENDING.value, - 'created': mock.ANY - }, { - 'batch_id': self.upload_id_list[0], - 'status': BatchRegisterPersonalInfoUploadStatus.DONE.value, - 'created': mock.ANY - } - ] + "batch_id": self.upload_id_list[1], + "status": BatchRegisterPersonalInfoUploadStatus.PENDING.value, + "created": mock.ANY, + }, + { + "batch_id": self.upload_id_list[0], + "status": BatchRegisterPersonalInfoUploadStatus.DONE.value, + "created": mock.ANY, + }, + ], } # Normal_3 @@ -168,36 +157,29 @@ def test_normal_3(self, client, db): batch_register_upload = BatchRegisterPersonalInfoUpload() batch_register_upload.issuer_address = _issuer_address batch_register_upload.upload_id = self.upload_id_list[1] - batch_register_upload.status = BatchRegisterPersonalInfoUploadStatus.PENDING.value + batch_register_upload.status = ( + BatchRegisterPersonalInfoUploadStatus.PENDING.value + ) db.add(batch_register_upload) # request target API resp = client.get( self.base_url.format(_token_address, self.upload_id_list[0]), - headers={ - "issuer-address": _issuer_address - }, - params={ - "status": BatchRegisterPersonalInfoUploadStatus.DONE.value - } + headers={"issuer-address": _issuer_address}, + params={"status": BatchRegisterPersonalInfoUploadStatus.DONE.value}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 1, - 'offset': None, - 'limit': None, - 'total': 2 - }, - 'uploads': [ + "result_set": {"count": 1, "offset": None, "limit": None, "total": 2}, + "uploads": [ { - 'batch_id': self.upload_id_list[0], - 'status': BatchRegisterPersonalInfoUploadStatus.DONE.value, - 'created': mock.ANY + "batch_id": self.upload_id_list[0], + "status": BatchRegisterPersonalInfoUploadStatus.DONE.value, + "created": mock.ANY, } - ] + ], } # Normal_4 @@ -227,37 +209,29 @@ def test_normal_4(self, client, db): batch_register_upload = BatchRegisterPersonalInfoUpload() batch_register_upload.issuer_address = _issuer_address batch_register_upload.upload_id = self.upload_id_list[1] - batch_register_upload.status = BatchRegisterPersonalInfoUploadStatus.PENDING.value + batch_register_upload.status = ( + BatchRegisterPersonalInfoUploadStatus.PENDING.value + ) db.add(batch_register_upload) # request target API resp = client.get( self.base_url.format(_token_address, self.upload_id_list[0]), - headers={ - "issuer-address": _issuer_address - }, - params={ - "offset": 0, - "limit": 1 - } + headers={"issuer-address": _issuer_address}, + params={"offset": 0, "limit": 1}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 2, - 'offset': 0, - 'limit': 1, - 'total': 2 - }, - 'uploads': [ + "result_set": {"count": 2, "offset": 0, "limit": 1, "total": 2}, + "uploads": [ { - 'batch_id': self.upload_id_list[1], - 'status': BatchRegisterPersonalInfoUploadStatus.PENDING.value, - 'created': mock.ANY + "batch_id": self.upload_id_list[1], + "status": BatchRegisterPersonalInfoUploadStatus.PENDING.value, + "created": mock.ANY, } - ] + ], } # Normal_5 @@ -287,41 +261,34 @@ def test_normal_5(self, client, db): batch_register_upload = BatchRegisterPersonalInfoUpload() batch_register_upload.issuer_address = _issuer_address batch_register_upload.upload_id = self.upload_id_list[1] - batch_register_upload.status = BatchRegisterPersonalInfoUploadStatus.PENDING.value + batch_register_upload.status = ( + BatchRegisterPersonalInfoUploadStatus.PENDING.value + ) db.add(batch_register_upload) # request target API resp = client.get( self.base_url.format(_token_address, self.upload_id_list[0]), - headers={ - "issuer-address": _issuer_address - }, - params={ - "sort_order": 0 - } + headers={"issuer-address": _issuer_address}, + params={"sort_order": 0}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 2, - 'offset': None, - 'limit': None, - 'total': 2 - }, - 'uploads': [ + "result_set": {"count": 2, "offset": None, "limit": None, "total": 2}, + "uploads": [ { - 'batch_id': self.upload_id_list[0], - 'status': BatchRegisterPersonalInfoUploadStatus.DONE.value, - 'created': mock.ANY + "batch_id": self.upload_id_list[0], + "status": BatchRegisterPersonalInfoUploadStatus.DONE.value, + "created": mock.ANY, }, { - 'batch_id': self.upload_id_list[1], - 'status': BatchRegisterPersonalInfoUploadStatus.PENDING.value, - 'created': mock.ANY - } - ] + "batch_id": self.upload_id_list[1], + "status": BatchRegisterPersonalInfoUploadStatus.PENDING.value, + "created": mock.ANY, + }, + ], } ######################################################################### @@ -347,24 +314,20 @@ def test_error_1(self, client, db): # request target API resp = client.get( - self.base_url.format(_token_address, self.upload_id_list[0]), - headers={} + self.base_url.format(_token_address, self.upload_id_list[0]), headers={} ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['header', 'issuer-address'], - 'msg': 'field required', - 'type': 'value_error.missing' + "loc": ["header", "issuer-address"], + "msg": "field required", + "type": "value_error.missing", } - ] + ], } # Error_2 @@ -398,17 +361,12 @@ def test_error_2(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address, self.upload_id_list[0]), - headers={ - "issuer-address": _issuer_address_1 - } + headers={"issuer-address": _issuer_address_1}, ) # assertion assert resp.status_code == 404 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'NotFound' - }, - 'detail': 'token not found' + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } diff --git a/tests/test_app_routers_bond_tokens_{token_address}_personal_info_batch_POST.py b/tests/test_app_routers_bond_tokens_{token_address}_personal_info_batch_POST.py index 619592d8..4d2ead53 100644 --- a/tests/test_app_routers_bond_tokens_{token_address}_personal_info_batch_POST.py +++ b/tests/test_app_routers_bond_tokens_{token_address}_personal_info_batch_POST.py @@ -23,11 +23,11 @@ from app.model.db import ( Account, AuthToken, - Token, - TokenType, BatchRegisterPersonalInfo, BatchRegisterPersonalInfoUpload, - BatchRegisterPersonalInfoUploadStatus + BatchRegisterPersonalInfoUploadStatus, + Token, + TokenType, ) from app.utils.e2ee_utils import E2EEUtils from tests.account_config import config_eth_account @@ -77,7 +77,7 @@ def test_normal_1(self, client, db): "email": "test_email", "birth": "test_birth", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } # request target API req_param = [personal_info for _ in range(0, 10)] @@ -86,8 +86,8 @@ def test_normal_1(self, client, db): json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion @@ -95,14 +95,18 @@ def test_normal_1(self, client, db): assert resp.json() == { "batch_id": ANY, "status": BatchRegisterPersonalInfoUploadStatus.PENDING.value, - "created": ANY + "created": ANY, } - _upload: Optional[BatchRegisterPersonalInfoUpload] = db.query(BatchRegisterPersonalInfoUpload).first() + _upload: Optional[BatchRegisterPersonalInfoUpload] = db.query( + BatchRegisterPersonalInfoUpload + ).first() assert _upload.status == BatchRegisterPersonalInfoUploadStatus.PENDING.value assert _upload.issuer_address == _issuer_address - _register_list: list[BatchRegisterPersonalInfo] = db.query(BatchRegisterPersonalInfo).all() + _register_list: list[BatchRegisterPersonalInfo] = db.query( + BatchRegisterPersonalInfo + ).all() assert len(_register_list) == 10 # @@ -147,7 +151,7 @@ def test_normal_2(self, client, db): "email": "test_email", "birth": "test_birth", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } # request target API req_param = [personal_info for _ in range(0, 10)] @@ -156,8 +160,8 @@ def test_normal_2(self, client, db): json=req_param, headers={ "issuer-address": _issuer_address, - "auth-token": "test_auth_token" - } + "auth-token": "test_auth_token", + }, ) # assertion @@ -165,14 +169,18 @@ def test_normal_2(self, client, db): assert resp.json() == { "batch_id": ANY, "status": BatchRegisterPersonalInfoUploadStatus.PENDING.value, - "created": ANY + "created": ANY, } - _upload: Optional[BatchRegisterPersonalInfoUpload] = db.query(BatchRegisterPersonalInfoUpload).first() + _upload: Optional[BatchRegisterPersonalInfoUpload] = db.query( + BatchRegisterPersonalInfoUpload + ).first() assert _upload.status == BatchRegisterPersonalInfoUploadStatus.PENDING.value assert _upload.issuer_address == _issuer_address - _register_list: list[BatchRegisterPersonalInfo] = db.query(BatchRegisterPersonalInfo).all() + _register_list: list[BatchRegisterPersonalInfo] = db.query( + BatchRegisterPersonalInfo + ).all() assert len(_register_list) == 10 ########################################################################### @@ -193,28 +201,24 @@ def test_error_1_1(self, client, db): _token_address = "0xd9F55747DE740297ff1eEe537aBE0f8d73B7D783" # request target API - resp = client.post( - self.test_url.format(_token_address) - ) + resp = client.post(self.test_url.format(_token_address)) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "field required", - "type": "value_error.missing" - }, { + "type": "value_error.missing", + }, + { "loc": ["body"], "msg": "field required", - "type": "value_error.missing" - } - ] + "type": "value_error.missing", + }, + ], } # @@ -239,7 +243,7 @@ def test_error_1_2(self, client, db): "email": None, "birth": None, "is_corporate": None, - "tax_category": None + "tax_category": None, } # request target API req_param = [personal_info for _ in range(0, 10)] @@ -248,8 +252,8 @@ def test_error_1_2(self, client, db): json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) details = [] @@ -258,21 +262,21 @@ def test_error_1_2(self, client, db): { "loc": ["body", i, "account_address"], "msg": "none is not an allowed value", - "type": "type_error.none.not_allowed" - }) - details.append({ + "type": "type_error.none.not_allowed", + } + ) + details.append( + { "loc": ["body", i, "key_manager"], "msg": "none is not an allowed value", - "type": "type_error.none.not_allowed" - }) + "type": "type_error.none.not_allowed", + } + ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, - "detail": details + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": details, } # @@ -297,7 +301,7 @@ def test_error_1_3(self, client, db): "email": "test_email", "birth": "test_birth", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } # request target API req_param = [personal_info for _ in range(0, 10)] @@ -306,29 +310,22 @@ def test_error_1_3(self, client, db): json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "loc": [ - "body", - i, - "account_address" - ], + "loc": ["body", i, "account_address"], "msg": "account_address is not a valid address", - "type": "value_error" + "type": "value_error", } for i in range(0, 10) - ] + ], } # @@ -341,40 +338,39 @@ def test_error_1_4(self, client, db): _token_address = "0xd9F55747DE740297ff1eEe537aBE0f8d73B7D783" # request target API - req_param = [{ - "account_address": _test_account_address, - "key_manager": "test_key_manager", - "name": "test_name", - "postal_code": "test_postal_code", - "address": "test_address", - "email": "test_email", - "birth": "test_birth", - "is_corporate": False, - "tax_category": 10 - }] + req_param = [ + { + "account_address": _test_account_address, + "key_manager": "test_key_manager", + "name": "test_name", + "postal_code": "test_postal_code", + "address": "test_address", + "email": "test_email", + "birth": "test_birth", + "is_corporate": False, + "tax_category": 10, + } + ] resp = client.post( self.test_url.format(_token_address), json=req_param, headers={ "issuer-address": "test_issuer_address", - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -391,40 +387,39 @@ def test_error_1_5(self, client, db): _token_address = "0xd9F55747DE740297ff1eEe537aBE0f8d73B7D783" # request target API - req_param = [{ - "account_address": _test_account_address, - "key_manager": "test_key_manager", - "name": "test_name", - "postal_code": "test_postal_code", - "address": "test_address", - "email": "test_email", - "birth": "test_birth", - "is_corporate": False, - "tax_category": 10 - }] + req_param = [ + { + "account_address": _test_account_address, + "key_manager": "test_key_manager", + "name": "test_name", + "postal_code": "test_postal_code", + "address": "test_address", + "email": "test_email", + "birth": "test_birth", + "is_corporate": False, + "tax_category": 10, + } + ] resp = client.post( self.test_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": "not_encrypted_password" - } + "eoa-password": "not_encrypted_password", + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "eoa-password"], "msg": "eoa-password is not a Base64-encoded encrypted data", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -441,34 +436,33 @@ def test_error_2_1(self, client, db): _token_address = "0xd9F55747DE740297ff1eEe537aBE0f8d73B7D783" # request target API - req_param = [{ - "account_address": _test_account_address, - "key_manager": "test_key_manager", - "name": "test_name", - "postal_code": "test_postal_code", - "address": "test_address", - "email": "test_email", - "birth": "test_birth", - "is_corporate": False, - "tax_category": 10 - }] + req_param = [ + { + "account_address": _test_account_address, + "key_manager": "test_key_manager", + "name": "test_name", + "postal_code": "test_postal_code", + "address": "test_address", + "email": "test_email", + "birth": "test_birth", + "is_corporate": False, + "tax_category": 10, + } + ] resp = client.post( self.test_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -492,34 +486,33 @@ def test_error_2_2(self, client, db): db.add(account) # request target API - req_param = [{ - "account_address": _test_account_address, - "key_manager": "test_key_manager", - "name": "test_name", - "postal_code": "test_postal_code", - "address": "test_address", - "email": "test_email", - "birth": "test_birth", - "is_corporate": False, - "tax_category": 10 - }] + req_param = [ + { + "account_address": _test_account_address, + "key_manager": "test_key_manager", + "name": "test_name", + "postal_code": "test_postal_code", + "address": "test_address", + "email": "test_email", + "birth": "test_birth", + "is_corporate": False, + "tax_category": 10, + } + ] resp = client.post( self.test_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("mismatch_password") - } + "eoa-password": E2EEUtils.encrypt("mismatch_password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -543,34 +536,33 @@ def test_error_3(self, client, db): db.add(account) # request target API - req_param = [{ - "account_address": _test_account_address, - "key_manager": "test_key_manager", - "name": "test_name", - "postal_code": "test_postal_code", - "address": "test_address", - "email": "test_email", - "birth": "test_birth", - "is_corporate": False, - "tax_category": 10 - }] + req_param = [ + { + "account_address": _test_account_address, + "key_manager": "test_key_manager", + "name": "test_name", + "postal_code": "test_postal_code", + "address": "test_address", + "email": "test_email", + "birth": "test_birth", + "is_corporate": False, + "tax_category": 10, + } + ] resp = client.post( self.test_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # @@ -603,34 +595,33 @@ def test_error_4_1(self, client, db): db.add(token) # request target API - req_param = [{ - "account_address": _test_account_address, - "key_manager": "test_key_manager", - "name": "test_name", - "postal_code": "test_postal_code", - "address": "test_address", - "email": "test_email", - "birth": "test_birth", - "is_corporate": False, - "tax_category": 10 - }] + req_param = [ + { + "account_address": _test_account_address, + "key_manager": "test_key_manager", + "name": "test_name", + "postal_code": "test_postal_code", + "address": "test_address", + "email": "test_email", + "birth": "test_birth", + "is_corporate": False, + "tax_category": 10, + } + ] resp = client.post( self.test_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } # @@ -669,16 +660,13 @@ def test_error_4_2(self, client, db): json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "personal information list must not be empty" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "personal information list must not be empty", } diff --git a/tests/test_app_routers_bond_tokens_{token_address}_personal_info_batch_{batch_id}_GET.py b/tests/test_app_routers_bond_tokens_{token_address}_personal_info_batch_{batch_id}_GET.py index f07d2469..94c46c16 100644 --- a/tests/test_app_routers_bond_tokens_{token_address}_personal_info_batch_{batch_id}_GET.py +++ b/tests/test_app_routers_bond_tokens_{token_address}_personal_info_batch_{batch_id}_GET.py @@ -16,16 +16,15 @@ SPDX-License-Identifier: Apache-2.0 """ -from app.utils.e2ee_utils import E2EEUtils - from app.model.db import ( - TokenType, Account, - Token, + BatchRegisterPersonalInfo, BatchRegisterPersonalInfoUpload, BatchRegisterPersonalInfoUploadStatus, - BatchRegisterPersonalInfo + Token, + TokenType, ) +from app.utils.e2ee_utils import E2EEUtils from tests.account_config import config_eth_account @@ -39,26 +38,30 @@ class TestAppRoutersBondTokensTokenAddressPersonalInfoBatchBatchIdGET: "0f33d48f-9e6e-4a36-a55e-5bbcbda69c80", "1c961f7d-e1ad-40e5-988b-cca3d6009643", "1e778f46-864e-4ec0-b566-21bd31cf63ff", - "1f33d48f-9e6e-4a36-a55e-5bbcbda69c80" + "1f33d48f-9e6e-4a36-a55e-5bbcbda69c80", ] account_list = [ { "address": config_eth_account("user1")["address"], - "keyfile": config_eth_account("user1")["keyfile_json"] - }, { + "keyfile": config_eth_account("user1")["keyfile_json"], + }, + { "address": config_eth_account("user2")["address"], - "keyfile": config_eth_account("user2")["keyfile_json"] - }, { + "keyfile": config_eth_account("user2")["keyfile_json"], + }, + { "address": config_eth_account("user3")["address"], - "keyfile": config_eth_account("user3")["keyfile_json"] - }, { + "keyfile": config_eth_account("user3")["keyfile_json"], + }, + { "address": config_eth_account("user4")["address"], - "keyfile": config_eth_account("user4")["keyfile_json"] - }, { + "keyfile": config_eth_account("user4")["keyfile_json"], + }, + { "address": config_eth_account("user5")["address"], - "keyfile": config_eth_account("user5")["keyfile_json"] - } + "keyfile": config_eth_account("user5")["keyfile_json"], + }, ] ########################################################################### @@ -96,7 +99,9 @@ def test_normal_1(self, client, db): batch_register_upload = BatchRegisterPersonalInfoUpload() batch_register_upload.issuer_address = _issuer_address batch_register_upload.upload_id = self.upload_id_list[0] - batch_register_upload.status = BatchRegisterPersonalInfoUploadStatus.PENDING.value + batch_register_upload.status = ( + BatchRegisterPersonalInfoUploadStatus.PENDING.value + ) db.add(batch_register_upload) # Prepare data : BatchRegisterPersonalInfo @@ -114,56 +119,58 @@ def test_normal_1(self, client, db): "email": "test_value@a.test", "birth": "19900101", "is_corporate": True, - "tax_category": 3 + "tax_category": 3, } db.add(batch_register) # request target API resp = client.get( self.base_url.format(_token_address, self.upload_id_list[0]), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 200 assert resp.json() == { "status": BatchRegisterPersonalInfoUploadStatus.PENDING.value, - "results": [{ - "status": 0, - "account_address": self.account_list[0]["address"], - "key_manager": "test_value", - "name": "test_value", - "postal_code": "1000001", - "address": "test_value", - "email": "test_value@a.test", - "birth": "19900101", - "is_corporate": True, - "tax_category": 3 - }, { - "status": 0, - "account_address": self.account_list[1]["address"], - "key_manager": "test_value", - "name": "test_value", - "postal_code": "1000001", - "address": "test_value", - "email": "test_value@a.test", - "birth": "19900101", - "is_corporate": True, - "tax_category": 3 - }, { - "status": 0, - "account_address": self.account_list[2]["address"], - "key_manager": "test_value", - "name": "test_value", - "postal_code": "1000001", - "address": "test_value", - "email": "test_value@a.test", - "birth": "19900101", - "is_corporate": True, - "tax_category": 3 - }] + "results": [ + { + "status": 0, + "account_address": self.account_list[0]["address"], + "key_manager": "test_value", + "name": "test_value", + "postal_code": "1000001", + "address": "test_value", + "email": "test_value@a.test", + "birth": "19900101", + "is_corporate": True, + "tax_category": 3, + }, + { + "status": 0, + "account_address": self.account_list[1]["address"], + "key_manager": "test_value", + "name": "test_value", + "postal_code": "1000001", + "address": "test_value", + "email": "test_value@a.test", + "birth": "19900101", + "is_corporate": True, + "tax_category": 3, + }, + { + "status": 0, + "account_address": self.account_list[2]["address"], + "key_manager": "test_value", + "name": "test_value", + "postal_code": "1000001", + "address": "test_value", + "email": "test_value@a.test", + "birth": "19900101", + "is_corporate": True, + "tax_category": 3, + }, + ], } ######################################################################### @@ -179,25 +186,20 @@ def test_error_1(self, client, db): # request target API resp = client.get( - self.base_url.format(_token_address, "test_batch_id"), - headers={ - } + self.base_url.format(_token_address, "test_batch_id"), headers={} ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['header', 'issuer-address'], - 'msg': 'field required', - 'type': 'value_error.missing' + "loc": ["header", "issuer-address"], + "msg": "field required", + "type": "value_error.missing", } - ] + ], } # @@ -212,14 +214,12 @@ def test_error_2(self, client, db): self.base_url.format(_token_address, "test_batch_id"), headers={ "issuer-address": _issuer_address, - } + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, "title": "NotFound" - }, - "detail": "batch not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "batch not found", } diff --git a/tests/test_app_routers_bond_tokens_{token_address}_redeem_GET.py b/tests/test_app_routers_bond_tokens_{token_address}_redeem_GET.py index b9eda841..df277153 100644 --- a/tests/test_app_routers_bond_tokens_{token_address}_redeem_GET.py +++ b/tests/test_app_routers_bond_tokens_{token_address}_redeem_GET.py @@ -22,17 +22,17 @@ import config from app.model.db import ( + IDXIssueRedeem, + IDXIssueRedeemEventType, + IDXIssueRedeemSortItem, Token, TokenType, - IDXIssueRedeem, - IDXIssueRedeemEventType, IDXIssueRedeemSortItem ) local_tz = timezone(config.TZ) class TestAppRoutersBondTokensTokenAddressRedeemGET: - # target API endpoint base_url = "/bond/tokens/{}/redeem" @@ -48,9 +48,9 @@ class TestAppRoutersBondTokensTokenAddressRedeemGET: test_amount = [10, 20, 30] test_block_timestamp = [ - datetime.strptime("2022/01/02 15:20:30", '%Y/%m/%d %H:%M:%S'), # JST 2022/01/03 - datetime.strptime("2022/01/01 15:20:30", '%Y/%m/%d %H:%M:%S'), # JST 2022/01/02 - datetime.strptime("2022/01/02 00:20:30", '%Y/%m/%d %H:%M:%S'), # JST 2022/01/02 + datetime.strptime("2022/01/02 15:20:30", "%Y/%m/%d %H:%M:%S"), # JST 2022/01/03 + datetime.strptime("2022/01/01 15:20:30", "%Y/%m/%d %H:%M:%S"), # JST 2022/01/02 + datetime.strptime("2022/01/02 00:20:30", "%Y/%m/%d %H:%M:%S"), # JST 2022/01/02 ] test_block_timestamp_str = [ "2022-01-03T00:20:30+09:00", @@ -86,20 +86,13 @@ def test_normal_1(self, client, db): db.add(_record) # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 0, - 'offset': None, - 'limit': None, - 'total': 0 - }, - 'history': [] + "result_set": {"count": 0, "offset": None, "limit": None, "total": 0}, + "history": [], } # Normal_2 @@ -146,45 +139,38 @@ def test_normal_2(self, client, db): db.add(_record) # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 3, - 'offset': None, - 'limit': None, - 'total': 3 - }, - 'history': [ + "result_set": {"count": 3, "offset": None, "limit": None, "total": 3}, + "history": [ { - 'transaction_hash': self.test_transaction_hash, - 'token_address': self.test_token_address, - 'locked_address': self.test_locked_address, - 'target_address': self.test_target_address, - 'amount': self.test_amount[0], - 'block_timestamp': self.test_block_timestamp_str[0] + "transaction_hash": self.test_transaction_hash, + "token_address": self.test_token_address, + "locked_address": self.test_locked_address, + "target_address": self.test_target_address, + "amount": self.test_amount[0], + "block_timestamp": self.test_block_timestamp_str[0], }, { - 'transaction_hash': self.test_transaction_hash, - 'token_address': self.test_token_address, - 'locked_address': self.test_locked_address, - 'target_address': self.test_target_address, - 'amount': self.test_amount[2], - 'block_timestamp': self.test_block_timestamp_str[2] + "transaction_hash": self.test_transaction_hash, + "token_address": self.test_token_address, + "locked_address": self.test_locked_address, + "target_address": self.test_target_address, + "amount": self.test_amount[2], + "block_timestamp": self.test_block_timestamp_str[2], }, { - 'transaction_hash': self.test_transaction_hash, - 'token_address': self.test_token_address, - 'locked_address': self.test_locked_address, - 'target_address': self.test_target_address, - 'amount': self.test_amount[1], - 'block_timestamp': self.test_block_timestamp_str[1] - } - ] + "transaction_hash": self.test_transaction_hash, + "token_address": self.test_token_address, + "locked_address": self.test_locked_address, + "target_address": self.test_target_address, + "amount": self.test_amount[1], + "block_timestamp": self.test_block_timestamp_str[1], + }, + ], } # Normal_3 @@ -235,45 +221,40 @@ def test_normal_3(self, client, db): self.base_url.format(self.test_token_address), params={ "sort_item": IDXIssueRedeemSortItem.BLOCK_TIMESTAMP.value, - "sort_order": 0 - } + "sort_order": 0, + }, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 3, - 'offset': None, - 'limit': None, - 'total': 3 - }, - 'history': [ + "result_set": {"count": 3, "offset": None, "limit": None, "total": 3}, + "history": [ { - 'transaction_hash': self.test_transaction_hash, - 'token_address': self.test_token_address, - 'locked_address': self.test_locked_address, - 'target_address': self.test_target_address, - 'amount': self.test_amount[1], - 'block_timestamp': self.test_block_timestamp_str[1] + "transaction_hash": self.test_transaction_hash, + "token_address": self.test_token_address, + "locked_address": self.test_locked_address, + "target_address": self.test_target_address, + "amount": self.test_amount[1], + "block_timestamp": self.test_block_timestamp_str[1], }, { - 'transaction_hash': self.test_transaction_hash, - 'token_address': self.test_token_address, - 'locked_address': self.test_locked_address, - 'target_address': self.test_target_address, - 'amount': self.test_amount[2], - 'block_timestamp': self.test_block_timestamp_str[2] + "transaction_hash": self.test_transaction_hash, + "token_address": self.test_token_address, + "locked_address": self.test_locked_address, + "target_address": self.test_target_address, + "amount": self.test_amount[2], + "block_timestamp": self.test_block_timestamp_str[2], }, { - 'transaction_hash': self.test_transaction_hash, - 'token_address': self.test_token_address, - 'locked_address': self.test_locked_address, - 'target_address': self.test_target_address, - 'amount': self.test_amount[0], - 'block_timestamp': self.test_block_timestamp_str[0] - } - ] + "transaction_hash": self.test_transaction_hash, + "token_address": self.test_token_address, + "locked_address": self.test_locked_address, + "target_address": self.test_target_address, + "amount": self.test_amount[0], + "block_timestamp": self.test_block_timestamp_str[0], + }, + ], } # Normal_4 @@ -322,31 +303,23 @@ def test_normal_4(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "offset": 1, - "limit": 1 - } + params={"offset": 1, "limit": 1}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 3, - 'offset': 1, - 'limit': 1, - 'total': 3 - }, - 'history': [ + "result_set": {"count": 3, "offset": 1, "limit": 1, "total": 3}, + "history": [ { - 'transaction_hash': self.test_transaction_hash, - 'token_address': self.test_token_address, - 'locked_address': self.test_locked_address, - 'target_address': self.test_target_address, - 'amount': self.test_amount[2], - 'block_timestamp': self.test_block_timestamp_str[2] + "transaction_hash": self.test_transaction_hash, + "token_address": self.test_token_address, + "locked_address": self.test_locked_address, + "target_address": self.test_target_address, + "amount": self.test_amount[2], + "block_timestamp": self.test_block_timestamp_str[2], } - ] + ], } ########################################################################### @@ -357,18 +330,13 @@ def test_normal_4(self, client, db): # NotFound def test_error_1(self, client, db): # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # Error_2 @@ -386,18 +354,13 @@ def test_error_2(self, client, db): db.add(_token) # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } # Error_3 @@ -407,33 +370,28 @@ def test_error_3(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "sort_item": "block_timestamp12345" - } + params={"sort_item": "block_timestamp12345"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['query', 'sort_item'], - 'msg': "value is not a valid enumeration member; permitted: 'block_timestamp', 'locked_address', 'target_address', 'amount'", - 'type': 'type_error.enum', - 'ctx': { - 'enum_values': [ - 'block_timestamp', - 'locked_address', - 'target_address', - 'amount' + "loc": ["query", "sort_item"], + "msg": "value is not a valid enumeration member; permitted: 'block_timestamp', 'locked_address', 'target_address', 'amount'", + "type": "type_error.enum", + "ctx": { + "enum_values": [ + "block_timestamp", + "locked_address", + "target_address", + "amount", ] - } + }, } - ] + ], } # Error_4_1 @@ -442,27 +400,21 @@ def test_error_3(self, client, db): def test_error_4_1(self, client, db): # request target API resp = client.get( - self.base_url.format(self.test_token_address), - params={ - "sort_order": -1 - } + self.base_url.format(self.test_token_address), params={"sort_order": -1} ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "ctx": {"limit_value": 0}, "loc": ["query", "sort_order"], "msg": "ensure this value is greater than or equal to 0", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", } - ] + ], } # Error_4_2 @@ -471,25 +423,19 @@ def test_error_4_1(self, client, db): def test_error_4_2(self, client, db): # request target API resp = client.get( - self.base_url.format(self.test_token_address), - params={ - "sort_order": 2 - } + self.base_url.format(self.test_token_address), params={"sort_order": 2} ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "ctx": {"limit_value": 1}, "loc": ["query", "sort_order"], "msg": "ensure this value is less than or equal to 1", - "type": "value_error.number.not_le" + "type": "value_error.number.not_le", } - ] + ], } diff --git a/tests/test_app_routers_bond_tokens_{token_address}_redeem_POST.py b/tests/test_app_routers_bond_tokens_{token_address}_redeem_POST.py index 7912f798..050691a4 100644 --- a/tests/test_app_routers_bond_tokens_{token_address}_redeem_POST.py +++ b/tests/test_app_routers_bond_tokens_{token_address}_redeem_POST.py @@ -20,14 +20,9 @@ from unittest import mock from unittest.mock import ANY, MagicMock -from app.model.db import ( - Account, - AuthToken, - Token, - TokenType -) -from app.utils.e2ee_utils import E2EEUtils from app.exceptions import SendTransactionError +from app.model.db import Account, AuthToken, Token, TokenType +from app.utils.e2ee_utils import E2EEUtils from tests.account_config import config_eth_account @@ -67,24 +62,19 @@ def test_normal_1(self, IbetStraightBondContract_mock, client, db): IbetStraightBondContract_mock.side_effect = [None] # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion IbetStraightBondContract_mock.assert_any_call( - data=req_param, - tx_from=_issuer_address, - private_key=ANY + data=req_param, tx_from=_issuer_address, private_key=ANY ) assert resp.status_code == 200 @@ -124,24 +114,19 @@ def test_normal_2(self, IbetStraightBondContract_mock, client, db): IbetStraightBondContract_mock.side_effect = [None] # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "auth-token": "test_auth_token" - } + "auth-token": "test_auth_token", + }, ) # assertion IbetStraightBondContract_mock.assert_any_call( - data=req_param, - tx_from=_issuer_address, - private_key=ANY + data=req_param, tx_from=_issuer_address, private_key=ANY ) assert resp.status_code == 200 @@ -169,37 +154,28 @@ def test_error_1(self, client, db): db.add(token) # request target API - req_param = { - "account_address": "0x0", - "amount": 10 - } + req_param = {"account_address": "0x0", "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "loc": [ - "body", - "account_address" - ], + "loc": ["body", "account_address"], "msg": "account_address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -220,40 +196,29 @@ def test_error_2(self, client, db): db.add(token) # request target API - req_param = { - "account_address": _issuer_address, - "amount": 0 - } + req_param = {"account_address": _issuer_address, "amount": 0} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "ctx": { - "limit_value": 1 - }, - "loc": [ - "body", - "amount" - ], + "ctx": {"limit_value": 1}, + "loc": ["body", "amount"], "msg": "ensure this value is greater than or equal to 1", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, - ] + ], } # @@ -274,40 +239,29 @@ def test_error_3(self, client, db): db.add(token) # request target API - req_param = { - "account_address": _issuer_address, - "amount": 1_000_000_000_001 - } + req_param = {"account_address": _issuer_address, "amount": 1_000_000_000_001} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "ctx": { - "limit_value": 1_000_000_000_000 - }, - "loc": [ - "body", - "amount" - ], + "ctx": {"limit_value": 1_000_000_000_000}, + "loc": ["body", "amount"], "msg": "ensure this value is less than or equal to 1000000000000", - "type": "value_error.number.not_le" + "type": "value_error.number.not_le", }, - ] + ], } # @@ -316,29 +270,24 @@ def test_error_4(self, client, db): _token_address = "token_address_test" # request target API - resp = client.post( - self.base_url.format(_token_address) - ) + resp = client.post(self.base_url.format(_token_address)) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, { "loc": ["body"], "msg": "field required", - "type": "value_error.missing" - } - ] + "type": "value_error.missing", + }, + ], } # @@ -349,33 +298,25 @@ def test_error_5(self, client, db): _token_address = "token_address_test" # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, - headers={ - "issuer-address": "issuer-address" - } + headers={"issuer-address": "issuer-address"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -394,30 +335,23 @@ def test_error_6(self, client, db): db.add(account) # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, - headers={ - "issuer-address": _issuer_address, - "eoa-password": "password" - } + headers={"issuer-address": _issuer_address, "eoa-password": "password"}, ) assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, - "detail": [{ - "loc": ["header", "eoa-password"], - "msg": "eoa-password is not a Base64-encoded encrypted data", - "type": "value_error" - }] + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ + { + "loc": ["header", "eoa-password"], + "msg": "eoa-password is not a Base64-encoded encrypted data", + "type": "value_error", + } + ], } # @@ -438,28 +372,22 @@ def test_error_7(self, client, db): db.add(token) # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -478,26 +406,20 @@ def test_error_8(self, client, db): db.add(account) # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password_test") - } + "eoa-password": E2EEUtils.encrypt("password_test"), + }, ) assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -516,26 +438,20 @@ def test_error_9(self, client, db): db.add(account) # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # @@ -563,33 +479,29 @@ def test_error_10(self, client, db): db.add(token) # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } # # Send Transaction Error - @mock.patch("app.model.blockchain.token.IbetStraightBondContract.redeem", - MagicMock(side_effect=SendTransactionError())) + @mock.patch( + "app.model.blockchain.token.IbetStraightBondContract.redeem", + MagicMock(side_effect=SendTransactionError()), + ) def test_error_11(self, client, db): test_account = config_eth_account("user1") _issuer_address = test_account["address"] @@ -612,25 +524,19 @@ def test_error_11(self, client, db): db.add(token) # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 2, - "title": "SendTransactionError" - }, - "detail": "failed to send transaction" + "meta": {"code": 2, "title": "SendTransactionError"}, + "detail": "failed to send transaction", } diff --git a/tests/test_app_routers_bond_tokens_{token_address}_redeem_batch_GET.py b/tests/test_app_routers_bond_tokens_{token_address}_redeem_batch_GET.py index c89c157d..30fafeee 100644 --- a/tests/test_app_routers_bond_tokens_{token_address}_redeem_batch_GET.py +++ b/tests/test_app_routers_bond_tokens_{token_address}_redeem_batch_GET.py @@ -20,10 +20,10 @@ from unittest import mock from app.model.db import ( + BatchIssueRedeemProcessingCategory, + BatchIssueRedeemUpload, Token, TokenType, - BatchIssueRedeemUpload, - BatchIssueRedeemProcessingCategory ) from tests.account_config import config_eth_account @@ -53,21 +53,13 @@ def test_normal_1(self, client, db): db.add(token) # request target API - resp = client.get( - self.base_url.format(token_address), - headers={} - ) + resp = client.get(self.base_url.format(token_address), headers={}) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 0, - "limit": None, - "offset": None, - "total": 0 - }, - "uploads": [] - } + "result_set": {"count": 0, "limit": None, "offset": None, "total": 0}, + "uploads": [], + } # # 1 record @@ -95,30 +87,21 @@ def test_normal_2(self, client, db): db.add(redeem_upload1) # request target API - resp = client.get( - self.base_url.format(token_address), - headers={} - ) + resp = client.get(self.base_url.format(token_address), headers={}) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 1, - "limit": None, - "offset": None, - "total": 1 - }, - "uploads": - [ + "result_set": {"count": 1, "limit": None, "offset": None, "total": 1}, + "uploads": [ { "issuer_address": issuer_address, "processed": False, "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, } - ] + ], } # @@ -184,19 +167,11 @@ def test_normal_3_1(self, client, db): db.add(redeem_upload5) # request target API - resp = client.get( - self.base_url.format(token_address), - headers={} - ) + resp = client.get(self.base_url.format(token_address), headers={}) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 4, - "limit": None, - "offset": None, - "total": 4 - }, + "result_set": {"count": 4, "limit": None, "offset": None, "total": 4}, "uploads": [ { "issuer_address": issuer_address, @@ -204,7 +179,7 @@ def test_normal_3_1(self, client, db): "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -212,7 +187,7 @@ def test_normal_3_1(self, client, db): "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -220,7 +195,7 @@ def test_normal_3_1(self, client, db): "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -228,9 +203,9 @@ def test_normal_3_1(self, client, db): "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY - } - ] + "created": mock.ANY, + }, + ], } # @@ -298,19 +273,12 @@ def test_normal_3_2(self, client, db): # request target API resp = client.get( self.base_url.format(token_address), - headers={ - "issuer-address": issuer_address - } + headers={"issuer-address": issuer_address}, ) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 2, - "limit": None, - "offset": None, - "total": 2 - }, + "result_set": {"count": 2, "limit": None, "offset": None, "total": 2}, "uploads": [ { "issuer_address": issuer_address, @@ -318,7 +286,7 @@ def test_normal_3_2(self, client, db): "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -326,10 +294,10 @@ def test_normal_3_2(self, client, db): "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY - } - ] - } + "created": mock.ANY, + }, + ], + } # # Multi record (status) @@ -394,31 +362,20 @@ def test_normal_3_3(self, client, db): db.add(redeem_upload5) # request target API - req_param = { - "processed": False - } - resp = client.get( - self.base_url.format(token_address), - params=req_param - ) + req_param = {"processed": False} + resp = client.get(self.base_url.format(token_address), params=req_param) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 3, - "limit": None, - "offset": None, - "total": 4 - }, - "uploads": - [ + "result_set": {"count": 3, "limit": None, "offset": None, "total": 4}, + "uploads": [ { "issuer_address": issuer_address, "processed": False, "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -426,7 +383,7 @@ def test_normal_3_3(self, client, db): "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -434,9 +391,9 @@ def test_normal_3_3(self, client, db): "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY - } - ] + "created": mock.ANY, + }, + ], } # @@ -502,23 +459,12 @@ def test_normal_4(self, client, db): db.add(redeem_upload5) # request target API - req_param = { - "limit": 2, - "offset": 2 - } - resp = client.get( - self.base_url.format(token_address), - params=req_param - ) + req_param = {"limit": 2, "offset": 2} + resp = client.get(self.base_url.format(token_address), params=req_param) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 4, - "limit": 2, - "offset": 2, - "total": 4 - }, + "result_set": {"count": 4, "limit": 2, "offset": 2, "total": 4}, "uploads": [ { "issuer_address": issuer_address, @@ -526,7 +472,7 @@ def test_normal_4(self, client, db): "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -534,9 +480,9 @@ def test_normal_4(self, client, db): "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY - } - ] + "created": mock.ANY, + }, + ], } # @@ -561,7 +507,9 @@ def test_normal_5(self, client, db): additional_issue_upload1.token_address = token_address additional_issue_upload1.issuer_address = issuer_address additional_issue_upload1.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload1.category = BatchIssueRedeemProcessingCategory.REDEEM.value + additional_issue_upload1.category = ( + BatchIssueRedeemProcessingCategory.REDEEM.value + ) additional_issue_upload1.processed = True db.add(additional_issue_upload1) @@ -570,7 +518,9 @@ def test_normal_5(self, client, db): additional_issue_upload2.token_address = token_address additional_issue_upload2.issuer_address = issuer_address additional_issue_upload2.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload2.category = BatchIssueRedeemProcessingCategory.REDEEM.value + additional_issue_upload2.category = ( + BatchIssueRedeemProcessingCategory.REDEEM.value + ) additional_issue_upload2.processed = False db.add(additional_issue_upload2) @@ -579,7 +529,9 @@ def test_normal_5(self, client, db): additional_issue_upload3.token_address = token_address additional_issue_upload3.issuer_address = issuer_address additional_issue_upload3.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload3.category = BatchIssueRedeemProcessingCategory.REDEEM.value + additional_issue_upload3.category = ( + BatchIssueRedeemProcessingCategory.REDEEM.value + ) additional_issue_upload3.processed = True db.add(additional_issue_upload3) @@ -588,7 +540,9 @@ def test_normal_5(self, client, db): additional_issue_upload4.token_address = token_address additional_issue_upload4.issuer_address = issuer_address additional_issue_upload4.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload4.category = BatchIssueRedeemProcessingCategory.REDEEM.value + additional_issue_upload4.category = ( + BatchIssueRedeemProcessingCategory.REDEEM.value + ) additional_issue_upload4.processed = False db.add(additional_issue_upload4) @@ -597,27 +551,19 @@ def test_normal_5(self, client, db): additional_issue_upload5.token_address = "other_token" additional_issue_upload5.issuer_address = issuer_address additional_issue_upload5.token_type = TokenType.IBET_STRAIGHT_BOND.value - additional_issue_upload5.category = BatchIssueRedeemProcessingCategory.REDEEM.value + additional_issue_upload5.category = ( + BatchIssueRedeemProcessingCategory.REDEEM.value + ) additional_issue_upload5.processed = False db.add(additional_issue_upload5) # request target API - req_param = { - "sort_order": 0 - } - resp = client.get( - self.base_url.format(token_address), - params=req_param - ) + req_param = {"sort_order": 0} + resp = client.get(self.base_url.format(token_address), params=req_param) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 4, - "limit": None, - "offset": None, - "total": 4 - }, + "result_set": {"count": 4, "limit": None, "offset": None, "total": 4}, "uploads": [ { "issuer_address": issuer_address, @@ -625,7 +571,7 @@ def test_normal_5(self, client, db): "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -633,7 +579,7 @@ def test_normal_5(self, client, db): "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -641,7 +587,7 @@ def test_normal_5(self, client, db): "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -649,9 +595,9 @@ def test_normal_5(self, client, db): "token_address": "token_address_test", "token_type": "IbetStraightBond", "batch_id": mock.ANY, - "created": mock.ANY - } - ] + "created": mock.ANY, + }, + ], } ########################################################################### @@ -677,13 +623,8 @@ def test_error_1(self, client, db): db.add(token) # request target API - req_param = { - "processed": "invalid_value" - } - resp = client.get( - self.base_url.format(token_address), - params=req_param - ) + req_param = {"processed": "invalid_value"} + resp = client.get(self.base_url.format(token_address), params=req_param) assert resp.status_code == 422 assert resp.json() == { @@ -691,10 +632,8 @@ def test_error_1(self, client, db): { "loc": ["query", "processed"], "msg": "value could not be parsed to a boolean", - "type": "type_error.bool" + "type": "type_error.bool", } ], - "meta": { - "code": 1, "title": "RequestValidationError" - } + "meta": {"code": 1, "title": "RequestValidationError"}, } diff --git a/tests/test_app_routers_bond_tokens_{token_address}_redeem_batch_POST.py b/tests/test_app_routers_bond_tokens_{token_address}_redeem_batch_POST.py index 7308a959..bf475eea 100644 --- a/tests/test_app_routers_bond_tokens_{token_address}_redeem_batch_POST.py +++ b/tests/test_app_routers_bond_tokens_{token_address}_redeem_batch_POST.py @@ -20,10 +20,11 @@ from app.model.db import ( Account, + BatchIssueRedeem, + BatchIssueRedeemProcessingCategory, + BatchIssueRedeemUpload, Token, TokenType, - BatchIssueRedeemUpload, - BatchIssueRedeem, BatchIssueRedeemProcessingCategory ) from app.utils.e2ee_utils import E2EEUtils from tests.account_config import config_eth_account @@ -64,23 +65,20 @@ def test_normal_1(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 10 - } - ] + req_param = [{"account_address": test_account_1, "amount": 10}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion - upload: Optional[BatchIssueRedeemUpload] = db.query(BatchIssueRedeemUpload).first() + upload: Optional[BatchIssueRedeemUpload] = db.query( + BatchIssueRedeemUpload + ).first() assert upload.issuer_address == issuer_address assert upload.token_type == TokenType.IBET_STRAIGHT_BOND.value assert upload.token_address == token_address @@ -128,26 +126,22 @@ def test_normal_2(self, client, db): # request target API req_param = [ - { - "account_address": test_account_1, - "amount": 10 - }, - { - "account_address": test_account_2, - "amount": 20 - } + {"account_address": test_account_1, "amount": 10}, + {"account_address": test_account_2, "amount": 20}, ] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion - upload: Optional[BatchIssueRedeemUpload] = db.query(BatchIssueRedeemUpload).first() + upload: Optional[BatchIssueRedeemUpload] = db.query( + BatchIssueRedeemUpload + ).first() assert upload.issuer_address == issuer_address assert upload.token_type == TokenType.IBET_STRAIGHT_BOND.value assert upload.token_address == token_address @@ -207,24 +201,21 @@ def test_error_1_1(self, client, db): json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['body'], - 'msg': 'value is not a valid list', - 'type': 'type_error.list' + "loc": ["body"], + "msg": "value is not a valid list", + "type": "type_error.list", } - ] + ], } # Error_1_2 @@ -252,35 +243,27 @@ def test_error_1_2(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": "0x0", - "amount": 10 - } - ] + req_param = [{"account_address": "0x0", "amount": 10}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['body', 0, 'account_address'], - 'msg': 'account_address is not a valid address', - 'type': 'value_error' + "loc": ["body", 0, "account_address"], + "msg": "account_address is not a valid address", + "type": "value_error", } - ] + ], } # Error_1_3_1 @@ -310,36 +293,28 @@ def test_error_1_3_1(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 0 - } - ] + req_param = [{"account_address": test_account_1, "amount": 0}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['body', 0, 'amount'], - 'msg': 'ensure this value is greater than or equal to 1', - 'type': 'value_error.number.not_ge', - 'ctx': {'limit_value': 1} + "loc": ["body", 0, "amount"], + "msg": "ensure this value is greater than or equal to 1", + "type": "value_error.number.not_ge", + "ctx": {"limit_value": 1}, } - ] + ], } # Error_1_3_2 @@ -369,36 +344,28 @@ def test_error_1_3_2(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 1_000_000_000_001 - } - ] + req_param = [{"account_address": test_account_1, "amount": 1_000_000_000_001}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['body', 0, 'amount'], - 'msg': 'ensure this value is less than or equal to 1000000000000', - 'type': 'value_error.number.not_le', - 'ctx': {'limit_value': 1000000000000} + "loc": ["body", 0, "amount"], + "msg": "ensure this value is less than or equal to 1000000000000", + "type": "value_error.number.not_le", + "ctx": {"limit_value": 1000000000000}, } - ] + ], } # Error_1_4 @@ -428,32 +395,22 @@ def test_error_1_4(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 10 - } - ] + req_param = [{"account_address": test_account_1, "amount": 10}] resp = client.post( - self.base_url.format(token_address), - json=req_param, - headers=None + self.base_url.format(token_address), json=req_param, headers=None ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['header', 'issuer-address'], - 'msg': 'field required', - 'type': 'value_error.missing' + "loc": ["header", "issuer-address"], + "msg": "field required", + "type": "value_error.missing", } - ] + ], } # Error_1_5 @@ -483,35 +440,24 @@ def test_error_1_5(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 10 - } - ] + req_param = [{"account_address": test_account_1, "amount": 10}] resp = client.post( self.base_url.format(token_address), json=req_param, - headers={ - "issuer-address": issuer_address, - "eoa-password": "password" - } + headers={"issuer-address": issuer_address, "eoa-password": "password"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['header', 'eoa-password'], - 'msg': 'eoa-password is not a Base64-encoded encrypted data', - 'type': 'value_error' + "loc": ["header", "eoa-password"], + "msg": "eoa-password is not a Base64-encoded encrypted data", + "type": "value_error", } - ] + ], } # Error_1_6 @@ -545,18 +491,15 @@ def test_error_1_6(self, client, db): json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'InvalidParameterError' - }, - 'detail': 'list length must be at least one' + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "list length must be at least one", } # Error_1_7_1 @@ -586,29 +529,21 @@ def test_error_1_7_1(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 10 - } - ] + req_param = [{"account_address": test_account_1, "amount": 10}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'AuthorizationError' - }, - 'detail': 'issuer does not exist, or password mismatch' + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # Error_1_7_2 @@ -638,29 +573,21 @@ def test_error_1_7_2(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 10 - } - ] + req_param = [{"account_address": test_account_1, "amount": 10}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'AuthorizationError' - }, - 'detail': 'issuer does not exist, or password mismatch' + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # Error_1_8_1 @@ -683,29 +610,21 @@ def test_error_1_8_1(self, client, db): db.add(account) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 10 - } - ] + req_param = [{"account_address": test_account_1, "amount": 10}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'NotFound' - }, - 'detail': 'token not found' + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # Error_1_8_2 @@ -737,27 +656,19 @@ def test_error_1_8_2(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 10 - } - ] + req_param = [{"account_address": test_account_1, "amount": 10}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'InvalidParameterError' - }, - 'detail': 'this token is temporarily unavailable' + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } diff --git a/tests/test_app_routers_bond_tokens_{token_address}_redeem_batch_{batch_id}_GET.py b/tests/test_app_routers_bond_tokens_{token_address}_redeem_batch_{batch_id}_GET.py index 3447ada5..fe7f5870 100644 --- a/tests/test_app_routers_bond_tokens_{token_address}_redeem_batch_{batch_id}_GET.py +++ b/tests/test_app_routers_bond_tokens_{token_address}_redeem_batch_{batch_id}_GET.py @@ -16,16 +16,15 @@ SPDX-License-Identifier: Apache-2.0 """ -from app.utils.e2ee_utils import E2EEUtils - from app.model.db import ( - TokenType, Account, - Token, - BatchIssueRedeemUpload, + BatchIssueRedeem, BatchIssueRedeemProcessingCategory, - BatchIssueRedeem + BatchIssueRedeemUpload, + Token, + TokenType, ) +from app.utils.e2ee_utils import E2EEUtils from tests.account_config import config_eth_account @@ -39,13 +38,8 @@ class TestAppRoutersBondTokensTokenAddressRedeemBatchBatchIdGET: ] account_list = [ - { - "address": config_eth_account("user1")["address"], - "amount": 1 - }, { - "address": config_eth_account("user2")["address"], - "amount": 2 - } + {"address": config_eth_account("user1")["address"], "amount": 1}, + {"address": config_eth_account("user2")["address"], "amount": 2}, ] ########################################################################### @@ -95,22 +89,20 @@ def test_normal_1(self, client, db): # request target API resp = client.get( self.base_url.format(test_token_address, self.upload_id_list[0]), - headers={ - "issuer-address": issuer_address - } + headers={"issuer-address": issuer_address}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'processed': True, - 'results': [ + "processed": True, + "results": [ { - 'account_address': self.account_list[0]["address"], - 'amount': self.account_list[0]["amount"], - 'status': 1 + "account_address": self.account_list[0]["address"], + "amount": self.account_list[0]["amount"], + "status": 1, } - ] + ], } # Normal_2 @@ -163,27 +155,25 @@ def test_normal_2(self, client, db): # request target API resp = client.get( self.base_url.format(test_token_address, self.upload_id_list[0]), - headers={ - "issuer-address": issuer_address - } + headers={"issuer-address": issuer_address}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'processed': True, - 'results': [ + "processed": True, + "results": [ { - 'account_address': self.account_list[0]["address"], - 'amount': self.account_list[0]["amount"], - 'status': 1 + "account_address": self.account_list[0]["address"], + "amount": self.account_list[0]["amount"], + "status": 1, }, { - 'account_address': self.account_list[1]["address"], - 'amount': self.account_list[1]["amount"], - 'status': 1 - } - ] + "account_address": self.account_list[1]["address"], + "amount": self.account_list[1]["amount"], + "status": 1, + }, + ], } ######################################################################### @@ -226,17 +216,12 @@ def test_error_1(self, client, db): # request target API resp = client.get( self.base_url.format(test_token_address, self.upload_id_list[0]), - headers={ - "issuer-address": issuer_address - } + headers={"issuer-address": issuer_address}, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "batch not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "batch not found", } diff --git a/tests/test_app_routers_bond_tokens_{token_address}_scheduled_events_GET.py b/tests/test_app_routers_bond_tokens_{token_address}_scheduled_events_GET.py index b2f4de02..a647c6db 100644 --- a/tests/test_app_routers_bond_tokens_{token_address}_scheduled_events_GET.py +++ b/tests/test_app_routers_bond_tokens_{token_address}_scheduled_events_GET.py @@ -17,19 +17,12 @@ SPDX-License-Identifier: Apache-2.0 """ import uuid -from datetime import ( - datetime, - timedelta -) +from datetime import datetime, timedelta from pytz import timezone +from app.model.db import ScheduledEvents, ScheduledEventType, TokenType from config import TZ -from app.model.db import ( - TokenType, - ScheduledEvents, - ScheduledEventType -) from tests.account_config import config_eth_account @@ -52,7 +45,12 @@ def test_normal_1(self, client, db): # prepare data datetime_now_utc = datetime.utcnow() - datetime_now_str = timezone("UTC").localize(datetime_now_utc).astimezone(self.local_tz).isoformat() + datetime_now_str = ( + timezone("UTC") + .localize(datetime_now_utc) + .astimezone(self.local_tz) + .isoformat() + ) update_data = { "face_value": 10000, "interest_rate": 0.5, @@ -87,7 +85,7 @@ def test_normal_1(self, client, db): self.base_url.format(_token_address), headers={ "issuer-address": _issuer_address, - } + }, ) # assertion @@ -101,7 +99,7 @@ def test_normal_1(self, client, db): "event_type": ScheduledEventType.UPDATE.value, "status": 0, "data": update_data, - "created": datetime_now_str + "created": datetime_now_str, } ] @@ -164,21 +162,34 @@ def test_normal_2(self, client, db): "scheduled_event_id": uuid_list[0], "token_address": _token_address, "token_type": TokenType.IBET_STRAIGHT_BOND.value, - "scheduled_datetime": timezone("UTC").localize(datetime_list[0]).astimezone(self.local_tz).isoformat(), + "scheduled_datetime": timezone("UTC") + .localize(datetime_list[0]) + .astimezone(self.local_tz) + .isoformat(), "event_type": ScheduledEventType.UPDATE.value, "status": 0, "data": update_data, - "created": timezone("UTC").localize(datetime_list[0]).astimezone(self.local_tz).isoformat(), - }, { + "created": timezone("UTC") + .localize(datetime_list[0]) + .astimezone(self.local_tz) + .isoformat(), + }, + { "scheduled_event_id": uuid_list[1], "token_address": _token_address, "token_type": TokenType.IBET_STRAIGHT_BOND.value, - "scheduled_datetime": timezone("UTC").localize(datetime_list[1]).astimezone(self.local_tz).isoformat(), + "scheduled_datetime": timezone("UTC") + .localize(datetime_list[1]) + .astimezone(self.local_tz) + .isoformat(), "event_type": ScheduledEventType.UPDATE.value, "status": 0, "data": update_data, - "created": timezone("UTC").localize(datetime_list[1]).astimezone(self.local_tz).isoformat(), - } + "created": timezone("UTC") + .localize(datetime_list[1]) + .astimezone(self.local_tz) + .isoformat(), + }, ] # @@ -193,7 +204,7 @@ def test_normal_3(self, client, db): self.base_url.format(_token_address), headers={ "issuer-address": _issuer_address, - } + }, ) # assertion diff --git a/tests/test_app_routers_bond_tokens_{token_address}_scheduled_events_POST.py b/tests/test_app_routers_bond_tokens_{token_address}_scheduled_events_POST.py index d9372e2c..2fd59651 100644 --- a/tests/test_app_routers_bond_tokens_{token_address}_scheduled_events_POST.py +++ b/tests/test_app_routers_bond_tokens_{token_address}_scheduled_events_POST.py @@ -16,20 +16,11 @@ SPDX-License-Identifier: Apache-2.0 """ -from datetime import ( - datetime, - timezone -) +from datetime import datetime, timezone from pytz import timezone as tz -from app.model.db import ( - Account, - Token, - TokenType, - ScheduledEvents, - ScheduledEventType -) +from app.model.db import Account, ScheduledEvents, ScheduledEventType, Token, TokenType from app.utils.e2ee_utils import E2EEUtils from tests.account_config import config_eth_account @@ -89,26 +80,30 @@ def test_normal_1(self, client, db): req_param = { "scheduled_datetime": datetime_now_str, "event_type": "Update", - "data": update_data + "data": update_data, } resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion - _scheduled_event = db.query(ScheduledEvents). \ - filter(ScheduledEvents.issuer_address == _issuer_address). \ - filter(ScheduledEvents.token_address == _token_address). \ - first() + _scheduled_event = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.issuer_address == _issuer_address) + .filter(ScheduledEvents.token_address == _token_address) + .first() + ) assert resp.status_code == 200 assert resp.json() == {"scheduled_event_id": _scheduled_event.event_id} assert _scheduled_event.token_type == TokenType.IBET_STRAIGHT_BOND.value - assert _scheduled_event.scheduled_datetime == datetime_now_utc.replace(tzinfo=None) + assert _scheduled_event.scheduled_datetime == datetime_now_utc.replace( + tzinfo=None + ) assert _scheduled_event.event_type == ScheduledEventType.UPDATE.value assert _scheduled_event.status == 0 assert _scheduled_event.data == update_data @@ -160,27 +155,30 @@ def test_normal_2(self, client, db): req_param = { "scheduled_datetime": datetime_now_str, "event_type": "Update", - "data": update_data + "data": update_data, } resp_1 = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion - _scheduled_event = db.query(ScheduledEvents). \ - filter(ScheduledEvents.issuer_address == _issuer_address). \ - filter(ScheduledEvents.token_address == _token_address). \ - first() + _scheduled_event = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.issuer_address == _issuer_address) + .filter(ScheduledEvents.token_address == _token_address) + .first() + ) assert resp_1.status_code == 200 assert resp_1.json() == {"scheduled_event_id": _scheduled_event.event_id} assert _scheduled_event.token_type == TokenType.IBET_STRAIGHT_BOND.value - assert _scheduled_event.scheduled_datetime == \ - datetime_now_jst.astimezone(timezone.utc).replace(tzinfo=None) + assert _scheduled_event.scheduled_datetime == datetime_now_jst.astimezone( + timezone.utc + ).replace(tzinfo=None) assert _scheduled_event.event_type == ScheduledEventType.UPDATE.value assert _scheduled_event.status == 0 assert _scheduled_event.data == update_data @@ -206,15 +204,15 @@ def test_error_1(self, client, db): req_param = { "scheduled_datetime": datetime_now_str, "event_type": "Update", - "data": update_data + "data": update_data, } resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address[:-1], # too short - "eoa-password": "password" # not encrypted - } + "eoa-password": "password", # not encrypted + }, ) # assertion @@ -224,12 +222,13 @@ def test_error_1(self, client, db): { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" - }, { + "type": "value_error", + }, + { "loc": ["header", "eoa-password"], "msg": "eoa-password is not a Base64-encoded encrypted data", - "type": "value_error" - } + "type": "value_error", + }, ] # @@ -251,15 +250,15 @@ def test_error_2(self, client, db): req_param = { "scheduled_datetime": datetime_now_str, "event_type": "Update", - "data": update_data + "data": update_data, } resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion @@ -300,15 +299,15 @@ def test_error_3(self, client, db): req_param = { "scheduled_datetime": datetime_now_str, "event_type": "Update", - "data": update_data + "data": update_data, } resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("mismatch-password") - } + "eoa-password": E2EEUtils.encrypt("mismatch-password"), + }, ) # assertion @@ -341,15 +340,15 @@ def test_error_4(self, client, db): req_param = { "scheduled_datetime": datetime_now_str, "event_type": "Update", - "data": update_data + "data": update_data, } resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion @@ -371,15 +370,15 @@ def test_error_5(self, client, db): "event_type": "aUpdateb", "data": { "face_value": "must be integer, but string", - } + }, } resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion @@ -389,17 +388,19 @@ def test_error_5(self, client, db): { "loc": ["body", "scheduled_datetime"], "msg": "invalid datetime format", - "type": "value_error.datetime" - }, { + "type": "value_error.datetime", + }, + { "ctx": {"enum_values": ["Update"]}, "loc": ["body", "event_type"], "msg": "value is not a valid enumeration member; permitted: 'Update'", - "type": "type_error.enum" - }, { + "type": "type_error.enum", + }, + { "loc": ["body", "data", "face_value"], "msg": "value is not a valid integer", - "type": "type_error.integer" - } + "type": "type_error.integer", + }, ] # @@ -449,23 +450,20 @@ def test_error_6(self, client, db): req_param = { "scheduled_datetime": datetime_now_str, "event_type": "Update", - "data": update_data + "data": update_data, } resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } diff --git a/tests/test_app_routers_bond_tokens_{token_address}_scheduled_events_{scheduled_event_id}_DELETE.py b/tests/test_app_routers_bond_tokens_{token_address}_scheduled_events_{scheduled_event_id}_DELETE.py index 8a0357dc..9d17187a 100644 --- a/tests/test_app_routers_bond_tokens_{token_address}_scheduled_events_{scheduled_event_id}_DELETE.py +++ b/tests/test_app_routers_bond_tokens_{token_address}_scheduled_events_{scheduled_event_id}_DELETE.py @@ -21,14 +21,9 @@ from pytz import timezone -from config import TZ -from app.model.db import ( - Account, - TokenType, - ScheduledEvents, - ScheduledEventType -) +from app.model.db import Account, ScheduledEvents, ScheduledEventType, TokenType from app.utils.e2ee_utils import E2EEUtils +from config import TZ from tests.account_config import config_eth_account @@ -56,7 +51,12 @@ def test_normal_1(self, client, db): db.add(account) datetime_now_utc = datetime.utcnow() - datetime_now_str = timezone("UTC").localize(datetime_now_utc).astimezone(self.local_tz).isoformat() + datetime_now_str = ( + timezone("UTC") + .localize(datetime_now_utc) + .astimezone(self.local_tz) + .isoformat() + ) data = { "face_value": 10000, "interest_rate": 0.5, @@ -91,8 +91,8 @@ def test_normal_1(self, client, db): self.base_url.format(_token_address, event_id), headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion @@ -105,9 +105,13 @@ def test_normal_1(self, client, db): "event_type": ScheduledEventType.UPDATE.value, "status": 0, "data": data, - "created": datetime_now_str + "created": datetime_now_str, } - token_event = db.query(ScheduledEvents).filter(ScheduledEvents.event_id == event_id).first() + token_event = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.event_id == event_id) + .first() + ) assert token_event is None ######################################################################### @@ -127,8 +131,8 @@ def test_error_1(self, client, db): self.base_url.format(_token_address, "test_event_id"), headers={ "issuer-address": _issuer_address[:-1], # too short - "eoa-password": "password" # not encrypted - } + "eoa-password": "password", # not encrypted + }, ) # assertion @@ -138,12 +142,13 @@ def test_error_1(self, client, db): { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" - }, { + "type": "value_error", + }, + { "loc": ["header", "eoa-password"], "msg": "eoa-password is not a Base64-encoded encrypted data", - "type": "value_error" - } + "type": "value_error", + }, ] # @@ -159,8 +164,8 @@ def test_error_2(self, client, db): self.base_url.format(_token_address, "test_event_id"), headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion @@ -189,8 +194,8 @@ def test_error_3(self, client, db): self.base_url.format(_token_address, "test_event_id"), headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("mismatch_password") - } + "eoa-password": E2EEUtils.encrypt("mismatch_password"), + }, ) # assertion @@ -219,8 +224,8 @@ def test_error_4(self, client, db): self.base_url.format(_token_address, "test_event_id"), headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion diff --git a/tests/test_app_routers_bond_tokens_{token_address}_scheduled_events_{scheduled_event_id}_GET.py b/tests/test_app_routers_bond_tokens_{token_address}_scheduled_events_{scheduled_event_id}_GET.py index 2518bb4e..0433d965 100644 --- a/tests/test_app_routers_bond_tokens_{token_address}_scheduled_events_{scheduled_event_id}_GET.py +++ b/tests/test_app_routers_bond_tokens_{token_address}_scheduled_events_{scheduled_event_id}_GET.py @@ -21,12 +21,8 @@ from pytz import timezone +from app.model.db import ScheduledEvents, ScheduledEventType, TokenType from config import TZ -from app.model.db import ( - TokenType, - ScheduledEvents, - ScheduledEventType -) from tests.account_config import config_eth_account @@ -49,7 +45,12 @@ def test_normal_1(self, client, db): # prepare data datetime_now_utc = datetime.utcnow() - datetime_now_str = timezone("UTC").localize(datetime_now_utc).astimezone(self.local_tz).isoformat() + datetime_now_str = ( + timezone("UTC") + .localize(datetime_now_utc) + .astimezone(self.local_tz) + .isoformat() + ) update_data = { "face_value": 10000, "interest_rate": 0.5, @@ -84,7 +85,7 @@ def test_normal_1(self, client, db): self.base_url.format(_token_address, event_id), headers={ "issuer-address": _issuer_address, - } + }, ) # assertion @@ -110,7 +111,12 @@ def test_normal_2(self, client, db): # prepare data datetime_now_utc = datetime.utcnow() - datetime_now_str = timezone("UTC").localize(datetime_now_utc).astimezone(self.local_tz).isoformat() + datetime_now_str = ( + timezone("UTC") + .localize(datetime_now_utc) + .astimezone(self.local_tz) + .isoformat() + ) update_data = { "face_value": 10000, "interest_rate": 0.5, @@ -155,7 +161,7 @@ def test_normal_2(self, client, db): "event_type": ScheduledEventType.UPDATE.value, "status": 0, "data": update_data, - "created": datetime_now_str + "created": datetime_now_str, } ######################################################################### @@ -174,14 +180,12 @@ def test_error_1(self, client, db): self.base_url.format(_token_address, "test_event_id"), headers={ "issuer-address": _issuer_address, - } + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, "title": "NotFound" - }, - "detail": "event not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "event not found", } diff --git a/tests/test_app_routers_bond_transfer_approvals_GET.py b/tests/test_app_routers_bond_transfer_approvals_GET.py index 26628fc8..e0d13555 100644 --- a/tests/test_app_routers_bond_transfer_approvals_GET.py +++ b/tests/test_app_routers_bond_transfer_approvals_GET.py @@ -22,11 +22,11 @@ import config from app.model.db import ( + IDXTransferApproval, Token, TokenType, - IDXTransferApproval, TransferApprovalHistory, - TransferApprovalOperationType + TransferApprovalOperationType, ) local_tz = timezone(config.TZ) @@ -48,13 +48,33 @@ class TestAppRoutersBondTransferApprovalsGET: test_from_address = "test_from_address" test_to_address = "test_to_address" test_application_datetime = datetime(year=2019, month=9, day=1) - test_application_datetime_str = timezone("UTC").localize(test_application_datetime).astimezone(local_tz).isoformat() + test_application_datetime_str = ( + timezone("UTC") + .localize(test_application_datetime) + .astimezone(local_tz) + .isoformat() + ) test_application_blocktimestamp = datetime(year=2019, month=9, day=2) - test_application_blocktimestamp_str = timezone("UTC").localize(test_application_blocktimestamp).astimezone(local_tz).isoformat() + test_application_blocktimestamp_str = ( + timezone("UTC") + .localize(test_application_blocktimestamp) + .astimezone(local_tz) + .isoformat() + ) test_approval_datetime = datetime(year=2019, month=9, day=3) - test_approval_datetime_str = timezone("UTC").localize(test_approval_datetime).astimezone(local_tz).isoformat() + test_approval_datetime_str = ( + timezone("UTC") + .localize(test_approval_datetime) + .astimezone(local_tz) + .isoformat() + ) test_approval_blocktimestamp = datetime(year=2019, month=9, day=4) - test_approval_blocktimestamp_str = timezone("UTC").localize(test_approval_blocktimestamp).astimezone(local_tz).isoformat() + test_approval_blocktimestamp_str = ( + timezone("UTC") + .localize(test_approval_blocktimestamp) + .astimezone(local_tz) + .isoformat() + ) ########################################################################### # Normal Case @@ -91,9 +111,13 @@ def test_normal_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 1 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = None _idx_transfer_approval.transfer_approved = None db.add(_idx_transfer_approval) @@ -107,9 +131,13 @@ def test_normal_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 1 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = None _idx_transfer_approval.transfer_approved = None db.add(_idx_transfer_approval) @@ -123,9 +151,13 @@ def test_normal_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 1 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = None _idx_transfer_approval.transfer_approved = None db.add(_idx_transfer_approval) @@ -138,13 +170,8 @@ def test_normal_1(self, client, db): # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 0, - "offset": None, - "limit": None, - "total": 0 - }, - "transfer_approvals": [] + "result_set": {"count": 0, "offset": None, "limit": None, "total": 0}, + "transfer_approvals": [], } assert resp.json() == assumed_response @@ -169,7 +196,9 @@ def test_normal_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 1 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -186,7 +215,9 @@ def test_normal_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 11 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -203,9 +234,13 @@ def test_normal_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 21 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = None _idx_transfer_approval.escrow_finished = True # escrow_finished _idx_transfer_approval.transfer_approved = None # event not synchronized @@ -215,7 +250,9 @@ def test_normal_2(self, client, db): _transfer_approval_history.token_address = self.test_token_address_1 _transfer_approval_history.exchange_address = config.ZERO_ADDRESS _transfer_approval_history.application_id = 21 - _transfer_approval_history.operation_type = TransferApprovalOperationType.APPROVE.value + _transfer_approval_history.operation_type = ( + TransferApprovalOperationType.APPROVE.value + ) db.add(_transfer_approval_history) # prepare data: IDXTransferApproval(Approve(transferred)) @@ -227,9 +264,13 @@ def test_normal_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 31 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = None _idx_transfer_approval.escrow_finished = True # escrow_finished _idx_transfer_approval.transfer_approved = True # transferred @@ -244,7 +285,9 @@ def test_normal_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 41 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None # event not synchronized @@ -256,7 +299,9 @@ def test_normal_2(self, client, db): _transfer_approval_history.token_address = self.test_token_address_1 _transfer_approval_history.exchange_address = config.ZERO_ADDRESS _transfer_approval_history.application_id = 41 - _transfer_approval_history.operation_type = TransferApprovalOperationType.CANCEL.value + _transfer_approval_history.operation_type = ( + TransferApprovalOperationType.CANCEL.value + ) db.add(_transfer_approval_history) # prepare data: IDXTransferApproval(Cancel(canceled)) @@ -268,7 +313,9 @@ def test_normal_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 51 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = True # cancelled @@ -286,12 +333,7 @@ def test_normal_2(self, client, db): # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 1, - "offset": None, - "limit": None, - "total": 1 - }, + "result_set": {"count": 1, "offset": None, "limit": None, "total": 1}, "transfer_approvals": [ { "issuer_address": self.test_issuer_address_1, @@ -302,7 +344,7 @@ def test_normal_2(self, client, db): "transferred_count": 2, "canceled_count": 2, }, - ] + ], } assert resp.json() == assumed_response @@ -346,7 +388,9 @@ def test_normal_3_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 1 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -362,7 +406,9 @@ def test_normal_3_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 11 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -378,7 +424,9 @@ def test_normal_3_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 12 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.escrow_finished = True # escrow_finished @@ -393,7 +441,9 @@ def test_normal_3_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 31 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = True # cancelled @@ -410,7 +460,9 @@ def test_normal_3_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 1 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -427,7 +479,9 @@ def test_normal_3_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 1 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -437,21 +491,13 @@ def test_normal_3_1(self, client, db): # request target API resp = client.get( - self.base_url, - headers={ - "issuer-address": self.test_issuer_address_1 - } + self.base_url, headers={"issuer-address": self.test_issuer_address_1} ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 2, - "offset": None, - "limit": None, - "total": 2 - }, + "result_set": {"count": 2, "offset": None, "limit": None, "total": 2}, "transfer_approvals": [ { "issuer_address": self.test_issuer_address_1, @@ -471,7 +517,7 @@ def test_normal_3_1(self, client, db): "transferred_count": 0, "canceled_count": 0, }, - ] + ], } assert resp.json() == assumed_response @@ -515,7 +561,9 @@ def test_normal_3_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 1 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -531,7 +579,9 @@ def test_normal_3_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 11 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -547,7 +597,9 @@ def test_normal_3_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 12 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.escrow_finished = True # escrow_finished @@ -562,7 +614,9 @@ def test_normal_3_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 31 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = True # cancelled @@ -579,7 +633,9 @@ def test_normal_3_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 1 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -596,7 +652,9 @@ def test_normal_3_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 1 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -612,12 +670,7 @@ def test_normal_3_2(self, client, db): # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 3, - "offset": None, - "limit": None, - "total": 3 - }, + "result_set": {"count": 3, "offset": None, "limit": None, "total": 3}, "transfer_approvals": [ { "issuer_address": self.test_issuer_address_1, @@ -646,7 +699,7 @@ def test_normal_3_2(self, client, db): "transferred_count": 0, "canceled_count": 0, }, - ] + ], } assert resp.json() == assumed_response @@ -698,7 +751,9 @@ def test_normal_4(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 1 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -715,7 +770,9 @@ def test_normal_4(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 1 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -732,7 +789,9 @@ def test_normal_4(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 1 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -749,7 +808,9 @@ def test_normal_4(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 1 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -763,18 +824,13 @@ def test_normal_4(self, client, db): params={ "limit": 2, "offset": 1, - } + }, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 4, - "offset": 1, - "limit": 2, - "total": 4 - }, + "result_set": {"count": 4, "offset": 1, "limit": 2, "total": 4}, "transfer_approvals": [ { "issuer_address": self.test_issuer_address_1, @@ -794,7 +850,7 @@ def test_normal_4(self, client, db): "transferred_count": 0, "canceled_count": 0, }, - ] + ], } assert resp.json() == assumed_response @@ -812,16 +868,13 @@ def test_error_1(self, client, db): params={ "offset": "c", "limit": "d", - } + }, ) # assertion assert resp.status_code == 422 assumed_response = { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["query", "offset"], @@ -833,6 +886,6 @@ def test_error_1(self, client, db): "msg": "value is not a valid integer", "type": "type_error.integer", }, - ] + ], } assert resp.json() == assumed_response diff --git a/tests/test_app_routers_bond_transfer_approvals_{token_Address}_GET.py b/tests/test_app_routers_bond_transfer_approvals_{token_Address}_GET.py index 399870f1..4e9534b9 100644 --- a/tests/test_app_routers_bond_transfer_approvals_{token_Address}_GET.py +++ b/tests/test_app_routers_bond_transfer_approvals_{token_Address}_GET.py @@ -22,18 +22,17 @@ import config from app.model.db import ( + IDXTransferApproval, Token, TokenType, - IDXTransferApproval, TransferApprovalHistory, - TransferApprovalOperationType + TransferApprovalOperationType, ) local_tz = timezone(config.TZ) class TestAppRoutersBondTransferApprovalsTokenAddressGET: - # target API endpoint base_url = "/bond/transfer_approvals/{}" @@ -45,17 +44,47 @@ class TestAppRoutersBondTransferApprovalsTokenAddressGET: test_from_address = "test_from_address" test_to_address = "test_to_address" test_application_datetime = datetime(year=2019, month=9, day=1) - test_application_datetime_str = timezone("UTC").localize(test_application_datetime).astimezone(local_tz).isoformat() + test_application_datetime_str = ( + timezone("UTC") + .localize(test_application_datetime) + .astimezone(local_tz) + .isoformat() + ) test_application_datetime_2 = datetime(year=2019, month=10, day=1) - test_application_datetime_str_2 = timezone("UTC").localize(test_application_datetime_2).astimezone(local_tz).isoformat() + test_application_datetime_str_2 = ( + timezone("UTC") + .localize(test_application_datetime_2) + .astimezone(local_tz) + .isoformat() + ) test_application_blocktimestamp = datetime(year=2019, month=9, day=2) - test_application_blocktimestamp_str = timezone("UTC").localize(test_application_blocktimestamp).astimezone(local_tz).isoformat() + test_application_blocktimestamp_str = ( + timezone("UTC") + .localize(test_application_blocktimestamp) + .astimezone(local_tz) + .isoformat() + ) test_approval_datetime = datetime(year=2019, month=9, day=3) - test_approval_datetime_str = timezone("UTC").localize(test_approval_datetime).astimezone(local_tz).isoformat() + test_approval_datetime_str = ( + timezone("UTC") + .localize(test_approval_datetime) + .astimezone(local_tz) + .isoformat() + ) test_approval_datetime_2 = datetime(year=2019, month=10, day=3) - test_approval_datetime_str_2 = timezone("UTC").localize(test_approval_datetime_2).astimezone(local_tz).isoformat() + test_approval_datetime_str_2 = ( + timezone("UTC") + .localize(test_approval_datetime_2) + .astimezone(local_tz) + .isoformat() + ) test_approval_blocktimestamp = datetime(year=2019, month=9, day=4) - test_approval_blocktimestamp_str = timezone("UTC").localize(test_approval_blocktimestamp).astimezone(local_tz).isoformat() + test_approval_blocktimestamp_str = ( + timezone("UTC") + .localize(test_approval_blocktimestamp) + .astimezone(local_tz) + .isoformat() + ) ########################################################################### # Normal Case @@ -74,20 +103,13 @@ def test_normal_1_1(self, client, db): db.add(_token) # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 0, - "offset": None, - "limit": None, - "total": 0 - }, - "transfer_approval_history": [] + "result_set": {"count": 0, "offset": None, "limit": None, "total": 0}, + "transfer_approval_history": [], } assert resp.json() == assumed_response @@ -113,7 +135,9 @@ def test_normal_1_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = False @@ -121,19 +145,12 @@ def test_normal_1_2(self, client, db): db.add(_idx_transfer_approval) # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 3, - "offset": None, - "limit": None, - "total": 3 - }, + "result_set": {"count": 3, "offset": None, "limit": None, "total": 3}, "transfer_approval_history": [ { "id": 3, @@ -189,7 +206,7 @@ def test_normal_1_2(self, client, db): "status": 0, "issuer_cancelable": True, }, - ] + ], } assert resp.json() == assumed_response @@ -215,9 +232,13 @@ def test_normal_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = False _idx_transfer_approval.transfer_approved = False db.add(_idx_transfer_approval) @@ -230,12 +251,7 @@ def test_normal_2(self, client, db): # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 3, - "offset": 1, - "limit": 1, - "total": 3 - }, + "result_set": {"count": 3, "offset": 1, "limit": 1, "total": 3}, "transfer_approval_history": [ { "id": 2, @@ -255,7 +271,7 @@ def test_normal_2(self, client, db): "status": 0, "issuer_cancelable": True, } - ] + ], } assert resp.json() == assumed_response @@ -276,35 +292,36 @@ def test_normal_3(self, client, db): _idx_transfer_approval = IDXTransferApproval() _idx_transfer_approval.token_address = self.test_token_address if i == 1: - _idx_transfer_approval.exchange_address = self.test_exchange_address + "0" + _idx_transfer_approval.exchange_address = ( + self.test_exchange_address + "0" + ) else: - _idx_transfer_approval.exchange_address = self.test_exchange_address + "1" + _idx_transfer_approval.exchange_address = ( + self.test_exchange_address + "1" + ) _idx_transfer_approval.application_id = i _idx_transfer_approval.from_address = self.test_from_address _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = False _idx_transfer_approval.transfer_approved = False db.add(_idx_transfer_approval) # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 3, - "offset": None, - "limit": None, - "total": 3 - }, + "result_set": {"count": 3, "offset": None, "limit": None, "total": 3}, "transfer_approval_history": [ { "id": 3, @@ -360,7 +377,7 @@ def test_normal_3(self, client, db): "status": 0, "issuer_cancelable": False, }, - ] + ], } assert resp.json() == assumed_response @@ -387,9 +404,13 @@ def test_normal_4_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = False _idx_transfer_approval.transfer_approved = False db.add(_idx_transfer_approval) @@ -397,20 +418,13 @@ def test_normal_4_1(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "from_address": self.test_from_address + "1" - } + params={"from_address": self.test_from_address + "1"}, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 1, - "offset": None, - "limit": None, - "total": 3 - }, + "result_set": {"count": 1, "offset": None, "limit": None, "total": 3}, "transfer_approval_history": [ { "id": 2, @@ -430,7 +444,7 @@ def test_normal_4_1(self, client, db): "status": 0, "issuer_cancelable": True, } - ] + ], } assert resp.json() == assumed_response @@ -457,9 +471,13 @@ def test_normal_4_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address + str(i) _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = False _idx_transfer_approval.transfer_approved = False db.add(_idx_transfer_approval) @@ -467,20 +485,13 @@ def test_normal_4_2(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "to_address": self.test_to_address + "1" - } + params={"to_address": self.test_to_address + "1"}, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 1, - "offset": None, - "limit": None, - "total": 3 - }, + "result_set": {"count": 1, "offset": None, "limit": None, "total": 3}, "transfer_approval_history": [ { "id": 2, @@ -500,7 +511,7 @@ def test_normal_4_2(self, client, db): "status": 0, "issuer_cancelable": True, } - ] + ], } assert resp.json() == assumed_response @@ -527,7 +538,9 @@ def test_normal_4_3_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) if i == 0: # unapproved _idx_transfer_approval.exchange_address = config.ZERO_ADDRESS _idx_transfer_approval.cancelled = None @@ -557,21 +570,13 @@ def test_normal_4_3_1(self, client, db): # request target API resp = client.get( - self.base_url.format(self.test_token_address), - params={ - "status": 0 - } + self.base_url.format(self.test_token_address), params={"status": 0} ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 1, - "offset": None, - "limit": None, - "total": 5 - }, + "result_set": {"count": 1, "offset": None, "limit": None, "total": 5}, "transfer_approval_history": [ { "id": 1, @@ -591,7 +596,7 @@ def test_normal_4_3_1(self, client, db): "status": 0, "issuer_cancelable": True, }, - ] + ], } assert resp.json() == assumed_response @@ -618,7 +623,9 @@ def test_normal_4_3_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) if i == 0: # unapproved _idx_transfer_approval.exchange_address = config.ZERO_ADDRESS _idx_transfer_approval.cancelled = None @@ -648,21 +655,13 @@ def test_normal_4_3_2(self, client, db): # request target API resp = client.get( - self.base_url.format(self.test_token_address), - params={ - "status": 1 - } + self.base_url.format(self.test_token_address), params={"status": 1} ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 1, - "offset": None, - "limit": None, - "total": 5 - }, + "result_set": {"count": 1, "offset": None, "limit": None, "total": 5}, "transfer_approval_history": [ { "id": 2, @@ -682,7 +681,7 @@ def test_normal_4_3_2(self, client, db): "status": 1, "issuer_cancelable": True, } - ] + ], } assert resp.json() == assumed_response @@ -709,7 +708,9 @@ def test_normal_4_3_3(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) if i == 0: # unapproved _idx_transfer_approval.exchange_address = config.ZERO_ADDRESS _idx_transfer_approval.cancelled = None @@ -726,7 +727,9 @@ def test_normal_4_3_3(self, client, db): _idx_transfer_approval.escrow_finished = True _idx_transfer_approval.transfer_approved = True _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) elif i == 3: # transferred_2 _idx_transfer_approval.exchange_address = config.ZERO_ADDRESS _idx_transfer_approval.cancelled = None @@ -736,7 +739,9 @@ def test_normal_4_3_3(self, client, db): _transfer_approval_history.token_address = self.test_token_address _transfer_approval_history.exchange_address = config.ZERO_ADDRESS _transfer_approval_history.application_id = i - _transfer_approval_history.operation_type = TransferApprovalOperationType.APPROVE.value + _transfer_approval_history.operation_type = ( + TransferApprovalOperationType.APPROVE.value + ) db.add(_transfer_approval_history) elif i == 4: # transferred_3 _idx_transfer_approval.exchange_address = config.ZERO_ADDRESS @@ -744,7 +749,9 @@ def test_normal_4_3_3(self, client, db): _idx_transfer_approval.escrow_finished = None _idx_transfer_approval.transfer_approved = True _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) elif i == 5: # canceled-1 _idx_transfer_approval.exchange_address = config.ZERO_ADDRESS _idx_transfer_approval.cancelled = None @@ -754,7 +761,9 @@ def test_normal_4_3_3(self, client, db): _transfer_approval_history.token_address = self.test_token_address _transfer_approval_history.exchange_address = config.ZERO_ADDRESS _transfer_approval_history.application_id = i - _transfer_approval_history.operation_type = TransferApprovalOperationType.CANCEL.value + _transfer_approval_history.operation_type = ( + TransferApprovalOperationType.CANCEL.value + ) db.add(_transfer_approval_history) elif i == 6: # canceled-2 _idx_transfer_approval.exchange_address = config.ZERO_ADDRESS @@ -765,21 +774,13 @@ def test_normal_4_3_3(self, client, db): # request target API resp = client.get( - self.base_url.format(self.test_token_address), - params={ - "status": 2 - } + self.base_url.format(self.test_token_address), params={"status": 2} ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 3, - "offset": None, - "limit": None, - "total": 7 - }, + "result_set": {"count": 3, "offset": None, "limit": None, "total": 7}, "transfer_approval_history": [ { "id": 5, @@ -834,8 +835,8 @@ def test_normal_4_3_3(self, client, db): "transfer_approved": True, "status": 2, "issuer_cancelable": False, - } - ] + }, + ], } assert resp.json() == assumed_response @@ -862,7 +863,9 @@ def test_normal_4_3_4(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) if i == 0: # unapproved _idx_transfer_approval.exchange_address = config.ZERO_ADDRESS _idx_transfer_approval.cancelled = None @@ -892,7 +895,9 @@ def test_normal_4_3_4(self, client, db): _transfer_approval_history.token_address = self.test_token_address _transfer_approval_history.exchange_address = config.ZERO_ADDRESS _transfer_approval_history.application_id = i - _transfer_approval_history.operation_type = TransferApprovalOperationType.CANCEL.value + _transfer_approval_history.operation_type = ( + TransferApprovalOperationType.CANCEL.value + ) db.add(_transfer_approval_history) elif i == 5: # canceled-2 _idx_transfer_approval.exchange_address = config.ZERO_ADDRESS @@ -904,21 +909,13 @@ def test_normal_4_3_4(self, client, db): # request target API resp = client.get( - self.base_url.format(self.test_token_address), - params={ - "status": 3 - } + self.base_url.format(self.test_token_address), params={"status": 3} ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 2, - "offset": None, - "limit": None, - "total": 6 - }, + "result_set": {"count": 2, "offset": None, "limit": None, "total": 6}, "transfer_approval_history": [ { "id": 6, @@ -955,8 +952,8 @@ def test_normal_4_3_4(self, client, db): "transfer_approved": False, "status": 3, "issuer_cancelable": True, - } - ] + }, + ], } assert resp.json() == assumed_response @@ -983,7 +980,9 @@ def test_normal_4_3_5(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) if i == 0: # unapproved _idx_transfer_approval.exchange_address = config.ZERO_ADDRESS _idx_transfer_approval.cancelled = None @@ -1008,7 +1007,9 @@ def test_normal_4_3_5(self, client, db): _transfer_approval_history.token_address = self.test_token_address _transfer_approval_history.exchange_address = config.ZERO_ADDRESS _transfer_approval_history.application_id = i - _transfer_approval_history.operation_type = TransferApprovalOperationType.APPROVE.value + _transfer_approval_history.operation_type = ( + TransferApprovalOperationType.APPROVE.value + ) db.add(_transfer_approval_history) elif i == 4: # transferred_3 _idx_transfer_approval.exchange_address = config.ZERO_ADDRESS @@ -1024,7 +1025,9 @@ def test_normal_4_3_5(self, client, db): _transfer_approval_history.token_address = self.test_token_address _transfer_approval_history.exchange_address = config.ZERO_ADDRESS _transfer_approval_history.application_id = i - _transfer_approval_history.operation_type = TransferApprovalOperationType.CANCEL.value + _transfer_approval_history.operation_type = ( + TransferApprovalOperationType.CANCEL.value + ) db.add(_transfer_approval_history) elif i == 6: # canceled-2 _idx_transfer_approval.exchange_address = config.ZERO_ADDRESS @@ -1035,21 +1038,13 @@ def test_normal_4_3_5(self, client, db): # request target API resp = client.get( - self.base_url.format(self.test_token_address), - params={ - "status": [0, 1] - } + self.base_url.format(self.test_token_address), params={"status": [0, 1]} ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 2, - "offset": None, - "limit": None, - "total": 7 - }, + "result_set": {"count": 2, "offset": None, "limit": None, "total": 7}, "transfer_approval_history": [ { "id": 2, @@ -1087,7 +1082,7 @@ def test_normal_4_3_5(self, client, db): "status": 0, "issuer_cancelable": True, }, - ] + ], } assert resp.json() == assumed_response @@ -1114,9 +1109,13 @@ def test_normal_5_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = False _idx_transfer_approval.transfer_approved = False db.add(_idx_transfer_approval) @@ -1124,21 +1123,13 @@ def test_normal_5_1(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "sort_item": "id", - "sort_order": 0 - } + params={"sort_item": "id", "sort_order": 0}, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 3, - "offset": None, - "limit": None, - "total": 3 - }, + "result_set": {"count": 3, "offset": None, "limit": None, "total": 3}, "transfer_approval_history": [ { "id": 1, @@ -1194,7 +1185,7 @@ def test_normal_5_1(self, client, db): "status": 0, "issuer_cancelable": False, }, - ] + ], } assert resp.json() == assumed_response @@ -1222,9 +1213,13 @@ def test_normal_5_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = False _idx_transfer_approval.transfer_approved = False db.add(_idx_transfer_approval) @@ -1232,21 +1227,13 @@ def test_normal_5_2(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "sort_item": "exchange_address", - "sort_order": 1 - } + params={"sort_item": "exchange_address", "sort_order": 1}, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 4, - "offset": None, - "limit": None, - "total": 4 - }, + "result_set": {"count": 4, "offset": None, "limit": None, "total": 4}, "transfer_approval_history": [ { "id": 3, @@ -1320,7 +1307,7 @@ def test_normal_5_2(self, client, db): "status": 0, "issuer_cancelable": True, }, - ] + ], } assert resp.json() == assumed_response @@ -1348,9 +1335,13 @@ def test_normal_5_3(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = False _idx_transfer_approval.transfer_approved = False db.add(_idx_transfer_approval) @@ -1358,21 +1349,13 @@ def test_normal_5_3(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "sort_item": "application_id", - "sort_order": 0 - } + params={"sort_item": "application_id", "sort_order": 0}, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 4, - "offset": None, - "limit": None, - "total": 4 - }, + "result_set": {"count": 4, "offset": None, "limit": None, "total": 4}, "transfer_approval_history": [ { "id": 2, @@ -1446,7 +1429,7 @@ def test_normal_5_3(self, client, db): "status": 0, "issuer_cancelable": False, }, - ] + ], } assert resp.json() == assumed_response @@ -1469,13 +1452,19 @@ def test_normal_5_4(self, client, db): _idx_transfer_approval.token_address = self.test_token_address _idx_transfer_approval.exchange_address = self.test_exchange_address _idx_transfer_approval.application_id = i - _idx_transfer_approval.from_address = self.test_from_address + str(int((3 - i) / 2)) + _idx_transfer_approval.from_address = self.test_from_address + str( + int((3 - i) / 2) + ) _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = False _idx_transfer_approval.transfer_approved = False db.add(_idx_transfer_approval) @@ -1483,21 +1472,13 @@ def test_normal_5_4(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "sort_item": "from_address", - "sort_order": 1 - } + params={"sort_item": "from_address", "sort_order": 1}, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 4, - "offset": None, - "limit": None, - "total": 4 - }, + "result_set": {"count": 4, "offset": None, "limit": None, "total": 4}, "transfer_approval_history": [ { "id": 2, @@ -1571,7 +1552,7 @@ def test_normal_5_4(self, client, db): "status": 0, "issuer_cancelable": False, }, - ] + ], } assert resp.json() == assumed_response @@ -1598,9 +1579,13 @@ def test_normal_5_5(self, client, db): _idx_transfer_approval.to_address = self.test_to_address + str(int(i / 2)) _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = False _idx_transfer_approval.transfer_approved = False db.add(_idx_transfer_approval) @@ -1608,21 +1593,13 @@ def test_normal_5_5(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "sort_item": "to_address", - "sort_order": 0 - } + params={"sort_item": "to_address", "sort_order": 0}, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 4, - "offset": None, - "limit": None, - "total": 4 - }, + "result_set": {"count": 4, "offset": None, "limit": None, "total": 4}, "transfer_approval_history": [ { "id": 2, @@ -1696,7 +1673,7 @@ def test_normal_5_5(self, client, db): "status": 0, "issuer_cancelable": False, }, - ] + ], } assert resp.json() == assumed_response @@ -1723,9 +1700,13 @@ def test_normal_5_6(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = int((3 - i) / 2) _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = False _idx_transfer_approval.transfer_approved = False db.add(_idx_transfer_approval) @@ -1733,21 +1714,13 @@ def test_normal_5_6(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "sort_item": "amount", - "sort_order": 1 - } + params={"sort_item": "amount", "sort_order": 1}, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 4, - "offset": None, - "limit": None, - "total": 4 - }, + "result_set": {"count": 4, "offset": None, "limit": None, "total": 4}, "transfer_approval_history": [ { "id": 2, @@ -1821,7 +1794,7 @@ def test_normal_5_6(self, client, db): "status": 0, "issuer_cancelable": False, }, - ] + ], } assert resp.json() == assumed_response @@ -1848,12 +1821,20 @@ def test_normal_5_7(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i if i % 2 == 0: - _idx_transfer_approval.application_datetime = self.test_application_datetime + _idx_transfer_approval.application_datetime = ( + self.test_application_datetime + ) else: - _idx_transfer_approval.application_datetime = self.test_application_datetime_2 - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_datetime = ( + self.test_application_datetime_2 + ) + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = False _idx_transfer_approval.transfer_approved = False db.add(_idx_transfer_approval) @@ -1861,21 +1842,13 @@ def test_normal_5_7(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "sort_item": "application_datetime", - "sort_order": 0 - } + params={"sort_item": "application_datetime", "sort_order": 0}, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 4, - "offset": None, - "limit": None, - "total": 4 - }, + "result_set": {"count": 4, "offset": None, "limit": None, "total": 4}, "transfer_approval_history": [ { "id": 3, @@ -1949,7 +1922,7 @@ def test_normal_5_7(self, client, db): "status": 0, "issuer_cancelable": False, }, - ] + ], } assert resp.json() == assumed_response @@ -1976,12 +1949,16 @@ def test_normal_5_8(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) if i % 2 == 0: _idx_transfer_approval.approval_datetime = self.test_approval_datetime else: _idx_transfer_approval.approval_datetime = self.test_approval_datetime_2 - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = False _idx_transfer_approval.transfer_approved = False db.add(_idx_transfer_approval) @@ -1989,21 +1966,13 @@ def test_normal_5_8(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "sort_item": "approval_datetime", - "sort_order": 1 - } + params={"sort_item": "approval_datetime", "sort_order": 1}, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 4, - "offset": None, - "limit": None, - "total": 4 - }, + "result_set": {"count": 4, "offset": None, "limit": None, "total": 4}, "transfer_approval_history": [ { "id": 4, @@ -2077,7 +2046,7 @@ def test_normal_5_8(self, client, db): "status": 0, "issuer_cancelable": False, }, - ] + ], } assert resp.json() == assumed_response @@ -2103,7 +2072,9 @@ def test_normal_5_9(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) if i == 0 or i == 1: # unapproved _idx_transfer_approval.approval_datetime = None @@ -2126,7 +2097,9 @@ def test_normal_5_9(self, client, db): _idx_transfer_approval.escrow_finished = None _idx_transfer_approval.transfer_approved = True _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) else: # canceled _idx_transfer_approval.approval_datetime = None @@ -2139,21 +2112,13 @@ def test_normal_5_9(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "sort_item": "status", - "sort_order": 0 - } + params={"sort_item": "status", "sort_order": 0}, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 8, - "offset": None, - "limit": None, - "total": 8 - }, + "result_set": {"count": 8, "offset": None, "limit": None, "total": 8}, "transfer_approval_history": [ { "id": 2, @@ -2299,7 +2264,7 @@ def test_normal_5_9(self, client, db): "status": 3, "issuer_cancelable": True, }, - ] + ], } assert resp.json() == assumed_response @@ -2318,16 +2283,13 @@ def test_error_1_1(self, client, db): "status": "a", "offset": "c", "limit": "d", - } + }, ) # assertion assert resp.status_code == 422 assumed_response = { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["query", "status", 0], @@ -2344,7 +2306,7 @@ def test_error_1_1(self, client, db): "msg": "value is not a valid integer", "type": "type_error.integer", }, - ] + ], } assert resp.json() == assumed_response @@ -2357,16 +2319,13 @@ def test_error_1_2(self, client, db): self.base_url.format(self.test_token_address), params={ "status": -1, - } + }, ) # assertion assert resp.status_code == 422 assumed_response = { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["query", "status", 0], @@ -2374,7 +2333,7 @@ def test_error_1_2(self, client, db): "msg": "ensure this value is greater than or equal to 0", "type": "value_error.number.not_ge", }, - ] + ], } assert resp.json() == assumed_response @@ -2387,16 +2346,13 @@ def test_error_1_3(self, client, db): self.base_url.format(self.test_token_address), params={ "status": 4, - } + }, ) # assertion assert resp.status_code == 422 assumed_response = { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["query", "status", 0], @@ -2404,7 +2360,7 @@ def test_error_1_3(self, client, db): "msg": "ensure this value is less than or equal to 3", "type": "value_error.number.not_le", }, - ] + ], } assert resp.json() == assumed_response @@ -2412,18 +2368,13 @@ def test_error_1_3(self, client, db): # token not found def test_error_1(self, client, db): # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 404 assumed_response = { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } assert resp.json() == assumed_response @@ -2441,16 +2392,11 @@ def test_error_2(self, client, db): db.add(_token) # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } diff --git a/tests/test_app_routers_bond_transfer_approvals_{token_Address}_{id}_GET.py b/tests/test_app_routers_bond_transfer_approvals_{token_Address}_{id}_GET.py index f57bedc3..1e574abe 100644 --- a/tests/test_app_routers_bond_transfer_approvals_{token_Address}_{id}_GET.py +++ b/tests/test_app_routers_bond_transfer_approvals_{token_Address}_{id}_GET.py @@ -22,11 +22,11 @@ import config from app.model.db import ( + IDXTransferApproval, Token, TokenType, - IDXTransferApproval, TransferApprovalHistory, - TransferApprovalOperationType + TransferApprovalOperationType, ) local_tz = timezone(config.TZ) @@ -44,13 +44,33 @@ class TestAppRoutersBondTransferApprovalsTokenAddressIdGET: test_from_address = "test_from_address" test_to_address = "test_to_address" test_application_datetime = datetime(year=2019, month=9, day=1) - test_application_datetime_str = timezone("UTC").localize(test_application_datetime).astimezone(local_tz).isoformat() + test_application_datetime_str = ( + timezone("UTC") + .localize(test_application_datetime) + .astimezone(local_tz) + .isoformat() + ) test_application_blocktimestamp = datetime(year=2019, month=9, day=2) - test_application_blocktimestamp_str = timezone("UTC").localize(test_application_blocktimestamp).astimezone(local_tz).isoformat() + test_application_blocktimestamp_str = ( + timezone("UTC") + .localize(test_application_blocktimestamp) + .astimezone(local_tz) + .isoformat() + ) test_approval_datetime = datetime(year=2019, month=9, day=3) - test_approval_datetime_str = timezone("UTC").localize(test_approval_datetime).astimezone(local_tz).isoformat() + test_approval_datetime_str = ( + timezone("UTC") + .localize(test_approval_datetime) + .astimezone(local_tz) + .isoformat() + ) test_approval_blocktimestamp = datetime(year=2019, month=9, day=4) - test_approval_blocktimestamp_str = timezone("UTC").localize(test_approval_blocktimestamp).astimezone(local_tz).isoformat() + test_approval_blocktimestamp_str = ( + timezone("UTC") + .localize(test_approval_blocktimestamp) + .astimezone(local_tz) + .isoformat() + ) ########################################################################### # Normal Case @@ -78,7 +98,9 @@ def test_normal_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -87,9 +109,7 @@ def test_normal_1(self, client, db): db.add(_idx_transfer_approval) # request target API - resp = client.get( - self.base_url.format(self.test_token_address, id) - ) + resp = client.get(self.base_url.format(self.test_token_address, id)) # assertion assert resp.status_code == 200 @@ -135,7 +155,9 @@ def test_normal_2_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -151,9 +173,7 @@ def test_normal_2_1(self, client, db): db.add(_cancel_op) # request target API - resp = client.get( - self.base_url.format(self.test_token_address, id) - ) + resp = client.get(self.base_url.format(self.test_token_address, id)) # assertion assert resp.status_code == 200 @@ -198,7 +218,9 @@ def test_normal_2_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = True @@ -207,9 +229,7 @@ def test_normal_2_2(self, client, db): db.add(_idx_transfer_approval) # request target API - resp = client.get( - self.base_url.format(self.test_token_address, id) - ) + resp = client.get(self.base_url.format(self.test_token_address, id)) # assertion assert resp.status_code == 200 @@ -254,18 +274,18 @@ def test_normal_3(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None - _idx_transfer_approval.approval_blocktimestamp = None + _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None _idx_transfer_approval.escrow_finished = True _idx_transfer_approval.transfer_approved = False db.add(_idx_transfer_approval) # request target API - resp = client.get( - self.base_url.format(self.test_token_address, id) - ) + resp = client.get(self.base_url.format(self.test_token_address, id)) # assertion assert resp.status_code == 200 @@ -311,9 +331,13 @@ def test_normal_4_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = None _idx_transfer_approval.escrow_finished = True _idx_transfer_approval.transfer_approved = None @@ -327,9 +351,7 @@ def test_normal_4_1(self, client, db): db.add(_approval_op) # request target API - resp = client.get( - self.base_url.format(self.test_token_address, id) - ) + resp = client.get(self.base_url.format(self.test_token_address, id)) # assertion assert resp.status_code == 200 @@ -374,18 +396,20 @@ def test_normal_4_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = None _idx_transfer_approval.escrow_finished = True _idx_transfer_approval.transfer_approved = True db.add(_idx_transfer_approval) # request target API - resp = client.get( - self.base_url.format(self.test_token_address, id) - ) + resp = client.get(self.base_url.format(self.test_token_address, id)) # assertion assert resp.status_code == 200 @@ -418,18 +442,13 @@ def test_error_1(self, client, db): id = 10 # request target API - resp = client.get( - self.base_url.format(self.test_token_address, id) - ) + resp = client.get(self.base_url.format(self.test_token_address, id)) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # @@ -448,18 +467,13 @@ def test_error_2(self, client, db): db.add(_token) # request target API - resp = client.get( - self.base_url.format(self.test_token_address, id) - ) + resp = client.get(self.base_url.format(self.test_token_address, id)) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } # @@ -478,16 +492,11 @@ def test_error_3(self, client, db): db.add(_token) # request target API - resp = client.get( - self.base_url.format(self.test_token_address, id) - ) + resp = client.get(self.base_url.format(self.test_token_address, id)) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "transfer approval not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "transfer approval not found", } diff --git a/tests/test_app_routers_bond_transfer_approvals_{token_Address}_{id}_POST.py b/tests/test_app_routers_bond_transfer_approvals_{token_Address}_{id}_POST.py index d2a6b8c7..0e4508c4 100644 --- a/tests/test_app_routers_bond_transfer_approvals_{token_Address}_{id}_POST.py +++ b/tests/test_app_routers_bond_transfer_approvals_{token_Address}_{id}_POST.py @@ -17,36 +17,29 @@ SPDX-License-Identifier: Apache-2.0 """ import hashlib - -import pytest -from unittest import mock -from unittest.mock import ( - ANY, - MagicMock -) from datetime import datetime +from unittest import mock +from unittest.mock import ANY, MagicMock +import pytest from pytz import timezone import config +from app.exceptions import ContractRevertError, SendTransactionError +from app.model.blockchain.tx_params.ibet_security_token_escrow import ( + ApproveTransferParams as EscrowApproveTransferParams, +) +from app.model.blockchain.tx_params.ibet_straight_bond import ApproveTransferParams from app.model.db import ( Account, AuthToken, + IDXTransferApproval, Token, TokenType, - IDXTransferApproval, TransferApprovalHistory, - TransferApprovalOperationType -) -from app.model.blockchain.tx_params.ibet_straight_bond import ( - ApproveTransferParams, -) -from app.model.blockchain.tx_params.ibet_security_token_escrow import ( - ApproveTransferParams as EscrowApproveTransferParams, + TransferApprovalOperationType, ) from app.utils.e2ee_utils import E2EEUtils -from app.exceptions import SendTransactionError, ContractRevertError - from tests.account_config import config_eth_account local_tz = timezone(config.TZ) @@ -63,10 +56,19 @@ class TestAppRoutersBondTransferApprovalsTokenAddressIdPOST: test_from_address = "test_from_address" test_to_address = "test_to_address" test_application_datetime = datetime(year=2019, month=9, day=1) - test_application_datetime_str = timezone("UTC").localize(test_application_datetime).astimezone(local_tz).isoformat() + test_application_datetime_str = ( + timezone("UTC") + .localize(test_application_datetime) + .astimezone(local_tz) + .isoformat() + ) test_application_blocktimestamp = datetime(year=2019, month=9, day=2) - test_application_blocktimestamp_str = timezone("UTC").localize(test_application_blocktimestamp).astimezone( - local_tz).isoformat() + test_application_blocktimestamp_str = ( + timezone("UTC") + .localize(test_application_blocktimestamp) + .astimezone(local_tz) + .isoformat() + ) test_approval_datetime = datetime(year=2019, month=9, day=3) test_approval_blocktimestamp = datetime(year=2019, month=9, day=4) @@ -77,7 +79,7 @@ class TestAppRoutersBondTransferApprovalsTokenAddressIdPOST: # # APPROVE # token - @pytest.mark.freeze_time('2021-04-27 12:34:56') + @pytest.mark.freeze_time("2021-04-27 12:34:56") def test_normal_1_1(self, client, db): issuer = config_eth_account("user1") issuer_address = issuer["address"] @@ -107,7 +109,9 @@ def test_normal_1_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -116,38 +120,35 @@ def test_normal_1_1(self, client, db): # mock IbetSecurityTokenContract_approve_transfer = mock.patch( target="app.model.blockchain.token.IbetSecurityTokenInterface.approve_transfer", - return_value=("test_tx_hash", {"status": 1}) + return_value=("test_tx_hash", {"status": 1}), ) # request target API with IbetSecurityTokenContract_approve_transfer as mock_transfer: resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "approve" - }, + json={"operation_type": "approve"}, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # Assertion assert resp.status_code == 200 assert resp.json() is None - _expected = { - "application_id": 100, - "data": str(datetime.utcnow().timestamp()) - } + _expected = {"application_id": 100, "data": str(datetime.utcnow().timestamp())} mock_transfer.assert_called_once_with( data=ApproveTransferParams(**_expected), tx_from=issuer_address, - private_key=ANY + private_key=ANY, ) - approval_op_list: list[TransferApprovalHistory] = db.query(TransferApprovalHistory).all() + approval_op_list: list[TransferApprovalHistory] = db.query( + TransferApprovalHistory + ).all() assert len(approval_op_list) == 1 approval_op = approval_op_list[0] assert approval_op.token_address == self.test_token_address @@ -158,7 +159,7 @@ def test_normal_1_1(self, client, db): # # APPROVE # exchange - @pytest.mark.freeze_time('2021-04-27 12:34:56') + @pytest.mark.freeze_time("2021-04-27 12:34:56") def test_normal_1_2(self, client, db): issuer = config_eth_account("user1") issuer_address = issuer["address"] @@ -188,7 +189,9 @@ def test_normal_1_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -198,38 +201,35 @@ def test_normal_1_2(self, client, db): # mock IbetSecurityTokenEscrow_approve_transfer = mock.patch( target="app.model.blockchain.exchange.IbetSecurityTokenEscrow.approve_transfer", - return_value=("test_tx_hash", {"status": 1}) + return_value=("test_tx_hash", {"status": 1}), ) # request target API with IbetSecurityTokenEscrow_approve_transfer as mock_transfer: resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "approve" - }, + json={"operation_type": "approve"}, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # Assertion assert resp.status_code == 200 assert resp.json() is None - _expected = { - "escrow_id": 100, - "data": str(datetime.utcnow().timestamp()) - } + _expected = {"escrow_id": 100, "data": str(datetime.utcnow().timestamp())} mock_transfer.assert_called_once_with( data=EscrowApproveTransferParams(**_expected), tx_from=issuer_address, - private_key=ANY + private_key=ANY, ) - approval_op_list: list[TransferApprovalHistory] = db.query(TransferApprovalHistory).all() + approval_op_list: list[TransferApprovalHistory] = db.query( + TransferApprovalHistory + ).all() assert len(approval_op_list) == 1 approval_op = approval_op_list[0] assert approval_op.token_address == self.test_token_address @@ -240,7 +240,7 @@ def test_normal_1_2(self, client, db): # # CANCEL # token - @pytest.mark.freeze_time('2021-04-27 12:34:56') + @pytest.mark.freeze_time("2021-04-27 12:34:56") def test_normal_2_1(self, client, db): issuer = config_eth_account("user1") issuer_address = issuer["address"] @@ -270,7 +270,9 @@ def test_normal_2_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -279,7 +281,7 @@ def test_normal_2_1(self, client, db): # mock IbetSecurityTokenContract_cancel_transfer = mock.patch( target="app.model.blockchain.token.IbetSecurityTokenInterface.cancel_transfer", - return_value=("test_tx_hash", {"status": 1}) + return_value=("test_tx_hash", {"status": 1}), ) # request target API @@ -288,29 +290,26 @@ def test_normal_2_1(self, client, db): self.base_url.format(self.test_token_address, id), headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") + "eoa-password": E2EEUtils.encrypt("password"), }, - json={ - "operation_type": "cancel" - } + json={"operation_type": "cancel"}, ) # Assertion assert resp.status_code == 200 assert resp.json() is None - _expected = { - "application_id": 100, - "data": str(datetime.utcnow().timestamp()) - } + _expected = {"application_id": 100, "data": str(datetime.utcnow().timestamp())} mock_transfer.assert_called_once_with( data=ApproveTransferParams(**_expected), tx_from=issuer_address, - private_key=ANY + private_key=ANY, ) - cancel_op_list: list[TransferApprovalHistory] = db.query(TransferApprovalHistory).all() + cancel_op_list: list[TransferApprovalHistory] = db.query( + TransferApprovalHistory + ).all() assert len(cancel_op_list) == 1 cancel_op = cancel_op_list[0] assert cancel_op.token_address == self.test_token_address @@ -320,7 +319,7 @@ def test_normal_2_1(self, client, db): # # Authorization by auth-token - @pytest.mark.freeze_time('2021-04-27 12:34:56') + @pytest.mark.freeze_time("2021-04-27 12:34:56") def test_normal_3(self, client, db): issuer = config_eth_account("user1") issuer_address = issuer["address"] @@ -356,7 +355,9 @@ def test_normal_3(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -365,35 +366,30 @@ def test_normal_3(self, client, db): # mock IbetSecurityTokenContract_approve_transfer = mock.patch( target="app.model.blockchain.token.IbetSecurityTokenInterface.approve_transfer", - return_value=("test_tx_hash", {"status": 1}) + return_value=("test_tx_hash", {"status": 1}), ) # request target API with IbetSecurityTokenContract_approve_transfer as mock_transfer: resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "approve" - }, + json={"operation_type": "approve"}, headers={ "issuer-address": issuer_address, - "auth-token": "test_auth_token" - } + "auth-token": "test_auth_token", + }, ) # Assertion assert resp.status_code == 200 assert resp.json() is None - _expected = { - "application_id": 100, - "data": str(datetime.utcnow().timestamp()) - } + _expected = {"application_id": 100, "data": str(datetime.utcnow().timestamp())} mock_transfer.assert_called_once_with( data=ApproveTransferParams(**_expected), tx_from=issuer_address, - private_key=ANY + private_key=ANY, ) ########################################################################### @@ -414,22 +410,19 @@ def test_error_1_1(self, client, db): # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, { "loc": ["body"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, - ] + ], } # @@ -446,23 +439,20 @@ def test_error_1_2(self, client, db): json={}, headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "operation_type"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, - ] + ], } # @@ -476,30 +466,25 @@ def test_error_1_3(self, client, db): # request target api resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "test" - }, + json={"operation_type": "test"}, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "operation_type"], "ctx": {"enum_values": ["approve", "cancel"]}, "msg": "value is not a valid enumeration member; permitted: 'approve', 'cancel'", - "type": "type_error.enum" + "type": "type_error.enum", }, - ] + ], } # @@ -511,34 +496,26 @@ def test_error_1_4(self, client, db): # request target api resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "approve" - }, - headers={ - "issuer-address": "issuer_address", - "eoa-password": "password" - } + json={"operation_type": "approve"}, + headers={"issuer-address": "issuer_address", "eoa-password": "password"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", }, { "loc": ["header", "eoa-password"], "msg": "eoa-password is not a Base64-encoded encrypted data", - "type": "value_error" - } - ] + "type": "value_error", + }, + ], } # @@ -553,23 +530,18 @@ def test_error_2_1(self, client, db): # request target api resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "approve" - }, + json={"operation_type": "approve"}, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -591,23 +563,18 @@ def test_error_2_2(self, client, db): # request target api resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "approve" - }, + json={"operation_type": "approve"}, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password_test") - } + "eoa-password": E2EEUtils.encrypt("password_test"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -629,23 +596,18 @@ def test_error_3_1(self, client, db): # request target api resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "approve" - }, + json={"operation_type": "approve"}, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # @@ -675,23 +637,18 @@ def test_error_3_2(self, client, db): # request target api resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "approve" - }, + json={"operation_type": "approve"}, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "transfer approval not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "transfer approval not found", } # @@ -722,23 +679,18 @@ def test_error_4_1(self, client, db): # request target api resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "approve" - }, + json={"operation_type": "approve"}, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } # @@ -773,9 +725,13 @@ def test_error_4_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = None _idx_transfer_approval.escrow_finished = None _idx_transfer_approval.transfer_approved = True @@ -784,23 +740,18 @@ def test_error_4_2(self, client, db): # request target api resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "approve" - }, + json={"operation_type": "approve"}, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "already approved" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "already approved", } # @@ -835,7 +786,9 @@ def test_error_4_3(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = True @@ -846,23 +799,18 @@ def test_error_4_3(self, client, db): # request target api resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "approve" - }, + json={"operation_type": "approve"}, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "canceled application" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "canceled application", } # @@ -897,7 +845,9 @@ def test_error_4_4(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = False @@ -910,21 +860,16 @@ def test_error_4_4(self, client, db): self.base_url.format(self.test_token_address, id), headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") + "eoa-password": E2EEUtils.encrypt("password"), }, - json={ - "operation_type": "cancel" - } + json={"operation_type": "cancel"}, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "escrow has not been finished yet" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "escrow has not been finished yet", } # @@ -959,7 +904,9 @@ def test_error_4_5(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = False @@ -972,21 +919,16 @@ def test_error_4_5(self, client, db): self.base_url.format(self.test_token_address, id), headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") + "eoa-password": E2EEUtils.encrypt("password"), }, - json={ - "operation_type": "cancel" - } + json={"operation_type": "cancel"}, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "application that cannot be canceled" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "application that cannot be canceled", } # @@ -1021,7 +963,9 @@ def test_error_4_6(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = False @@ -1041,21 +985,16 @@ def test_error_4_6(self, client, db): self.base_url.format(self.test_token_address, id), headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") + "eoa-password": E2EEUtils.encrypt("password"), }, - json={ - "operation_type": "cancel" - } + json={"operation_type": "cancel"}, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "duplicate operation" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "duplicate operation", } # @@ -1065,7 +1004,8 @@ def test_error_4_6(self, client, db): # raise SendTransactionError @mock.patch( "app.model.blockchain.token.IbetSecurityTokenInterface.approve_transfer", - MagicMock(side_effect=SendTransactionError())) + MagicMock(side_effect=SendTransactionError()), + ) def test_error_5_1(self, client, db): issuer = config_eth_account("user1") issuer_address = issuer["address"] @@ -1095,7 +1035,9 @@ def test_error_5_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -1104,23 +1046,18 @@ def test_error_5_1(self, client, db): # request target API resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "approve" - }, + json={"operation_type": "approve"}, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 2, - "title": "SendTransactionError" - }, - "detail": "failed to send transaction" + "meta": {"code": 2, "title": "SendTransactionError"}, + "detail": "failed to send transaction", } # @@ -1157,7 +1094,9 @@ def test_error_5_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -1166,34 +1105,31 @@ def test_error_5_2(self, client, db): # mock IbetSecurityTokenContract_approve_transfer = mock.patch( target="app.model.blockchain.token.IbetSecurityTokenInterface.approve_transfer", - side_effect=ContractRevertError("120902") + side_effect=ContractRevertError("120902"), ) IbetSecurityTokenContract_cancel_transfer = mock.patch( target="app.model.blockchain.token.IbetSecurityTokenInterface.cancel_transfer", - return_value=("test_tx_hash", {"status": 1}) + return_value=("test_tx_hash", {"status": 1}), ) # request target API - with IbetSecurityTokenContract_approve_transfer, IbetSecurityTokenContract_cancel_transfer: + with ( + IbetSecurityTokenContract_approve_transfer + ), IbetSecurityTokenContract_cancel_transfer: resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "approve" - }, + json={"operation_type": "approve"}, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 120902, - "title": "ContractRevertError" - }, - "detail": "Application is invalid." + "meta": {"code": 120902, "title": "ContractRevertError"}, + "detail": "Application is invalid.", } # @@ -1203,7 +1139,8 @@ def test_error_5_2(self, client, db): # raise SendTransactionError @mock.patch( "app.model.blockchain.exchange.IbetSecurityTokenEscrow.approve_transfer", - MagicMock(side_effect=SendTransactionError())) + MagicMock(side_effect=SendTransactionError()), + ) def test_error_5_3(self, client, db): issuer = config_eth_account("user1") issuer_address = issuer["address"] @@ -1233,7 +1170,9 @@ def test_error_5_3(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -1243,23 +1182,18 @@ def test_error_5_3(self, client, db): # request target API resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "approve" - }, + json={"operation_type": "approve"}, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 2, - "title": "SendTransactionError" - }, - "detail": "failed to send transaction" + "meta": {"code": 2, "title": "SendTransactionError"}, + "detail": "failed to send transaction", } # @@ -1296,7 +1230,9 @@ def test_error_5_4(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -1306,30 +1242,25 @@ def test_error_5_4(self, client, db): # mock IbetSecurityTokenEscrow_approve_transfer = mock.patch( target="app.model.blockchain.exchange.IbetSecurityTokenEscrow.approve_transfer", - side_effect=ContractRevertError("120902") + side_effect=ContractRevertError("120902"), ) # request target API with IbetSecurityTokenEscrow_approve_transfer: resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "approve" - }, + json={"operation_type": "approve"}, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 120902, - "title": "ContractRevertError" - }, - "detail": "Application is invalid." + "meta": {"code": 120902, "title": "ContractRevertError"}, + "detail": "Application is invalid.", } # @@ -1339,7 +1270,8 @@ def test_error_5_4(self, client, db): # raise SendTransactionError @mock.patch( "app.model.blockchain.token.IbetSecurityTokenInterface.cancel_transfer", - MagicMock(side_effect=SendTransactionError())) + MagicMock(side_effect=SendTransactionError()), + ) def test_error_6_1(self, client, db): issuer = config_eth_account("user1") issuer_address = issuer["address"] @@ -1369,7 +1301,9 @@ def test_error_6_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -1380,21 +1314,16 @@ def test_error_6_1(self, client, db): self.base_url.format(self.test_token_address, id), headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") + "eoa-password": E2EEUtils.encrypt("password"), }, - json={ - "operation_type": "cancel" - } + json={"operation_type": "cancel"}, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 2, - "title": "SendTransactionError" - }, - "detail": "failed to send transaction" + "meta": {"code": 2, "title": "SendTransactionError"}, + "detail": "failed to send transaction", } # @@ -1431,7 +1360,9 @@ def test_error_6_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -1440,7 +1371,7 @@ def test_error_6_2(self, client, db): # mock IbetSecurityTokenContract_cancel_transfer = mock.patch( target="app.model.blockchain.token.IbetSecurityTokenInterface.cancel_transfer", - side_effect=ContractRevertError("120802") + side_effect=ContractRevertError("120802"), ) # request target API @@ -1449,19 +1380,14 @@ def test_error_6_2(self, client, db): self.base_url.format(self.test_token_address, id), headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") + "eoa-password": E2EEUtils.encrypt("password"), }, - json={ - "operation_type": "cancel" - } + json={"operation_type": "cancel"}, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 120802, - "title": "ContractRevertError" - }, - "detail": "Application is invalid." + "meta": {"code": 120802, "title": "ContractRevertError"}, + "detail": "Application is invalid.", } diff --git a/tests/test_app_routers_bond_transfers_POST.py b/tests/test_app_routers_bond_transfers_POST.py index 000aad6b..9aaf3a08 100644 --- a/tests/test_app_routers_bond_transfers_POST.py +++ b/tests/test_app_routers_bond_transfers_POST.py @@ -20,14 +20,9 @@ from unittest import mock from unittest.mock import ANY, MagicMock -from app.model.db import ( - Account, - AuthToken, - Token, - TokenType -) -from app.utils.e2ee_utils import E2EEUtils from app.exceptions import SendTransactionError +from app.model.db import Account, AuthToken, Token, TokenType +from app.utils.e2ee_utils import E2EEUtils from tests.account_config import config_eth_account @@ -78,15 +73,15 @@ def test_normal_1(self, IbetStraightBondContract_mock, client, db): "token_address": _token_address, "from_address": _from_address, "to_address": _to_address, - "amount": 10 + "amount": 10, } resp = client.post( self.test_url, json=req_param, headers={ "issuer-address": _admin_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion @@ -94,10 +89,10 @@ def test_normal_1(self, IbetStraightBondContract_mock, client, db): data={ "from_address": _from_address, "to_address": _to_address, - "amount": 10 + "amount": 10, }, tx_from=_admin_address, - private_key=ANY + private_key=ANY, ) assert resp.status_code == 200 @@ -148,15 +143,12 @@ def test_normal_2(self, IbetStraightBondContract_mock, client, db): "token_address": _token_address, "from_address": _from_address, "to_address": _to_address, - "amount": 10 + "amount": 10, } resp = client.post( self.test_url, json=req_param, - headers={ - "issuer-address": _admin_address, - "auth-token": "test_auth_token" - } + headers={"issuer-address": _admin_address, "auth-token": "test_auth_token"}, ) # assertion @@ -164,10 +156,10 @@ def test_normal_2(self, IbetStraightBondContract_mock, client, db): data={ "from_address": _from_address, "to_address": _to_address, - "amount": 10 + "amount": 10, }, tx_from=_admin_address, - private_key=ANY + private_key=ANY, ) assert resp.status_code == 200 @@ -189,51 +181,39 @@ def test_error_1(self, client, db): "token_address": _token_address, "from_address": _from_address, "to_address": _to_address, - "amount": 0 + "amount": 0, } resp = client.post( - self.test_url, - json=req_param, - headers={ - "issuer-address": "issuer-address" - } + self.test_url, json=req_param, headers={"issuer-address": "issuer-address"} ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "token_address"], "msg": "token_address is not a valid address", - "type": "value_error" + "type": "value_error", }, { "loc": ["body", "from_address"], "msg": "from_address is not a valid address", - "type": "value_error" + "type": "value_error", }, { "loc": ["body", "to_address"], "msg": "to_address is not a valid address", - "type": "value_error" + "type": "value_error", }, { - "ctx": { - "limit_value": 1 - }, - "loc": [ - "body", - "amount" - ], + "ctx": {"limit_value": 1}, + "loc": ["body", "amount"], "msg": "ensure this value is greater than or equal to 1", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, - ] + ], } # @@ -250,65 +230,48 @@ def test_error_2(self, client, db): "token_address": _token_address, "from_address": _from_address, "to_address": _to_address, - "amount": 1_000_000_000_001 + "amount": 1_000_000_000_001, } resp = client.post( - self.test_url, - json=req_param, - headers={ - "issuer-address": "issuer-address" - } + self.test_url, json=req_param, headers={"issuer-address": "issuer-address"} ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "ctx": { - "limit_value": 1_000_000_000_000 - }, - "loc": [ - "body", - "amount" - ], + "ctx": {"limit_value": 1_000_000_000_000}, + "loc": ["body", "amount"], "msg": "ensure this value is less than or equal to 1000000000000", - "type": "value_error.number.not_le" + "type": "value_error.number.not_le", }, - ] + ], } # # RequestValidationError: headers and body required def test_error_3(self, client, db): # request target API - resp = client.post( - self.test_url - ) + resp = client.post(self.test_url) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, { "loc": ["body"], "msg": "field required", - "type": "value_error.missing" - } - ] + "type": "value_error.missing", + }, + ], } # @@ -327,30 +290,23 @@ def test_error_4(self, client, db): "token_address": _token_address, "from_address": _from_address, "to_address": _to_address, - "amount": 10 + "amount": 10, } resp = client.post( - self.test_url, - json=req_param, - headers={ - "issuer-address": "issuer-address" - } + self.test_url, json=req_param, headers={"issuer-address": "issuer-address"} ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -371,29 +327,25 @@ def test_error_5(self, client, db): "token_address": _token_address, "from_address": _from_address, "to_address": _to_address, - "amount": 10 + "amount": 10, } resp = client.post( self.test_url, json=req_param, - headers={ - "issuer-address": _admin_address, - "eoa-password": "password" - } + headers={"issuer-address": _admin_address, "eoa-password": "password"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, - "detail": [{ - "loc": ["header", "eoa-password"], - "msg": "eoa-password is not a Base64-encoded encrypted data", - "type": "value_error" - }] + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ + { + "loc": ["header", "eoa-password"], + "msg": "eoa-password is not a Base64-encoded encrypted data", + "type": "value_error", + } + ], } # @@ -416,25 +368,22 @@ def test_error_6(self, client, db): "token_address": _token_address, "from_address": _from_address, "to_address": _to_address, - "amount": 10 + "amount": 10, } resp = client.post( self.test_url, json=req_param, headers={ "issuer-address": _admin_address, # Non-existent issuer - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -464,25 +413,22 @@ def test_error_7(self, client, db): "token_address": _token_address, "from_address": _from_address, "to_address": _to_address, - "amount": 10 + "amount": 10, } resp = client.post( self.test_url, json=req_param, headers={ "issuer-address": _admin_address, - "eoa-password": E2EEUtils.encrypt("password_test") - } + "eoa-password": E2EEUtils.encrypt("password_test"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -512,25 +458,22 @@ def test_error_8(self, client, db): "token_address": _token_address, "from_address": _from_address, "to_address": _to_address, - "amount": 10 + "amount": 10, } resp = client.post( self.test_url, json=req_param, headers={ "issuer-address": _admin_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "token not found", } # @@ -569,31 +512,30 @@ def test_error_9(self, client, db): "token_address": _token_address, "from_address": _from_address, "to_address": _to_address, - "amount": 10 + "amount": 10, } resp = client.post( self.test_url, json=req_param, headers={ "issuer-address": _admin_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } # # Send Transaction Error - @mock.patch("app.model.blockchain.token.IbetStraightBondContract.transfer", - MagicMock(side_effect=SendTransactionError())) + @mock.patch( + "app.model.blockchain.token.IbetStraightBondContract.transfer", + MagicMock(side_effect=SendTransactionError()), + ) def test_error_10(self, client, db): _admin_account = config_eth_account("user1") _admin_address = _admin_account["address"] @@ -627,23 +569,20 @@ def test_error_10(self, client, db): "token_address": _token_address, "from_address": _from_address, "to_address": _to_address, - "amount": 10 + "amount": 10, } resp = client.post( self.test_url, json=req_param, headers={ "issuer-address": _admin_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 2, - "title": "SendTransactionError" - }, - "detail": "failed to send transaction" + "meta": {"code": 2, "title": "SendTransactionError"}, + "detail": "failed to send transaction", } diff --git a/tests/test_app_routers_bond_transfers_{token_Address}_GET.py b/tests/test_app_routers_bond_transfers_{token_Address}_GET.py index 84e25116..1ddb092c 100644 --- a/tests/test_app_routers_bond_transfers_{token_Address}_GET.py +++ b/tests/test_app_routers_bond_transfers_{token_Address}_GET.py @@ -21,12 +21,7 @@ from pytz import timezone import config -from app.model.db import ( - Token, - TokenType, - IDXTransfer, - IDXTransferSourceEventType -) +from app.model.db import IDXTransfer, IDXTransferSourceEventType, Token, TokenType local_tz = timezone(config.TZ) @@ -41,9 +36,9 @@ class TestAppRoutersBondTransfersGET: test_from_address = "test_from_address" test_to_address = "test_to_address" test_block_timestamp = [ - datetime.strptime("2022/01/02 15:20:30", '%Y/%m/%d %H:%M:%S'), # JST 2022/01/03 - datetime.strptime("2022/01/01 15:20:30", '%Y/%m/%d %H:%M:%S'), # JST 2022/01/02 - datetime.strptime("2022/01/02 00:20:30", '%Y/%m/%d %H:%M:%S'), # JST 2022/01/02 + datetime.strptime("2022/01/02 15:20:30", "%Y/%m/%d %H:%M:%S"), # JST 2022/01/03 + datetime.strptime("2022/01/01 15:20:30", "%Y/%m/%d %H:%M:%S"), # JST 2022/01/02 + datetime.strptime("2022/01/02 00:20:30", "%Y/%m/%d %H:%M:%S"), # JST 2022/01/02 ] test_block_timestamp_str = [ "2022-01-03T00:20:30+09:00", @@ -81,19 +76,12 @@ def test_normal_1(self, client, db): db.add(_idx_transfer) # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 3, - "offset": None, - "limit": None, - "total": 3 - }, + "result_set": {"count": 3, "offset": None, "limit": None, "total": 3}, "transfer_history": [ { "transaction_hash": self.test_transaction_hash, @@ -103,7 +91,7 @@ def test_normal_1(self, client, db): "amount": 0, "source_event": IDXTransferSourceEventType.TRANSFER.value, "data": None, - "block_timestamp": self.test_block_timestamp_str[0] + "block_timestamp": self.test_block_timestamp_str[0], }, { "transaction_hash": self.test_transaction_hash, @@ -113,7 +101,7 @@ def test_normal_1(self, client, db): "amount": 2, "source_event": IDXTransferSourceEventType.TRANSFER.value, "data": None, - "block_timestamp": self.test_block_timestamp_str[2] + "block_timestamp": self.test_block_timestamp_str[2], }, { "transaction_hash": self.test_transaction_hash, @@ -123,9 +111,9 @@ def test_normal_1(self, client, db): "amount": 1, "source_event": IDXTransferSourceEventType.TRANSFER.value, "data": None, - "block_timestamp": self.test_block_timestamp_str[1] + "block_timestamp": self.test_block_timestamp_str[1], }, - ] + ], } assert resp.json() == assumed_response @@ -162,12 +150,7 @@ def test_normal_2_1(self, client, db): # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 3, - "offset": 1, - "limit": 1, - "total": 3 - }, + "result_set": {"count": 3, "offset": 1, "limit": 1, "total": 3}, "transfer_history": [ { "transaction_hash": self.test_transaction_hash, @@ -177,9 +160,9 @@ def test_normal_2_1(self, client, db): "amount": 2, "source_event": IDXTransferSourceEventType.TRANSFER.value, "data": None, - "block_timestamp": self.test_block_timestamp_str[2] + "block_timestamp": self.test_block_timestamp_str[2], }, - ] + ], } assert resp.json() == assumed_response @@ -232,20 +215,13 @@ def test_normal_2_2(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "source_event": IDXTransferSourceEventType.UNLOCK.value - } + params={"source_event": IDXTransferSourceEventType.UNLOCK.value}, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 1, - "offset": None, - "limit": None, - "total": 3 - }, + "result_set": {"count": 1, "offset": None, "limit": None, "total": 3}, "transfer_history": [ { "transaction_hash": self.test_transaction_hash, @@ -255,9 +231,9 @@ def test_normal_2_2(self, client, db): "amount": 2, "source_event": IDXTransferSourceEventType.UNLOCK.value, "data": {"message": "unlock"}, - "block_timestamp": self.test_block_timestamp_str[2] + "block_timestamp": self.test_block_timestamp_str[2], } - ] + ], } assert resp.json() == assumed_response @@ -309,21 +285,13 @@ def test_normal_2_3(self, client, db): # request target API resp = client.get( - self.base_url.format(self.test_token_address), - params={ - "data": "unlo" - } + self.base_url.format(self.test_token_address), params={"data": "unlo"} ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 1, - "offset": None, - "limit": None, - "total": 3 - }, + "result_set": {"count": 1, "offset": None, "limit": None, "total": 3}, "transfer_history": [ { "transaction_hash": self.test_transaction_hash, @@ -333,9 +301,9 @@ def test_normal_2_3(self, client, db): "amount": 2, "source_event": IDXTransferSourceEventType.UNLOCK.value, "data": {"message": "unlock"}, - "block_timestamp": self.test_block_timestamp_str[2] + "block_timestamp": self.test_block_timestamp_str[2], } - ] + ], } assert resp.json() == assumed_response @@ -370,18 +338,13 @@ def test_normal_3(self, client, db): params={ "sort_item": "block_timestamp", "sort_order": 0, - } + }, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 3, - "offset": None, - "limit": None, - "total": 3 - }, + "result_set": {"count": 3, "offset": None, "limit": None, "total": 3}, "transfer_history": [ { "transaction_hash": self.test_transaction_hash, @@ -391,7 +354,7 @@ def test_normal_3(self, client, db): "amount": 1, "source_event": IDXTransferSourceEventType.TRANSFER.value, "data": None, - "block_timestamp": self.test_block_timestamp_str[1] + "block_timestamp": self.test_block_timestamp_str[1], }, { "transaction_hash": self.test_transaction_hash, @@ -401,7 +364,7 @@ def test_normal_3(self, client, db): "amount": 2, "source_event": IDXTransferSourceEventType.TRANSFER.value, "data": None, - "block_timestamp": self.test_block_timestamp_str[2] + "block_timestamp": self.test_block_timestamp_str[2], }, { "transaction_hash": self.test_transaction_hash, @@ -411,9 +374,9 @@ def test_normal_3(self, client, db): "amount": 0, "source_event": IDXTransferSourceEventType.TRANSFER.value, "data": None, - "block_timestamp": self.test_block_timestamp_str[0] - } - ] + "block_timestamp": self.test_block_timestamp_str[0], + }, + ], } assert resp.json() == assumed_response @@ -469,18 +432,13 @@ def test_normal_4(self, client, db): params={ "sort_item": "from_address", "sort_order": 0, - } + }, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 3, - "offset": None, - "limit": None, - "total": 3 - }, + "result_set": {"count": 3, "offset": None, "limit": None, "total": 3}, "transfer_history": [ { "transaction_hash": self.test_transaction_hash, @@ -490,7 +448,7 @@ def test_normal_4(self, client, db): "amount": 2, "source_event": IDXTransferSourceEventType.UNLOCK.value, "data": {"message": "unlock"}, - "block_timestamp": self.test_block_timestamp_str[2] + "block_timestamp": self.test_block_timestamp_str[2], }, { "transaction_hash": self.test_transaction_hash, @@ -500,7 +458,7 @@ def test_normal_4(self, client, db): "amount": 0, "source_event": IDXTransferSourceEventType.TRANSFER.value, "data": None, - "block_timestamp": self.test_block_timestamp_str[0] + "block_timestamp": self.test_block_timestamp_str[0], }, { "transaction_hash": self.test_transaction_hash, @@ -510,9 +468,9 @@ def test_normal_4(self, client, db): "amount": 1, "source_event": IDXTransferSourceEventType.TRANSFER.value, "data": None, - "block_timestamp": self.test_block_timestamp_str[1] + "block_timestamp": self.test_block_timestamp_str[1], }, - ] + ], } assert resp.json() == assumed_response @@ -568,18 +526,13 @@ def test_normal_5(self, client, db): params={ "sort_item": "to_address", "sort_order": 1, - } + }, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 3, - "offset": None, - "limit": None, - "total": 3 - }, + "result_set": {"count": 3, "offset": None, "limit": None, "total": 3}, "transfer_history": [ { "transaction_hash": self.test_transaction_hash, @@ -589,7 +542,7 @@ def test_normal_5(self, client, db): "amount": 0, "source_event": IDXTransferSourceEventType.TRANSFER.value, "data": None, - "block_timestamp": self.test_block_timestamp_str[0] + "block_timestamp": self.test_block_timestamp_str[0], }, { "transaction_hash": self.test_transaction_hash, @@ -599,7 +552,7 @@ def test_normal_5(self, client, db): "amount": 2, "source_event": IDXTransferSourceEventType.UNLOCK.value, "data": {"message": "unlock"}, - "block_timestamp": self.test_block_timestamp_str[2] + "block_timestamp": self.test_block_timestamp_str[2], }, { "transaction_hash": self.test_transaction_hash, @@ -609,9 +562,9 @@ def test_normal_5(self, client, db): "amount": 1, "source_event": IDXTransferSourceEventType.TRANSFER.value, "data": None, - "block_timestamp": self.test_block_timestamp_str[1] + "block_timestamp": self.test_block_timestamp_str[1], }, - ] + ], } assert resp.json() == assumed_response @@ -667,18 +620,13 @@ def test_normal_6(self, client, db): params={ "sort_item": "amount", "sort_order": 0, - } + }, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 3, - "offset": None, - "limit": None, - "total": 3 - }, + "result_set": {"count": 3, "offset": None, "limit": None, "total": 3}, "transfer_history": [ { "transaction_hash": self.test_transaction_hash, @@ -688,7 +636,7 @@ def test_normal_6(self, client, db): "amount": 1, "source_event": IDXTransferSourceEventType.TRANSFER.value, "data": None, - "block_timestamp": self.test_block_timestamp_str[0] + "block_timestamp": self.test_block_timestamp_str[0], }, { "transaction_hash": self.test_transaction_hash, @@ -698,7 +646,7 @@ def test_normal_6(self, client, db): "amount": 2, "source_event": IDXTransferSourceEventType.UNLOCK.value, "data": {"message": "unlock"}, - "block_timestamp": self.test_block_timestamp_str[2] + "block_timestamp": self.test_block_timestamp_str[2], }, { "transaction_hash": self.test_transaction_hash, @@ -708,9 +656,9 @@ def test_normal_6(self, client, db): "amount": 2, "source_event": IDXTransferSourceEventType.TRANSFER.value, "data": None, - "block_timestamp": self.test_block_timestamp_str[1] + "block_timestamp": self.test_block_timestamp_str[1], }, - ] + ], } assert resp.json() == assumed_response @@ -722,18 +670,13 @@ def test_normal_6(self, client, db): # token not found def test_error_1(self, client, db): # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 404 assumed_response = { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } assert resp.json() == assumed_response @@ -751,18 +694,13 @@ def test_error_2(self, client, db): db.add(_token) # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } # @@ -771,27 +709,29 @@ def test_error_3(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "sort_item": "block_timestamp12345" - } + params={"sort_item": "block_timestamp12345"}, ) # assertion assert resp.status_code == 422 assumed_response = { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "ctx": {"enum_values": ["block_timestamp", "from_address", "to_address", "amount"]}, + "ctx": { + "enum_values": [ + "block_timestamp", + "from_address", + "to_address", + "amount", + ] + }, "loc": ["query", "sort_item"], "msg": "value is not a valid enumeration member; permitted: 'block_timestamp', 'from_address', " - "'to_address', 'amount'", - "type": "type_error.enum" + "'to_address', 'amount'", + "type": "type_error.enum", } - ] + ], } assert resp.json() == assumed_response @@ -800,29 +740,21 @@ def test_error_3(self, client, db): def test_error_4(self, client, db): # request target API resp = client.get( - self.base_url.format(self.test_token_address), - params={ - "sort_order": -1 - } + self.base_url.format(self.test_token_address), params={"sort_order": -1} ) # assertion assert resp.status_code == 422 assumed_response = { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "ctx": { - "limit_value": 0 - }, + "ctx": {"limit_value": 0}, "loc": ["query", "sort_order"], "msg": "ensure this value is greater than or equal to 0", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", } - ] + ], } assert resp.json() == assumed_response @@ -831,28 +763,20 @@ def test_error_4(self, client, db): def test_error_5(self, client, db): # request target API resp = client.get( - self.base_url.format(self.test_token_address), - params={ - "sort_order": 2 - } + self.base_url.format(self.test_token_address), params={"sort_order": 2} ) # assertion assert resp.status_code == 422 assumed_response = { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "ctx": { - "limit_value": 1 - }, + "ctx": {"limit_value": 1}, "loc": ["query", "sort_order"], "msg": "ensure this value is less than or equal to 1", - "type": "value_error.number.not_le" + "type": "value_error.number.not_le", } - ] + ], } assert resp.json() == assumed_response diff --git a/tests/test_app_routers_docs_GET.py b/tests/test_app_routers_docs_GET.py index 87b0789d..659ac308 100644 --- a/tests/test_app_routers_docs_GET.py +++ b/tests/test_app_routers_docs_GET.py @@ -21,7 +21,7 @@ class TestOpenAPIDoc: # テスト対象API - apiurl_base = '/openapi.json' + apiurl_base = "/openapi.json" ########################################################################### # Normal diff --git a/tests/test_app_routers_e2e_messaging_accounts_GET.py b/tests/test_app_routers_e2e_messaging_accounts_GET.py index 34ac89e5..e8d6d3fd 100644 --- a/tests/test_app_routers_e2e_messaging_accounts_GET.py +++ b/tests/test_app_routers_e2e_messaging_accounts_GET.py @@ -19,10 +19,7 @@ import time from datetime import datetime -from app.model.db import ( - E2EMessagingAccount, - E2EMessagingAccountRsaKey -) +from app.model.db import E2EMessagingAccount, E2EMessagingAccountRsaKey class TestAppRoutersE2EMessagingAccountsGET: @@ -75,7 +72,7 @@ def test_normal_2(self, client, db): "rsa_key_generate_interval": 1, "rsa_generation": 2, "rsa_public_key": "rsa_public_key_1_1", - "is_deleted": False + "is_deleted": False, }, ] @@ -152,28 +149,28 @@ def test_normal_3(self, client, db): "rsa_key_generate_interval": 0, "rsa_generation": 0, "rsa_public_key": "rsa_public_key_1_1", - "is_deleted": False + "is_deleted": False, }, { "account_address": "0x1234567890123456789012345678900000000001", "rsa_key_generate_interval": 1, "rsa_generation": 2, "rsa_public_key": None, - "is_deleted": True + "is_deleted": True, }, { "account_address": "0x1234567890123456789012345678900000000002", "rsa_key_generate_interval": 3, "rsa_generation": 4, "rsa_public_key": "rsa_public_key_2_1", - "is_deleted": False + "is_deleted": False, }, { "account_address": "0x1234567890123456789012345678900000000003", "rsa_key_generate_interval": 0, "rsa_generation": 0, "rsa_public_key": "rsa_public_key_3_3", - "is_deleted": False + "is_deleted": False, }, ] diff --git a/tests/test_app_routers_e2e_messaging_accounts_POST.py b/tests/test_app_routers_e2e_messaging_accounts_POST.py index 47ea92f8..7debd3d6 100644 --- a/tests/test_app_routers_e2e_messaging_accounts_POST.py +++ b/tests/test_app_routers_e2e_messaging_accounts_POST.py @@ -17,28 +17,20 @@ SPDX-License-Identifier: Apache-2.0 """ import base64 +from datetime import datetime, timezone from unittest import mock -from unittest.mock import MagicMock -from unittest.mock import ANY -from datetime import ( - datetime, - timezone -) +from unittest.mock import ANY, MagicMock -from config import ( - EOA_PASSWORD_PATTERN_MSG, - E2E_MESSAGING_RSA_DEFAULT_PASSPHRASE, - E2E_MESSAGING_RSA_PASSPHRASE_PATTERN_MSG -) +from app.exceptions import SendTransactionError from app.model.blockchain import E2EMessaging -from app.model.db import ( - E2EMessagingAccount, - E2EMessagingAccountRsaKey, - TransactionLock -) +from app.model.db import E2EMessagingAccount, E2EMessagingAccountRsaKey, TransactionLock from app.utils.contract_utils import ContractUtils from app.utils.e2ee_utils import E2EEUtils -from app.exceptions import SendTransactionError +from config import ( + E2E_MESSAGING_RSA_DEFAULT_PASSPHRASE, + E2E_MESSAGING_RSA_PASSPHRASE_PATTERN_MSG, + EOA_PASSWORD_PATTERN_MSG, +) class TestAppRoutersE2EMessagingAccountsPOST: @@ -62,25 +54,28 @@ def test_normal_1(self, client, db, e2e_messaging_contract): # mock mock_E2EMessaging_set_public_key = mock.patch( target="app.model.blockchain.e2e_messaging.E2EMessaging.set_public_key", - side_effect=[("tx_1", {"blockNumber": 12345})] + side_effect=[("tx_1", {"blockNumber": 12345})], ) mock_ContractUtils_get_block_by_transaction_hash = mock.patch( target="app.utils.contract_utils.ContractUtils.get_block_by_transaction_hash", side_effect=[ { "number": 12345, - "timestamp": datetime(2099, 4, 27, 12, 34, 56, tzinfo=timezone.utc).timestamp() + "timestamp": datetime( + 2099, 4, 27, 12, 34, 56, tzinfo=timezone.utc + ).timestamp(), }, - ] + ], ) - with mock.patch("app.routers.e2e_messaging.E2E_MESSAGING_CONTRACT_ADDRESS", - e2e_messaging_contract.address), \ - mock_E2EMessaging_set_public_key, mock_ContractUtils_get_block_by_transaction_hash: + with mock.patch( + "app.routers.e2e_messaging.E2E_MESSAGING_CONTRACT_ADDRESS", + e2e_messaging_contract.address, + ), ( + mock_E2EMessaging_set_public_key + ), mock_ContractUtils_get_block_by_transaction_hash: # request target api - req_param = { - "eoa_password": E2EEUtils.encrypt(self.valid_password) - } + req_param = {"eoa_password": E2EEUtils.encrypt(self.valid_password)} resp = client.post(self.base_url, json=req_param) # assertion @@ -88,7 +83,7 @@ def test_normal_1(self, client, db, e2e_messaging_contract): public_key=ANY, key_type="RSA4096", tx_from=resp.json()["account_address"], - private_key=ANY + private_key=ANY, ) ContractUtils.get_block_by_transaction_hash.assert_called_with( tx_hash="tx_1", @@ -125,7 +120,10 @@ def test_normal_1(self, client, db, e2e_messaging_contract): assert _rsa_key.account_address == resp.json()["account_address"] assert _rsa_key.rsa_private_key == ANY assert _rsa_key.rsa_public_key == resp.json()["rsa_public_key"] - assert E2EEUtils.decrypt(_rsa_key.rsa_passphrase) == E2E_MESSAGING_RSA_DEFAULT_PASSPHRASE + assert ( + E2EEUtils.decrypt(_rsa_key.rsa_passphrase) + == E2E_MESSAGING_RSA_DEFAULT_PASSPHRASE + ) assert _rsa_key.block_timestamp == datetime(2099, 4, 27, 12, 34, 56) assert 0 == len(_transaction_before) assert 1 == len(_transaction_after) @@ -143,32 +141,37 @@ def test_normal_2(self, client, db, e2e_messaging_contract): class KMSClientMock: def generate_random(self, NumberOfBytes): assert NumberOfBytes == 32 - return { - "Plaintext": b"12345678901234567890123456789012" - } + return {"Plaintext": b"12345678901234567890123456789012"} mock_boto3_client = mock.patch( - target="boto3.client", - side_effect=[KMSClientMock()] + target="boto3.client", side_effect=[KMSClientMock()] ) mock_E2EMessaging_set_public_key = mock.patch( target="app.model.blockchain.e2e_messaging.E2EMessaging.set_public_key", - side_effect=[("tx_1", {"blockNumber": 12345})] + side_effect=[("tx_1", {"blockNumber": 12345})], ) mock_ContractUtils_get_block_by_transaction_hash = mock.patch( target="app.utils.contract_utils.ContractUtils.get_block_by_transaction_hash", side_effect=[ { "number": 12345, - "timestamp": datetime(2099, 4, 27, 12, 34, 56, tzinfo=timezone.utc).timestamp() + "timestamp": datetime( + 2099, 4, 27, 12, 34, 56, tzinfo=timezone.utc + ).timestamp(), }, - ] + ], ) - with mock.patch("app.routers.e2e_messaging.AWS_KMS_GENERATE_RANDOM_ENABLED", True), \ - mock.patch("app.routers.e2e_messaging.E2E_MESSAGING_CONTRACT_ADDRESS", - e2e_messaging_contract.address), \ - mock_boto3_client, mock_E2EMessaging_set_public_key, mock_ContractUtils_get_block_by_transaction_hash: + with mock.patch( + "app.routers.e2e_messaging.AWS_KMS_GENERATE_RANDOM_ENABLED", True + ), mock.patch( + "app.routers.e2e_messaging.E2E_MESSAGING_CONTRACT_ADDRESS", + e2e_messaging_contract.address, + ), ( + mock_boto3_client + ), ( + mock_E2EMessaging_set_public_key + ), mock_ContractUtils_get_block_by_transaction_hash: # request target api req_param = { "eoa_password": E2EEUtils.encrypt(self.valid_password), @@ -183,7 +186,7 @@ def generate_random(self, NumberOfBytes): public_key=ANY, key_type="RSA4096", tx_from=resp.json()["account_address"], - private_key=ANY + private_key=ANY, ) ContractUtils.get_block_by_transaction_hash.assert_called_with( tx_hash="tx_1", @@ -240,17 +243,14 @@ def test_error_1_1(self, client, db): # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", } - ] + ], } # @@ -263,17 +263,14 @@ def test_error_1_2(self, client, db): # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "eoa_password"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, - ] + ], } # @@ -282,7 +279,9 @@ def test_error_1_2(self, client, db): def test_error_1_3(self, client, db): req_param = { "eoa_password": base64.encodebytes("password".encode("utf-8")).decode(), - "rsa_passphrase": base64.encodebytes("password_rsa".encode("utf-8")).decode(), + "rsa_passphrase": base64.encodebytes( + "password_rsa".encode("utf-8") + ).decode(), "rsa_key_generate_interval": -1, "rsa_generation": -1, } @@ -292,34 +291,31 @@ def test_error_1_3(self, client, db): # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "eoa_password"], "msg": "eoa_password is not a Base64-encoded encrypted data", - "type": "value_error" + "type": "value_error", }, { "loc": ["body", "rsa_passphrase"], "msg": "rsa_passphrase is not a Base64-encoded encrypted data", - "type": "value_error" + "type": "value_error", }, { "loc": ["body", "rsa_key_generate_interval"], "ctx": {"limit_value": 0}, "msg": "ensure this value is greater than or equal to 0", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, { "loc": ["body", "rsa_generation"], "ctx": {"limit_value": 0}, "msg": "ensure this value is greater than or equal to 0", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, - ] + ], } # @@ -338,44 +334,36 @@ def test_error_1_4(self, client, db): # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "rsa_key_generate_interval"], "ctx": {"limit_value": 10_000}, "msg": "ensure this value is less than or equal to 10000", - "type": "value_error.number.not_le" + "type": "value_error.number.not_le", }, { "loc": ["body", "rsa_generation"], "ctx": {"limit_value": 100}, "msg": "ensure this value is less than or equal to 100", - "type": "value_error.number.not_le" + "type": "value_error.number.not_le", }, - ] + ], } # # Passphrase Policy Violation # eoa_password def test_error_2_1(self, client, db): - req_param = { - "eoa_password": E2EEUtils.encrypt(self.invalid_password) - } + req_param = {"eoa_password": E2EEUtils.encrypt(self.invalid_password)} resp = client.post(self.base_url, json=req_param) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": EOA_PASSWORD_PATTERN_MSG + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": EOA_PASSWORD_PATTERN_MSG, } # @@ -384,7 +372,7 @@ def test_error_2_1(self, client, db): def test_error_2_2(self, client, db): req_param = { "eoa_password": E2EEUtils.encrypt(self.valid_password), - "rsa_passphrase": E2EEUtils.encrypt(self.invalid_password) + "rsa_passphrase": E2EEUtils.encrypt(self.invalid_password), } resp = client.post(self.base_url, json=req_param) @@ -392,30 +380,24 @@ def test_error_2_2(self, client, db): # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": E2E_MESSAGING_RSA_PASSPHRASE_PATTERN_MSG + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": E2E_MESSAGING_RSA_PASSPHRASE_PATTERN_MSG, } # # Send Transaction Error - @mock.patch("app.model.blockchain.e2e_messaging.E2EMessaging.set_public_key", - MagicMock(side_effect=SendTransactionError)) + @mock.patch( + "app.model.blockchain.e2e_messaging.E2EMessaging.set_public_key", + MagicMock(side_effect=SendTransactionError), + ) def test_error_3(self, client, db, e2e_messaging_contract): # request target api - req_param = { - "eoa_password": E2EEUtils.encrypt(self.valid_password) - } + req_param = {"eoa_password": E2EEUtils.encrypt(self.valid_password)} resp = client.post(self.base_url, json=req_param) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 2, - "title": "SendTransactionError" - }, - "detail": "failed to send transaction" + "meta": {"code": 2, "title": "SendTransactionError"}, + "detail": "failed to send transaction", } diff --git a/tests/test_app_routers_e2e_messaging_accounts_{account_address}_DELETE.py b/tests/test_app_routers_e2e_messaging_accounts_{account_address}_DELETE.py index 88edd6fb..5241b36e 100644 --- a/tests/test_app_routers_e2e_messaging_accounts_{account_address}_DELETE.py +++ b/tests/test_app_routers_e2e_messaging_accounts_{account_address}_DELETE.py @@ -19,10 +19,7 @@ import time from datetime import datetime -from app.model.db import ( - E2EMessagingAccount, - E2EMessagingAccountRsaKey -) +from app.model.db import E2EMessagingAccount, E2EMessagingAccountRsaKey class TestAppRoutersE2EMessagingAccountsAccountAddressPOST: @@ -66,7 +63,9 @@ def test_normal_1(self, client, db): # request target api resp = client.delete( - self.base_url.format(account_address="0x1234567890123456789012345678900000000000"), + self.base_url.format( + account_address="0x1234567890123456789012345678900000000000" + ), ) # assertion @@ -91,14 +90,14 @@ def test_normal_1(self, client, db): # no data def test_error_1(self, client, db): resp = client.delete( - self.base_url.format(account_address="0x1234567890123456789012345678900000000000"), + self.base_url.format( + account_address="0x1234567890123456789012345678900000000000" + ), ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, "title": "NotFound" - }, - "detail": "e2e messaging account is not exists" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "e2e messaging account is not exists", } diff --git a/tests/test_app_routers_e2e_messaging_accounts_{account_address}_GET.py b/tests/test_app_routers_e2e_messaging_accounts_{account_address}_GET.py index 5897b635..29c81aa6 100644 --- a/tests/test_app_routers_e2e_messaging_accounts_{account_address}_GET.py +++ b/tests/test_app_routers_e2e_messaging_accounts_{account_address}_GET.py @@ -19,10 +19,7 @@ import time from datetime import datetime -from app.model.db import ( - E2EMessagingAccount, - E2EMessagingAccountRsaKey -) +from app.model.db import E2EMessagingAccount, E2EMessagingAccountRsaKey class TestAppRoutersE2EMessagingAccountsAccountAddressGET: @@ -65,7 +62,9 @@ def test_normal_1(self, client, db): # request target api resp = client.get( - self.base_url.format(account_address="0x1234567890123456789012345678900000000000"), + self.base_url.format( + account_address="0x1234567890123456789012345678900000000000" + ), ) # assertion @@ -89,7 +88,9 @@ def test_normal_2(self, client, db): # request target api resp = client.get( - self.base_url.format(account_address="0x1234567890123456789012345678900000000000"), + self.base_url.format( + account_address="0x1234567890123456789012345678900000000000" + ), ) # assertion @@ -117,8 +118,6 @@ def test_error_1(self, client, db): # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, "title": "NotFound" - }, - "detail": "e2e messaging account is not exists" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "e2e messaging account is not exists", } diff --git a/tests/test_app_routers_e2e_messaging_accounts_{account_address}_eoa_password_POST.py b/tests/test_app_routers_e2e_messaging_accounts_{account_address}_eoa_password_POST.py index e918daa6..5eac6907 100644 --- a/tests/test_app_routers_e2e_messaging_accounts_{account_address}_eoa_password_POST.py +++ b/tests/test_app_routers_e2e_messaging_accounts_{account_address}_eoa_password_POST.py @@ -18,10 +18,10 @@ """ from eth_keyfile import decode_keyfile_json -from config import EOA_PASSWORD_PATTERN_MSG from app.model.blockchain import IbetStraightBondContract from app.model.db import E2EMessagingAccount from app.utils.e2ee_utils import E2EEUtils +from config import EOA_PASSWORD_PATTERN_MSG from tests.account_config import config_eth_account @@ -53,8 +53,7 @@ def test_normal_1(self, client, db, e2e_messaging_contract): "eoa_password": E2EEUtils.encrypt(new_password), } resp = client.post( - self.base_url.format(account_address=user_address_1), - json=req_param + self.base_url.format(account_address=user_address_1), json=req_param ) # assertion @@ -66,8 +65,7 @@ def test_normal_1(self, client, db, e2e_messaging_contract): # test new keyfile private_key = decode_keyfile_json( - raw_keyfile_json=_account.keyfile, - password=new_password.encode("utf-8") + raw_keyfile_json=_account.keyfile, password=new_password.encode("utf-8") ) arguments = [ "name_test", @@ -78,12 +76,10 @@ def test_normal_1(self, client, db, e2e_messaging_contract): 30, "return_date_test", "return_amount_test", - "purpose_test" + "purpose_test", ] IbetStraightBondContract().create( - args=arguments, - tx_from=user_address_1, - private_key=private_key + args=arguments, tx_from=user_address_1, private_key=private_key ) ########################################################################### @@ -94,22 +90,23 @@ def test_normal_1(self, client, db, e2e_messaging_contract): # Parameter Error # no body def test_error_1_1(self, client, db): - resp = client.post(self.base_url.format(account_address="0x1234567890123456789012345678900000000000")) + resp = client.post( + self.base_url.format( + account_address="0x1234567890123456789012345678900000000000" + ) + ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", } - ] + ], } # @@ -118,29 +115,28 @@ def test_error_1_1(self, client, db): def test_error_1_2(self, client, db): req_param = {} resp = client.post( - self.base_url.format(account_address="0x1234567890123456789012345678900000000000"), - json=req_param + self.base_url.format( + account_address="0x1234567890123456789012345678900000000000" + ), + json=req_param, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "old_eoa_password"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, { "loc": ["body", "eoa_password"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, - ] + ], } # @@ -154,29 +150,28 @@ def test_error_1_3(self, client, db): "eoa_password": new_password, } resp = client.post( - self.base_url.format(account_address="0x1234567890123456789012345678900000000000"), - json=req_param + self.base_url.format( + account_address="0x1234567890123456789012345678900000000000" + ), + json=req_param, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "old_eoa_password"], "msg": "old_eoa_password is not a Base64-encoded encrypted data", - "type": "value_error" + "type": "value_error", }, { "loc": ["body", "eoa_password"], "msg": "eoa_password is not a Base64-encoded encrypted data", - "type": "value_error" + "type": "value_error", }, - ] + ], } # @@ -189,17 +184,17 @@ def test_error_2(self, client, db): "eoa_password": E2EEUtils.encrypt(new_password), } resp = client.post( - self.base_url.format(account_address="0x1234567890123456789012345678900000000000"), - json=req_param + self.base_url.format( + account_address="0x1234567890123456789012345678900000000000" + ), + json=req_param, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, "title": "NotFound" - }, - "detail": "e2e messaging account is not exists" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "e2e messaging account is not exists", } # @@ -223,17 +218,14 @@ def test_normal_3(self, client, db, e2e_messaging_contract): "eoa_password": E2EEUtils.encrypt(new_password), } resp = client.post( - self.base_url.format(account_address=user_address_1), - json=req_param + self.base_url.format(account_address=user_address_1), json=req_param ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, "title": "InvalidParameterError" - }, - "detail": "old password mismatch" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "old password mismatch", } # @@ -257,15 +249,12 @@ def test_normal_4(self, client, db, e2e_messaging_contract): "eoa_password": E2EEUtils.encrypt(new_password), } resp = client.post( - self.base_url.format(account_address=user_address_1), - json=req_param + self.base_url.format(account_address=user_address_1), json=req_param ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, "title": "InvalidParameterError" - }, - "detail": EOA_PASSWORD_PATTERN_MSG + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": EOA_PASSWORD_PATTERN_MSG, } diff --git a/tests/test_app_routers_e2e_messaging_accounts_{account_address}_rsa_key_POST.py b/tests/test_app_routers_e2e_messaging_accounts_{account_address}_rsa_key_POST.py index 31120445..3ca96e90 100644 --- a/tests/test_app_routers_e2e_messaging_accounts_{account_address}_rsa_key_POST.py +++ b/tests/test_app_routers_e2e_messaging_accounts_{account_address}_rsa_key_POST.py @@ -19,10 +19,7 @@ import time from datetime import datetime -from app.model.db import ( - E2EMessagingAccount, - E2EMessagingAccountRsaKey -) +from app.model.db import E2EMessagingAccount, E2EMessagingAccountRsaKey class TestAppRoutersE2EMessagingAccountsAccountAddressRSAKeyPOST: @@ -67,7 +64,9 @@ def test_normal_1(self, client, db): "rsa_generation": 2, } resp = client.post( - self.base_url.format(account_address="0x1234567890123456789012345678900000000000"), + self.base_url.format( + account_address="0x1234567890123456789012345678900000000000" + ), json=req_param, ) @@ -116,7 +115,9 @@ def test_normal_2(self, client, db): # request target api req_param = {} resp = client.post( - self.base_url.format(account_address="0x1234567890123456789012345678900000000000"), + self.base_url.format( + account_address="0x1234567890123456789012345678900000000000" + ), json=req_param, ) @@ -141,22 +142,23 @@ def test_normal_2(self, client, db): # Parameter Error # no body def test_error_1_1(self, client, db): - resp = client.post(self.base_url.format(account_address="0x1234567890123456789012345678900000000000")) + resp = client.post( + self.base_url.format( + account_address="0x1234567890123456789012345678900000000000" + ) + ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", } - ] + ], } # @@ -168,31 +170,30 @@ def test_error_1_2(self, client, db): "rsa_generation": -1, } resp = client.post( - self.base_url.format(account_address="0x1234567890123456789012345678900000000000"), - json=req_param + self.base_url.format( + account_address="0x1234567890123456789012345678900000000000" + ), + json=req_param, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "rsa_key_generate_interval"], "ctx": {"limit_value": 0}, "msg": "ensure this value is greater than or equal to 0", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, { "loc": ["body", "rsa_generation"], "ctx": {"limit_value": 0}, "msg": "ensure this value is greater than or equal to 0", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, - ] + ], } # @@ -204,31 +205,30 @@ def test_error_1_3(self, client, db): "rsa_generation": 101, } resp = client.post( - self.base_url.format(account_address="0x1234567890123456789012345678900000000000"), - json=req_param + self.base_url.format( + account_address="0x1234567890123456789012345678900000000000" + ), + json=req_param, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "rsa_key_generate_interval"], "ctx": {"limit_value": 10_000}, "msg": "ensure this value is less than or equal to 10000", - "type": "value_error.number.not_le" + "type": "value_error.number.not_le", }, { "loc": ["body", "rsa_generation"], "ctx": {"limit_value": 100}, "msg": "ensure this value is less than or equal to 100", - "type": "value_error.number.not_le" + "type": "value_error.number.not_le", }, - ] + ], } # @@ -236,15 +236,15 @@ def test_error_1_3(self, client, db): def test_error_2(self, client, db): req_param = {} resp = client.post( - self.base_url.format(account_address="0x1234567890123456789012345678900000000000"), - json=req_param + self.base_url.format( + account_address="0x1234567890123456789012345678900000000000" + ), + json=req_param, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, "title": "NotFound" - }, - "detail": "e2e messaging account is not exists" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "e2e messaging account is not exists", } diff --git a/tests/test_app_routers_e2e_messaging_accounts_{account_address}_rsa_passphrase_POST.py b/tests/test_app_routers_e2e_messaging_accounts_{account_address}_rsa_passphrase_POST.py index 41a54bea..b16ebc51 100644 --- a/tests/test_app_routers_e2e_messaging_accounts_{account_address}_rsa_passphrase_POST.py +++ b/tests/test_app_routers_e2e_messaging_accounts_{account_address}_rsa_passphrase_POST.py @@ -22,12 +22,9 @@ from Crypto.Cipher import PKCS1_OAEP from Crypto.PublicKey import RSA -from config import E2E_MESSAGING_RSA_PASSPHRASE_PATTERN_MSG -from app.model.db import ( - E2EMessagingAccount, - E2EMessagingAccountRsaKey -) +from app.model.db import E2EMessagingAccount, E2EMessagingAccountRsaKey from app.utils.e2ee_utils import E2EEUtils +from config import E2E_MESSAGING_RSA_PASSPHRASE_PATTERN_MSG from tests.account_config import config_eth_account @@ -149,14 +146,17 @@ def test_normal_1(self, client, db, e2e_messaging_contract): "rsa_passphrase": E2EEUtils.encrypt(new_passphrase), } resp = client.post( - self.base_url.format(account_address=user_address_1), - json=req_param + self.base_url.format(account_address=user_address_1), json=req_param ) # assertion assert resp.status_code == 200 assert resp.json() is None - _rsa_key_list = db.query(E2EMessagingAccountRsaKey).order_by(E2EMessagingAccountRsaKey.block_timestamp).all() + _rsa_key_list = ( + db.query(E2EMessagingAccountRsaKey) + .order_by(E2EMessagingAccountRsaKey.block_timestamp) + .all() + ) assert len(_rsa_key_list) == 3 _rsa_key = _rsa_key_list[2] assert _rsa_key.rsa_private_key != self.rsa_private_key @@ -180,22 +180,23 @@ def test_normal_1(self, client, db, e2e_messaging_contract): # Parameter Error # no body def test_error_1_1(self, client, db): - resp = client.post(self.base_url.format(account_address="0x1234567890123456789012345678900000000000")) + resp = client.post( + self.base_url.format( + account_address="0x1234567890123456789012345678900000000000" + ) + ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", } - ] + ], } # @@ -204,29 +205,28 @@ def test_error_1_1(self, client, db): def test_error_1_2(self, client, db): req_param = {} resp = client.post( - self.base_url.format(account_address="0x1234567890123456789012345678900000000000"), - json=req_param + self.base_url.format( + account_address="0x1234567890123456789012345678900000000000" + ), + json=req_param, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "old_rsa_passphrase"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, { "loc": ["body", "rsa_passphrase"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, - ] + ], } # @@ -241,29 +241,28 @@ def test_error_1_3(self, client, db): "rsa_passphrase": new_passphrase, } resp = client.post( - self.base_url.format(account_address="0x1234567890123456789012345678900000000000"), - json=req_param + self.base_url.format( + account_address="0x1234567890123456789012345678900000000000" + ), + json=req_param, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "old_rsa_passphrase"], "msg": "old_rsa_passphrase is not a Base64-encoded encrypted data", - "type": "value_error" + "type": "value_error", }, { "loc": ["body", "rsa_passphrase"], "msg": "rsa_passphrase is not a Base64-encoded encrypted data", - "type": "value_error" + "type": "value_error", }, - ] + ], } # @@ -278,17 +277,17 @@ def test_error_2_1(self, client, db): "rsa_passphrase": E2EEUtils.encrypt(new_passphrase), } resp = client.post( - self.base_url.format(account_address="0x1234567890123456789012345678900000000000"), - json=req_param + self.base_url.format( + account_address="0x1234567890123456789012345678900000000000" + ), + json=req_param, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, "title": "NotFound" - }, - "detail": "e2e messaging account is not exists" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "e2e messaging account is not exists", } # @@ -314,17 +313,14 @@ def test_normal_2_2(self, client, db, e2e_messaging_contract): "rsa_passphrase": E2EEUtils.encrypt(new_passphrase), } resp = client.post( - self.base_url.format(account_address=user_address_1), - json=req_param + self.base_url.format(account_address=user_address_1), json=req_param ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, "title": "NotFound" - }, - "detail": "e2e messaging rsa key is not exists" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "e2e messaging rsa key is not exists", } # @@ -356,17 +352,14 @@ def test_normal_3(self, client, db, e2e_messaging_contract): "rsa_passphrase": E2EEUtils.encrypt(new_passphrase), } resp = client.post( - self.base_url.format(account_address=user_address_1), - json=req_param + self.base_url.format(account_address=user_address_1), json=req_param ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, "title": "InvalidParameterError" - }, - "detail": "old passphrase mismatch" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "old passphrase mismatch", } # @@ -398,15 +391,12 @@ def test_normal_4(self, client, db, e2e_messaging_contract): "rsa_passphrase": E2EEUtils.encrypt(new_passphrase), } resp = client.post( - self.base_url.format(account_address=user_address_1), - json=req_param + self.base_url.format(account_address=user_address_1), json=req_param ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, "title": "InvalidParameterError" - }, - "detail": E2E_MESSAGING_RSA_PASSPHRASE_PATTERN_MSG + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": E2E_MESSAGING_RSA_PASSPHRASE_PATTERN_MSG, } diff --git a/tests/test_app_routers_e2e_messaging_messages_GET.py b/tests/test_app_routers_e2e_messaging_messages_GET.py index 501e08b1..3cf132d5 100644 --- a/tests/test_app_routers_e2e_messaging_messages_GET.py +++ b/tests/test_app_routers_e2e_messaging_messages_GET.py @@ -19,10 +19,7 @@ import json from datetime import datetime -from app.model.db import ( - IDXE2EMessaging, - E2EMessagingAccount -) +from app.model.db import E2EMessagingAccount, IDXE2EMessaging class TestAppRoutersE2EMessagingMessagesGET: @@ -38,9 +35,11 @@ def insert_data(self, db, e2e_messaging): _e2e_messaging.send_timestamp = e2e_messaging["send_timestamp"] db.add(_e2e_messaging) - _account = db.query(E2EMessagingAccount). \ - filter(E2EMessagingAccount.account_address == e2e_messaging["to_address"]). \ - first() + _account = ( + db.query(E2EMessagingAccount) + .filter(E2EMessagingAccount.account_address == e2e_messaging["to_address"]) + .first() + ) if _account is None: _account = E2EMessagingAccount() _account.account_address = e2e_messaging["to_address"] @@ -61,13 +60,8 @@ def test_normal_1(self, client, db): # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 0, - "offset": None, - "limit": None, - "total": 0 - }, - "e2e_messages": [] + "result_set": {"count": 0, "offset": None, "limit": None, "total": 0}, + "e2e_messages": [], } # @@ -79,7 +73,9 @@ def test_normal_2(self, client, db): "to_address": "0x1234567890123456789012345678900000000000", "type": "type_test1", "message": "message_test1", - "send_timestamp": datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f'), # JST 2022/01/02 + "send_timestamp": datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ), # JST 2022/01/02 } self.insert_data(db, e2e_messaging) @@ -91,12 +87,7 @@ def test_normal_2(self, client, db): # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 1, - "offset": None, - "limit": None, - "total": 1 - }, + "result_set": {"count": 1, "offset": None, "limit": None, "total": 1}, "e2e_messages": [ { "id": 1, @@ -106,7 +97,7 @@ def test_normal_2(self, client, db): "message": "message_test1", "send_timestamp": "2022-01-02T00:20:30.000001+09:00", }, - ] + ], } # @@ -118,7 +109,9 @@ def test_normal_3(self, client, db): "to_address": "0x1234567890123456789012345678900000000000", "type": "type_test1", "message": "message_test1", - "send_timestamp": datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f'), # JST 2022/01/02 + "send_timestamp": datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ), # JST 2022/01/02 } self.insert_data(db, e2e_messaging) e2e_messaging = { @@ -126,7 +119,9 @@ def test_normal_3(self, client, db): "to_address": "0x1234567890123456789012345678900000000000", "type": "type_test2", "message": json.dumps({"aaa": 1, "bbb": True, "ccc": "hoge"}), - "send_timestamp": datetime.strptime("2022/01/01 15:20:31.000001", '%Y/%m/%d %H:%M:%S.%f'), # JST 2022/01/02 + "send_timestamp": datetime.strptime( + "2022/01/01 15:20:31.000001", "%Y/%m/%d %H:%M:%S.%f" + ), # JST 2022/01/02 } self.insert_data(db, e2e_messaging) e2e_messaging = { @@ -134,7 +129,9 @@ def test_normal_3(self, client, db): "to_address": "0x1234567890123456789012345678900000000001", "type": "type_test3", "message": json.dumps(["a", "b", "c"]), - "send_timestamp": datetime.strptime("2022/01/01 15:20:32.000001", '%Y/%m/%d %H:%M:%S.%f'), # JST 2022/01/02 + "send_timestamp": datetime.strptime( + "2022/01/01 15:20:32.000001", "%Y/%m/%d %H:%M:%S.%f" + ), # JST 2022/01/02 } self.insert_data(db, e2e_messaging) e2e_messaging = { @@ -142,15 +139,24 @@ def test_normal_3(self, client, db): "to_address": "0x1234567890123456789012345678900000000001", "type": "type_test4", "message": json.dumps(["a", 1, True]), - "send_timestamp": datetime.strptime("2022/01/01 15:20:33.000001", '%Y/%m/%d %H:%M:%S.%f'), # JST 2022/01/02 + "send_timestamp": datetime.strptime( + "2022/01/01 15:20:33.000001", "%Y/%m/%d %H:%M:%S.%f" + ), # JST 2022/01/02 } self.insert_data(db, e2e_messaging) e2e_messaging = { "from_address": "0x1234567890123456789012345678900000000010", "to_address": "0x1234567890123456789012345678900000000000", "type": "type_test0", - "message": json.dumps([{"aaa": 1, "bbb": True, "ccc": "hoge"}, {"aaa": 2, "bbb": False, "ccc": "fuga"}]), - "send_timestamp": datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f'), # JST 2022/01/02 + "message": json.dumps( + [ + {"aaa": 1, "bbb": True, "ccc": "hoge"}, + {"aaa": 2, "bbb": False, "ccc": "fuga"}, + ] + ), + "send_timestamp": datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ), # JST 2022/01/02 } self.insert_data(db, e2e_messaging) @@ -162,12 +168,7 @@ def test_normal_3(self, client, db): # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 5, - "offset": None, - "limit": None, - "total": 5 - }, + "result_set": {"count": 5, "offset": None, "limit": None, "total": 5}, "e2e_messages": [ { "id": 1, @@ -182,11 +183,7 @@ def test_normal_3(self, client, db): "from_address": "0x1234567890123456789012345678900000000011", "to_address": "0x1234567890123456789012345678900000000000", "type": "type_test2", - "message": { - "aaa": 1, - "bbb": True, - "ccc": "hoge" - }, + "message": {"aaa": 1, "bbb": True, "ccc": "hoge"}, "send_timestamp": "2022-01-02T00:20:31.000001+09:00", }, { @@ -211,20 +208,12 @@ def test_normal_3(self, client, db): "to_address": "0x1234567890123456789012345678900000000000", "type": "type_test0", "message": [ - { - "aaa": 1, - "bbb": True, - "ccc": "hoge" - }, - { - "aaa": 2, - "bbb": False, - "ccc": "fuga" - }, + {"aaa": 1, "bbb": True, "ccc": "hoge"}, + {"aaa": 2, "bbb": False, "ccc": "fuga"}, ], "send_timestamp": "2022-01-02T00:20:30.000001+09:00", }, - ] + ], } # @@ -237,7 +226,9 @@ def test_normal_4_1(self, client, db): "to_address": "0x1234567890123456789012345678900000000000", "type": "type_test1", "message": "message_test1", - "send_timestamp": datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f'), # JST 2022/01/02 + "send_timestamp": datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ), # JST 2022/01/02 } self.insert_data(db, e2e_messaging) e2e_messaging = { @@ -245,7 +236,9 @@ def test_normal_4_1(self, client, db): "to_address": "0x1234567890123456789012345678900000000001", "type": "type_test2", "message": "message_test2", - "send_timestamp": datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f'), # JST 2022/01/02 + "send_timestamp": datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ), # JST 2022/01/02 } self.insert_data(db, e2e_messaging) e2e_messaging = { @@ -253,27 +246,22 @@ def test_normal_4_1(self, client, db): "to_address": "0x1234567890123456789012345678900000000002", "type": "type_test3", "message": "message_test3", - "send_timestamp": datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f'), # JST 2022/01/02 + "send_timestamp": datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ), # JST 2022/01/02 } self.insert_data(db, e2e_messaging) # request target api resp = client.get( self.base_url, - params={ - "from_address": "0x1234567890123456789012345678900000000010" - } + params={"from_address": "0x1234567890123456789012345678900000000010"}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 2, - "offset": None, - "limit": None, - "total": 3 - }, + "result_set": {"count": 2, "offset": None, "limit": None, "total": 3}, "e2e_messages": [ { "id": 1, @@ -291,7 +279,7 @@ def test_normal_4_1(self, client, db): "message": "message_test3", "send_timestamp": "2022-01-02T00:20:30.000001+09:00", }, - ] + ], } # @@ -304,7 +292,9 @@ def test_normal_4_2(self, client, db): "to_address": "0x1234567890123456789012345678900000000000", "type": "type_test1", "message": "message_test1", - "send_timestamp": datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f'), # JST 2022/01/02 + "send_timestamp": datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ), # JST 2022/01/02 } self.insert_data(db, e2e_messaging) e2e_messaging = { @@ -312,7 +302,9 @@ def test_normal_4_2(self, client, db): "to_address": "0x1234567890123456789012345678900000000001", "type": "type_test2", "message": "message_test2", - "send_timestamp": datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f'), # JST 2022/01/02 + "send_timestamp": datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ), # JST 2022/01/02 } self.insert_data(db, e2e_messaging) e2e_messaging = { @@ -320,27 +312,22 @@ def test_normal_4_2(self, client, db): "to_address": "0x1234567890123456789012345678900000000000", "type": "type_test3", "message": "message_test3", - "send_timestamp": datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f'), # JST 2022/01/02 + "send_timestamp": datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ), # JST 2022/01/02 } self.insert_data(db, e2e_messaging) # request target api resp = client.get( self.base_url, - params={ - "to_address": "0x1234567890123456789012345678900000000000" - } + params={"to_address": "0x1234567890123456789012345678900000000000"}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 2, - "offset": None, - "limit": None, - "total": 3 - }, + "result_set": {"count": 2, "offset": None, "limit": None, "total": 3}, "e2e_messages": [ { "id": 1, @@ -358,7 +345,7 @@ def test_normal_4_2(self, client, db): "message": "message_test3", "send_timestamp": "2022-01-02T00:20:30.000001+09:00", }, - ] + ], } # @@ -371,7 +358,9 @@ def test_normal_4_3(self, client, db): "to_address": "0x1234567890123456789012345678900000000000", "type": "type_test1", "message": "message_test1", - "send_timestamp": datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f'), # JST 2022/01/02 + "send_timestamp": datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ), # JST 2022/01/02 } self.insert_data(db, e2e_messaging) e2e_messaging = { @@ -379,7 +368,9 @@ def test_normal_4_3(self, client, db): "to_address": "0x1234567890123456789012345678900000000001", "type": "type_test2", "message": "message_test2", - "send_timestamp": datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f'), # JST 2022/01/02 + "send_timestamp": datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ), # JST 2022/01/02 } self.insert_data(db, e2e_messaging) e2e_messaging = { @@ -387,27 +378,19 @@ def test_normal_4_3(self, client, db): "to_address": "0x1234567890123456789012345678900000000002", "type": "type_test1", "message": "message_test3", - "send_timestamp": datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f'), # JST 2022/01/02 + "send_timestamp": datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ), # JST 2022/01/02 } self.insert_data(db, e2e_messaging) # request target api - resp = client.get( - self.base_url, - params={ - "type": "type_test1" - } - ) + resp = client.get(self.base_url, params={"type": "type_test1"}) # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 2, - "offset": None, - "limit": None, - "total": 3 - }, + "result_set": {"count": 2, "offset": None, "limit": None, "total": 3}, "e2e_messages": [ { "id": 1, @@ -425,7 +408,7 @@ def test_normal_4_3(self, client, db): "message": "message_test3", "send_timestamp": "2022-01-02T00:20:30.000001+09:00", }, - ] + ], } # @@ -438,7 +421,9 @@ def test_normal_4_4(self, client, db): "to_address": "0x1234567890123456789012345678900000000000", "type": "type_test1", "message": "wordmessage_test1", - "send_timestamp": datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f'), # JST 2022/01/02 + "send_timestamp": datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ), # JST 2022/01/02 } self.insert_data(db, e2e_messaging) e2e_messaging = { @@ -446,7 +431,9 @@ def test_normal_4_4(self, client, db): "to_address": "0x1234567890123456789012345678900000000001", "type": "type_test2", "message": "message_test2", - "send_timestamp": datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f'), # JST 2022/01/02 + "send_timestamp": datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ), # JST 2022/01/02 } self.insert_data(db, e2e_messaging) e2e_messaging = { @@ -454,7 +441,9 @@ def test_normal_4_4(self, client, db): "to_address": "0x1234567890123456789012345678900000000002", "type": "type_test3", "message": "message_test3word", - "send_timestamp": datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f'), # JST 2022/01/02 + "send_timestamp": datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ), # JST 2022/01/02 } self.insert_data(db, e2e_messaging) e2e_messaging = { @@ -462,7 +451,9 @@ def test_normal_4_4(self, client, db): "to_address": "0x1234567890123456789012345678900000000003", "type": "type_test4", "message": "messageword_test4", - "send_timestamp": datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f'), # JST 2022/01/02 + "send_timestamp": datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ), # JST 2022/01/02 } self.insert_data(db, e2e_messaging) e2e_messaging = { @@ -470,27 +461,19 @@ def test_normal_4_4(self, client, db): "to_address": "0x1234567890123456789012345678900000000004", "type": "type_test5", "message": "word", - "send_timestamp": datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f'), # JST 2022/01/02 + "send_timestamp": datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ), # JST 2022/01/02 } self.insert_data(db, e2e_messaging) # request target api - resp = client.get( - self.base_url, - params={ - "message": "word" - } - ) + resp = client.get(self.base_url, params={"message": "word"}) # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 4, - "offset": None, - "limit": None, - "total": 5 - }, + "result_set": {"count": 4, "offset": None, "limit": None, "total": 5}, "e2e_messages": [ { "id": 1, @@ -524,7 +507,7 @@ def test_normal_4_4(self, client, db): "message": "word", "send_timestamp": "2022-01-02T00:20:30.000001+09:00", }, - ] + ], } # @@ -536,7 +519,9 @@ def test_normal_5(self, client, db): "to_address": "0x1234567890123456789012345678900000000000", "type": "type_test1", "message": "message_test1", - "send_timestamp": datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f'), # JST 2022/01/02 + "send_timestamp": datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ), # JST 2022/01/02 } self.insert_data(db, e2e_messaging) e2e_messaging = { @@ -544,7 +529,9 @@ def test_normal_5(self, client, db): "to_address": "0x1234567890123456789012345678900000000000", "type": "type_test2", "message": json.dumps({"aaa": 1, "bbb": True, "ccc": "hoge"}), - "send_timestamp": datetime.strptime("2022/01/01 15:20:31.000001", '%Y/%m/%d %H:%M:%S.%f'), # JST 2022/01/02 + "send_timestamp": datetime.strptime( + "2022/01/01 15:20:31.000001", "%Y/%m/%d %H:%M:%S.%f" + ), # JST 2022/01/02 } self.insert_data(db, e2e_messaging) e2e_messaging = { @@ -552,7 +539,9 @@ def test_normal_5(self, client, db): "to_address": "0x1234567890123456789012345678900000000001", "type": "type_test3", "message": json.dumps(["a", "b", "c"]), - "send_timestamp": datetime.strptime("2022/01/01 15:20:32.000001", '%Y/%m/%d %H:%M:%S.%f'), # JST 2022/01/02 + "send_timestamp": datetime.strptime( + "2022/01/01 15:20:32.000001", "%Y/%m/%d %H:%M:%S.%f" + ), # JST 2022/01/02 } self.insert_data(db, e2e_messaging) e2e_messaging = { @@ -560,15 +549,24 @@ def test_normal_5(self, client, db): "to_address": "0x1234567890123456789012345678900000000001", "type": "type_test4", "message": json.dumps(["a", 1, True]), - "send_timestamp": datetime.strptime("2022/01/01 15:20:33.000001", '%Y/%m/%d %H:%M:%S.%f'), # JST 2022/01/02 + "send_timestamp": datetime.strptime( + "2022/01/01 15:20:33.000001", "%Y/%m/%d %H:%M:%S.%f" + ), # JST 2022/01/02 } self.insert_data(db, e2e_messaging) e2e_messaging = { "from_address": "0x1234567890123456789012345678900000000010", "to_address": "0x1234567890123456789012345678900000000000", "type": "type_test0", - "message": json.dumps([{"aaa": 1, "bbb": True, "ccc": "hoge"}, {"aaa": 2, "bbb": False, "ccc": "fuga"}]), - "send_timestamp": datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f'), # JST 2022/01/02 + "message": json.dumps( + [ + {"aaa": 1, "bbb": True, "ccc": "hoge"}, + {"aaa": 2, "bbb": False, "ccc": "fuga"}, + ] + ), + "send_timestamp": datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ), # JST 2022/01/02 } self.insert_data(db, e2e_messaging) @@ -578,30 +576,21 @@ def test_normal_5(self, client, db): params={ "offset": 1, "limit": 2, - } + }, ) # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 5, - "offset": 1, - "limit": 2, - "total": 5 - }, + "result_set": {"count": 5, "offset": 1, "limit": 2, "total": 5}, "e2e_messages": [ { "id": 2, "from_address": "0x1234567890123456789012345678900000000011", "to_address": "0x1234567890123456789012345678900000000000", "type": "type_test2", - "message": { - "aaa": 1, - "bbb": True, - "ccc": "hoge" - }, - "send_timestamp": "2022-01-02T00:20:31.000001+09:00" + "message": {"aaa": 1, "bbb": True, "ccc": "hoge"}, + "send_timestamp": "2022-01-02T00:20:31.000001+09:00", }, { "id": 3, @@ -609,9 +598,9 @@ def test_normal_5(self, client, db): "to_address": "0x1234567890123456789012345678900000000001", "type": "type_test3", "message": ["a", "b", "c"], - "send_timestamp": "2022-01-02T00:20:32.000001+09:00" - } - ] + "send_timestamp": "2022-01-02T00:20:32.000001+09:00", + }, + ], } ########################################################################### @@ -625,29 +614,23 @@ def test_error_1(self, client, db): # request target API resp = client.get( self.base_url, - params={ - "offset": "test", - "limit": "test" - }, + params={"offset": "test", "limit": "test"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["query", "offset"], "msg": "value is not a valid integer", - "type": "type_error.integer" + "type": "type_error.integer", }, { "loc": ["query", "limit"], "msg": "value is not a valid integer", - "type": "type_error.integer" + "type": "type_error.integer", }, - ] + ], } diff --git a/tests/test_app_routers_e2e_messaging_messages_{id}_GET.py b/tests/test_app_routers_e2e_messaging_messages_{id}_GET.py index 438647e7..479df4d0 100644 --- a/tests/test_app_routers_e2e_messaging_messages_{id}_GET.py +++ b/tests/test_app_routers_e2e_messaging_messages_{id}_GET.py @@ -19,10 +19,7 @@ import json from datetime import datetime -from app.model.db import ( - IDXE2EMessaging, - E2EMessagingAccount -) +from app.model.db import E2EMessagingAccount, IDXE2EMessaging class TestAppRoutersE2EMessagingMessagesIdGET: @@ -40,9 +37,11 @@ def insert_data(self, db, e2e_messaging): _e2e_messaging.send_timestamp = e2e_messaging["send_timestamp"] db.add(_e2e_messaging) - _account = db.query(E2EMessagingAccount). \ - filter(E2EMessagingAccount.account_address == e2e_messaging["to_address"]). \ - first() + _account = ( + db.query(E2EMessagingAccount) + .filter(E2EMessagingAccount.account_address == e2e_messaging["to_address"]) + .first() + ) if _account is None: _account = E2EMessagingAccount() _account.account_address = e2e_messaging["to_address"] @@ -62,7 +61,9 @@ def test_normal_1_1(self, client, db): "to_address": "0x1234567890123456789012345678900000000000", "type": "type_test1", "message": "message_test1", - "send_timestamp": datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f'), # JST 2022/01/02 + "send_timestamp": datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ), # JST 2022/01/02 } self.insert_data(db, e2e_messaging) @@ -92,7 +93,9 @@ def test_normal_1_2(self, client, db): "to_address": "0x1234567890123456789012345678900000000000", "type": "type_test1", "message": json.dumps({"aaa": 1, "bbb": True, "ccc": "hoge"}), - "send_timestamp": datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f'), # JST 2022/01/02 + "send_timestamp": datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ), # JST 2022/01/02 } self.insert_data(db, e2e_messaging) @@ -108,11 +111,7 @@ def test_normal_1_2(self, client, db): "from_address": "0x1234567890123456789012345678900000000010", "to_address": "0x1234567890123456789012345678900000000000", "type": "type_test1", - "message": { - "aaa": 1, - "bbb": True, - "ccc": "hoge" - }, + "message": {"aaa": 1, "bbb": True, "ccc": "hoge"}, "send_timestamp": "2022-01-02T00:20:30.000001+09:00", } @@ -126,7 +125,9 @@ def test_normal_1_3(self, client, db): "to_address": "0x1234567890123456789012345678900000000000", "type": "type_test1", "message": json.dumps(["a", 1, True]), - "send_timestamp": datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f'), # JST 2022/01/02 + "send_timestamp": datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ), # JST 2022/01/02 } self.insert_data(db, e2e_messaging) @@ -155,8 +156,15 @@ def test_normal_1_4(self, client, db): "from_address": "0x1234567890123456789012345678900000000010", "to_address": "0x1234567890123456789012345678900000000000", "type": "type_test1", - "message": json.dumps([{"aaa": 1, "bbb": True, "ccc": "hoge"}, {"aaa": 2, "bbb": False, "ccc": "fuga"}]), - "send_timestamp": datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f'), # JST 2022/01/02 + "message": json.dumps( + [ + {"aaa": 1, "bbb": True, "ccc": "hoge"}, + {"aaa": 2, "bbb": False, "ccc": "fuga"}, + ] + ), + "send_timestamp": datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ), # JST 2022/01/02 } self.insert_data(db, e2e_messaging) @@ -173,16 +181,8 @@ def test_normal_1_4(self, client, db): "to_address": "0x1234567890123456789012345678900000000000", "type": "type_test1", "message": [ - { - "aaa": 1, - "bbb": True, - "ccc": "hoge" - }, - { - "aaa": 2, - "bbb": False, - "ccc": "fuga" - } + {"aaa": 1, "bbb": True, "ccc": "hoge"}, + {"aaa": 2, "bbb": False, "ccc": "fuga"}, ], "send_timestamp": "2022-01-02T00:20:30.000001+09:00", } @@ -196,24 +196,19 @@ def test_normal_1_4(self, client, db): # no data def test_error_1(self, client, db): # request target API - resp = client.get( - self.base_url.format(id="id") - ) + resp = client.get(self.base_url.format(id="id")) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['path', 'id'], - 'msg': 'value is not a valid integer', - 'type': 'type_error.integer' + "loc": ["path", "id"], + "msg": "value is not a valid integer", + "type": "type_error.integer", } - ] + ], } # @@ -227,7 +222,9 @@ def test_error_2(self, client, db): "to_address": "0x1234567890123456789012345678900000000000", "type": "type_test1", "message": "test_message1", - "send_timestamp": datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f'), # JST 2022/01/02 + "send_timestamp": datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ), # JST 2022/01/02 } self.insert_data(db, e2e_messaging) @@ -239,9 +236,6 @@ def test_error_2(self, client, db): # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, + "meta": {"code": 1, "title": "NotFound"}, "detail": "e2e messaging not found", } diff --git a/tests/test_app_routers_e2ee_GET.py b/tests/test_app_routers_e2ee_GET.py index 04458ccd..878cb352 100644 --- a/tests/test_app_routers_e2ee_GET.py +++ b/tests/test_app_routers_e2ee_GET.py @@ -35,14 +35,14 @@ def test_normal_1(self, client, db): assert resp.status_code == 200 assert resp.json() == { "public_key": "-----BEGIN PUBLIC KEY-----\n" - "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuJ52ArJ9eEGjJdhUHE4c\n" - "jekmlfNYztqPWMMj/JtfCMR/B0BOqWdrwOQ4eNTv0IgW+5pGPszD8KSctCI1vy47\n" - "ZjCTPndZp7ypDqUpyVBqonZ3XCpQrjqwHy3Pn1HT3+xiQzTxFxVOQZ7ftQyziviD\n" - "1vfGzWfZ/Ww5g+y/tEgMbmw8+6XwVMmwPeKtNYM1t9SrPkm27Tvw3upVYL3Pq2hv\n" - "9pBfM60xV834MkL8KWPdQlTHMJvQ8cRjoAO9kycVe3xN2qq5ShiMGSwaEn5FiC2z\n" - "iVfprRkMGXgi02K7XunKcmpr56oDk16ltyqvpWJMdqYLzK50JYh+C7ipgk+S4D9y\n" - "5QIDAQAB\n" - "-----END PUBLIC KEY-----" + "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuJ52ArJ9eEGjJdhUHE4c\n" + "jekmlfNYztqPWMMj/JtfCMR/B0BOqWdrwOQ4eNTv0IgW+5pGPszD8KSctCI1vy47\n" + "ZjCTPndZp7ypDqUpyVBqonZ3XCpQrjqwHy3Pn1HT3+xiQzTxFxVOQZ7ftQyziviD\n" + "1vfGzWfZ/Ww5g+y/tEgMbmw8+6XwVMmwPeKtNYM1t9SrPkm27Tvw3upVYL3Pq2hv\n" + "9pBfM60xV834MkL8KWPdQlTHMJvQ8cRjoAO9kycVe3xN2qq5ShiMGSwaEn5FiC2z\n" + "iVfprRkMGXgi02K7XunKcmpr56oDk16ltyqvpWJMdqYLzK50JYh+C7ipgk+S4D9y\n" + "5QIDAQAB\n" + "-----END PUBLIC KEY-----" } ########################################################################### diff --git a/tests/test_app_routers_files_GET.py b/tests/test_app_routers_files_GET.py index dc2a3242..7749e271 100644 --- a/tests/test_app_routers_files_GET.py +++ b/tests/test_app_routers_files_GET.py @@ -45,13 +45,8 @@ def test_normal_1(self, client, db): # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 0, - "offset": None, - "limit": None, - "total": 0 - }, - "files": [] + "result_set": {"count": 0, "offset": None, "limit": None, "total": 0}, + "files": [], } # @@ -69,7 +64,9 @@ def test_normal_2(self, client, db): _upload_file.content_size = len(file_content_1_bin) _upload_file.description = "description_1" _upload_file.label = "label_1" - _upload_file.created = datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/02 + _upload_file.created = datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/02 db.add(_upload_file) # request target api @@ -80,12 +77,7 @@ def test_normal_2(self, client, db): # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 1, - "offset": None, - "limit": None, - "total": 1 - }, + "result_set": {"count": 1, "offset": None, "limit": None, "total": 1}, "files": [ { "file_id": "file_id_1", @@ -97,7 +89,7 @@ def test_normal_2(self, client, db): "label": "label_1", "created": "2022-01-02T00:20:30.000001+09:00", }, - ] + ], } # @@ -115,7 +107,9 @@ def test_normal_3(self, client, db): _upload_file.content_size = len(file_content_bin) _upload_file.description = "description_1" _upload_file.label = "label_1" - _upload_file.created = datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/02 + _upload_file.created = datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/02 db.add(_upload_file) _upload_file = UploadFile() @@ -127,7 +121,9 @@ def test_normal_3(self, client, db): _upload_file.content_size = len(file_content_bin) _upload_file.description = "description_2" _upload_file.label = "label_2" - _upload_file.created = datetime.strptime("2022/01/02 00:20:30.000001", '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/02 + _upload_file.created = datetime.strptime( + "2022/01/02 00:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/02 db.add(_upload_file) # request target api @@ -138,12 +134,7 @@ def test_normal_3(self, client, db): # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 2, - "offset": None, - "limit": None, - "total": 2 - }, + "result_set": {"count": 2, "offset": None, "limit": None, "total": 2}, "files": [ { "file_id": "file_id_2", @@ -165,7 +156,7 @@ def test_normal_3(self, client, db): "label": "label_1", "created": "2022-01-02T00:20:30.000001+09:00", }, - ] + ], } # @@ -184,19 +175,25 @@ def test_normal_4_1(self, client, db): _upload_file.content_size = len(file_content_bin) _upload_file.description = "description_1" _upload_file.label = "label_1" - _upload_file.created = datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/02 + _upload_file.created = datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/02 db.add(_upload_file) _upload_file = UploadFile() _upload_file.file_id = "file_id_2" - _upload_file.issuer_address = "0x1234567890123456789012345678900000000002" # not target + _upload_file.issuer_address = ( + "0x1234567890123456789012345678900000000002" # not target + ) _upload_file.relation = self.token_address _upload_file.file_name = "file_name_2" _upload_file.content = file_content_bin _upload_file.content_size = len(file_content_bin) _upload_file.description = "description_2" _upload_file.label = "label_2" - _upload_file.created = datetime.strptime("2022/01/02 00:20:30.000001", '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/02 + _upload_file.created = datetime.strptime( + "2022/01/02 00:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/02 db.add(_upload_file) # request target api @@ -210,12 +207,7 @@ def test_normal_4_1(self, client, db): # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 1, - "offset": None, - "limit": None, - "total": 2 - }, + "result_set": {"count": 1, "offset": None, "limit": None, "total": 2}, "files": [ { "file_id": "file_id_1", @@ -227,7 +219,7 @@ def test_normal_4_1(self, client, db): "label": "label_1", "created": "2022-01-02T00:20:30.000001+09:00", }, - ] + ], } # @@ -246,7 +238,9 @@ def test_normal_4_2(self, client, db): _upload_file.content_size = len(file_content_bin) _upload_file.description = "description_1" _upload_file.label = "label_1" - _upload_file.created = datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/02 + _upload_file.created = datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/02 db.add(_upload_file) _upload_file = UploadFile() @@ -258,7 +252,9 @@ def test_normal_4_2(self, client, db): _upload_file.content_size = len(file_content_bin) _upload_file.description = "description_2" _upload_file.label = "label_2" - _upload_file.created = datetime.strptime("2022/01/02 00:20:30.000001", '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/02 + _upload_file.created = datetime.strptime( + "2022/01/02 00:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/02 db.add(_upload_file) # request target api @@ -272,12 +268,7 @@ def test_normal_4_2(self, client, db): # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 1, - "offset": None, - "limit": None, - "total": 2 - }, + "result_set": {"count": 1, "offset": None, "limit": None, "total": 2}, "files": [ { "file_id": "file_id_1", @@ -289,7 +280,7 @@ def test_normal_4_2(self, client, db): "label": "label_1", "created": "2022-01-02T00:20:30.000001+09:00", }, - ] + ], } # @@ -308,7 +299,9 @@ def test_normal_4_3(self, client, db): _upload_file.content_size = len(file_content_bin) _upload_file.description = "description_1" _upload_file.label = "label_1" - _upload_file.created = datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/02 + _upload_file.created = datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/02 db.add(_upload_file) _upload_file = UploadFile() @@ -320,7 +313,9 @@ def test_normal_4_3(self, client, db): _upload_file.content_size = len(file_content_bin) _upload_file.description = "description_2" _upload_file.label = "label_2" - _upload_file.created = datetime.strptime("2022/01/02 00:20:30.000001", '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/02 + _upload_file.created = datetime.strptime( + "2022/01/02 00:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/02 db.add(_upload_file) # request target api @@ -334,12 +329,7 @@ def test_normal_4_3(self, client, db): # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 1, - "offset": None, - "limit": None, - "total": 2 - }, + "result_set": {"count": 1, "offset": None, "limit": None, "total": 2}, "files": [ { "file_id": "file_id_1", @@ -351,7 +341,7 @@ def test_normal_4_3(self, client, db): "label": "label_1", "created": "2022-01-02T00:20:30.000001+09:00", }, - ] + ], } # @@ -370,7 +360,9 @@ def test_normal_4_4_1(self, client, db): _upload_file.content_size = len(file_content_bin) _upload_file.description = "description_1" _upload_file.label = "" - _upload_file.created = datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/02 + _upload_file.created = datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/02 db.add(_upload_file) _upload_file = UploadFile() @@ -382,7 +374,9 @@ def test_normal_4_4_1(self, client, db): _upload_file.content_size = len(file_content_bin) _upload_file.description = "description_2" _upload_file.label = "label_2" # not null - _upload_file.created = datetime.strptime("2022/01/02 00:20:30.000001", '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/02 + _upload_file.created = datetime.strptime( + "2022/01/02 00:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/02 db.add(_upload_file) _upload_file = UploadFile() @@ -394,7 +388,9 @@ def test_normal_4_4_1(self, client, db): _upload_file.content_size = len(file_content_bin) _upload_file.description = "description_3" _upload_file.label = " " # half-width space - _upload_file.created = datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/02 + _upload_file.created = datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/02 db.add(_upload_file) _upload_file = UploadFile() @@ -406,7 +402,9 @@ def test_normal_4_4_1(self, client, db): _upload_file.content_size = len(file_content_bin) _upload_file.description = "description_4" _upload_file.label = " " # full-width space - _upload_file.created = datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/02 + _upload_file.created = datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/02 db.add(_upload_file) # request target api @@ -420,12 +418,7 @@ def test_normal_4_4_1(self, client, db): # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 1, - "offset": None, - "limit": None, - "total": 4 - }, + "result_set": {"count": 1, "offset": None, "limit": None, "total": 4}, "files": [ { "file_id": "file_id_1", @@ -437,7 +430,7 @@ def test_normal_4_4_1(self, client, db): "label": "", "created": "2022-01-02T00:20:30.000001+09:00", }, - ] + ], } # @@ -456,7 +449,9 @@ def test_normal_4_4_2(self, client, db): _upload_file.content_size = len(file_content_bin) _upload_file.description = "description_1" _upload_file.label = "単語label_1" - _upload_file.created = datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/02 + _upload_file.created = datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/02 db.add(_upload_file) _upload_file = UploadFile() @@ -468,7 +463,9 @@ def test_normal_4_4_2(self, client, db): _upload_file.content_size = len(file_content_bin) _upload_file.description = "description_2" _upload_file.label = "label_2" # not target - _upload_file.created = datetime.strptime("2022/01/02 00:20:30.000001", '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/02 + _upload_file.created = datetime.strptime( + "2022/01/02 00:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/02 db.add(_upload_file) _upload_file = UploadFile() @@ -480,7 +477,9 @@ def test_normal_4_4_2(self, client, db): _upload_file.content_size = len(file_content_bin) _upload_file.description = "description_3" _upload_file.label = "label単語_3" - _upload_file.created = datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/02 + _upload_file.created = datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/02 db.add(_upload_file) _upload_file = UploadFile() @@ -492,7 +491,9 @@ def test_normal_4_4_2(self, client, db): _upload_file.content_size = len(file_content_bin) _upload_file.description = "description_4" _upload_file.label = "label_4単語" - _upload_file.created = datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/02 + _upload_file.created = datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/02 db.add(_upload_file) # request target api @@ -506,12 +507,7 @@ def test_normal_4_4_2(self, client, db): # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 3, - "offset": None, - "limit": None, - "total": 4 - }, + "result_set": {"count": 3, "offset": None, "limit": None, "total": 4}, "files": [ { "file_id": "file_id_4", @@ -543,7 +539,7 @@ def test_normal_4_4_2(self, client, db): "label": "単語label_1", "created": "2022-01-02T00:20:30.000001+09:00", }, - ] + ], } # @@ -561,7 +557,9 @@ def test_normal_5(self, client, db): _upload_file.content_size = len(file_content_bin) _upload_file.description = "description_1" _upload_file.label = "label_1" - _upload_file.created = datetime.strptime("2022/01/01 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/02 + _upload_file.created = datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/02 db.add(_upload_file) _upload_file = UploadFile() @@ -573,7 +571,9 @@ def test_normal_5(self, client, db): _upload_file.content_size = len(file_content_bin) _upload_file.description = "description_2" _upload_file.label = "label_2" - _upload_file.created = datetime.strptime("2022/01/02 00:20:30.000001", '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/02 + _upload_file.created = datetime.strptime( + "2022/01/02 00:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/02 db.add(_upload_file) _upload_file = UploadFile() @@ -585,7 +585,9 @@ def test_normal_5(self, client, db): _upload_file.content_size = len(file_content_bin) _upload_file.description = "description_3" _upload_file.label = "label_3" - _upload_file.created = datetime.strptime("2022/01/02 15:20:30.000001", '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/03 + _upload_file.created = datetime.strptime( + "2022/01/02 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/03 db.add(_upload_file) _upload_file = UploadFile() @@ -597,27 +599,21 @@ def test_normal_5(self, client, db): _upload_file.content_size = len(file_content_bin) _upload_file.description = "description_4" _upload_file.label = "label_4" - _upload_file.created = datetime.strptime("2022/01/03 00:20:30.000001", '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/03 + _upload_file.created = datetime.strptime( + "2022/01/03 00:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/03 db.add(_upload_file) # request target api resp = client.get( self.base_url, - params={ - "offset": 1, - "limit": 2 - }, + params={"offset": 1, "limit": 2}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 4, - "offset": 1, - "limit": 2, - "total": 4 - }, + "result_set": {"count": 4, "offset": 1, "limit": 2, "total": 4}, "files": [ { "file_id": "file_id_3", @@ -639,7 +635,7 @@ def test_normal_5(self, client, db): "label": "label_2", "created": "2022-01-02T09:20:30.000001+09:00", }, - ] + ], } ########################################################################### @@ -650,42 +646,34 @@ def test_normal_5(self, client, db): # Parameter Error # Query def test_error_1(self, client, db): - # request target API resp = client.get( self.base_url, - params={ - "offset": "test", - "limit": "test" - }, + params={"offset": "test", "limit": "test"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["query", "offset"], "msg": "value is not a valid integer", - "type": "type_error.integer" + "type": "type_error.integer", }, { "loc": ["query", "limit"], "msg": "value is not a valid integer", - "type": "type_error.integer" + "type": "type_error.integer", }, - ] + ], } # # Parameter Error # Header def test_error_2(self, client, db): - # request target API resp = client.get( self.base_url, @@ -697,15 +685,12 @@ def test_error_2(self, client, db): # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] - } \ No newline at end of file + ], + } diff --git a/tests/test_app_routers_files_POST.py b/tests/test_app_routers_files_POST.py index 0ca70714..e26936e5 100644 --- a/tests/test_app_routers_files_POST.py +++ b/tests/test_app_routers_files_POST.py @@ -18,10 +18,11 @@ """ import base64 from unittest import mock + import pytz -from config import TZ from app.model.db import UploadFile +from config import TZ local_tz = pytz.timezone(TZ) utc_tz = pytz.timezone("UTC") @@ -54,7 +55,7 @@ def test_normal_1(self, client, db): "file_name": "file_name_1", "content": base64.b64encode(file_content_bin).decode(), "description": "description_1", - "label": "label_1" + "label": "label_1", } resp = client.post( self.base_url, @@ -85,13 +86,15 @@ def test_normal_1(self, client, db): "content_size": len(file_content_bin), "description": req_param["description"], "label": req_param["label"], - "created": utc_tz.localize(_upload_file.created).astimezone(local_tz).isoformat() + "created": utc_tz.localize(_upload_file.created) + .astimezone(local_tz) + .isoformat(), } # # binary file def test_normal_2(self, client, db): - file_content_bin = b'x00x01x02x03x04x05x06x07' + file_content_bin = b"x00x01x02x03x04x05x06x07" # request target api req_param = { @@ -99,7 +102,7 @@ def test_normal_2(self, client, db): "file_name": "file_name_1", "content": base64.b64encode(file_content_bin).decode(), "description": "description_1", - "label": "label_1" + "label": "label_1", } resp = client.post( self.base_url, @@ -130,7 +133,9 @@ def test_normal_2(self, client, db): "content_size": len(file_content_bin), "description": req_param["description"], "label": req_param["label"], - "created": utc_tz.localize(_upload_file.created).astimezone(local_tz).isoformat() + "created": utc_tz.localize(_upload_file.created) + .astimezone(local_tz) + .isoformat(), } # @@ -144,7 +149,7 @@ def test_normal_3(self, client, db): "relation": self.token_address, "file_name": "file_name_1", "content": base64.b64encode(file_content_bin).decode(), - "description": "description_1" + "description": "description_1", } resp = client.post( self.base_url, @@ -175,7 +180,9 @@ def test_normal_3(self, client, db): "content_size": len(file_content_bin), "description": req_param["description"], "label": "", - "created": utc_tz.localize(_upload_file.created).astimezone(local_tz).isoformat() + "created": utc_tz.localize(_upload_file.created) + .astimezone(local_tz) + .isoformat(), } ########################################################################### @@ -195,22 +202,19 @@ def test_error_1(self, client, db): # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, { "loc": ["body"], "msg": "field required", - "type": "value_error.missing" - } - ] + "type": "value_error.missing", + }, + ], } # @@ -230,22 +234,19 @@ def test_error_2(self, client, db): # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "file_name"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, { "loc": ["body", "content"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, - ] + ], } # @@ -254,7 +255,7 @@ def test_error_2(self, client, db): # Body @mock.patch("app.model.schema.file.MAX_UPLOAD_FILE_SIZE", 6) def test_error_3(self, client, db): - file_content_bin = b'x00x01x02x03x04x05x06x07' + file_content_bin = b"x00x01x02x03x04x05x06x07" # request target api resp = client.post( @@ -262,35 +263,35 @@ def test_error_3(self, client, db): json={ "relation": "123456789012345678901234567890123456789012345678901", "file_name": "12345678901234567890123456789012345678901234567890" - "12345678901234567890123456789012345678901234567890" - "12345678901234567890123456789012345678901234567890" - "12345678901234567890123456789012345678901234567890" - "123456789012345678901234567890123456789012345678901234567", + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "123456789012345678901234567890123456789012345678901234567", "content": base64.b64encode(file_content_bin).decode(), "description": "12345678901234567890123456789012345678901234567890" - "12345678901234567890123456789012345678901234567890" - "12345678901234567890123456789012345678901234567890" - "12345678901234567890123456789012345678901234567890" - "12345678901234567890123456789012345678901234567890" - "12345678901234567890123456789012345678901234567890" - "12345678901234567890123456789012345678901234567890" - "12345678901234567890123456789012345678901234567890" - "12345678901234567890123456789012345678901234567890" - "12345678901234567890123456789012345678901234567890" - "12345678901234567890123456789012345678901234567890" - "12345678901234567890123456789012345678901234567890" - "12345678901234567890123456789012345678901234567890" - "12345678901234567890123456789012345678901234567890" - "12345678901234567890123456789012345678901234567890" - "12345678901234567890123456789012345678901234567890" - "12345678901234567890123456789012345678901234567890" - "12345678901234567890123456789012345678901234567890" - "12345678901234567890123456789012345678901234567890" - "123456789012345678901234567890123456789012345678901", + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "123456789012345678901234567890123456789012345678901", "label": "12345678901234567890123456789012345678901234567890" - "12345678901234567890123456789012345678901234567890" - "12345678901234567890123456789012345678901234567890" - "123456789012345678901234567890123456789012345678901" + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "123456789012345678901234567890123456789012345678901", }, headers={ "issuer-address": self.issuer_address, @@ -300,22 +301,19 @@ def test_error_3(self, client, db): # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "relation"], "msg": "ensure this value has at most 50 characters", "type": "value_error.any_str.max_length", - "ctx": {"limit_value": 50} + "ctx": {"limit_value": 50}, }, { "loc": ["body", "file_name"], "msg": "ensure this value has at most 256 characters", "type": "value_error.any_str.max_length", - "ctx": {"limit_value": 256} + "ctx": {"limit_value": 256}, }, { "loc": ["body", "content"], @@ -326,22 +324,21 @@ def test_error_3(self, client, db): "loc": ["body", "description"], "msg": "ensure this value has at most 1000 characters", "type": "value_error.any_str.max_length", - "ctx": {"limit_value": 1000} + "ctx": {"limit_value": 1000}, }, { "loc": ["body", "label"], "msg": "ensure this value has at most 200 characters", "type": "value_error.any_str.max_length", - "ctx": {"limit_value": 200} + "ctx": {"limit_value": 200}, }, - ] + ], } # # Parameter Error # Not Base64 def test_error_4(self, client, db): - # request target api req_param = { "relation": self.token_address, @@ -361,15 +358,12 @@ def test_error_4(self, client, db): # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "content"], "msg": "content is not a Base64-encoded string", "type": "value_error", }, - ] + ], } diff --git a/tests/test_app_routers_files_{file_id}_DELETE.py b/tests/test_app_routers_files_{file_id}_DELETE.py index 8e1f4b29..c6e8321f 100644 --- a/tests/test_app_routers_files_{file_id}_DELETE.py +++ b/tests/test_app_routers_files_{file_id}_DELETE.py @@ -85,17 +85,14 @@ def test_error_1(self, client, db): # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, - ] + ], } # @@ -113,17 +110,14 @@ def test_error_2(self, client, db): # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -140,7 +134,9 @@ def test_error_3(self, client, db): # prepare data _upload_file = UploadFile() _upload_file.file_id = "file_id_1" - _upload_file.issuer_address = "0x1234567890123456789012345678900000000002" # not target + _upload_file.issuer_address = ( + "0x1234567890123456789012345678900000000002" # not target + ) _upload_file.relation = self.token_address _upload_file.file_name = "file_name_1" _upload_file.content = file_content_bin @@ -160,9 +156,6 @@ def test_error_3(self, client, db): # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "file not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "file not found", } diff --git a/tests/test_app_routers_files_{file_id}_GET.py b/tests/test_app_routers_files_{file_id}_GET.py index 88ea6106..15042103 100644 --- a/tests/test_app_routers_files_{file_id}_GET.py +++ b/tests/test_app_routers_files_{file_id}_GET.py @@ -121,8 +121,7 @@ def test_normal_1_2(self, client, db): # # binary file def test_normal_2(self, client, db): - - file_content_bin = b'x00x01x02x03x04x05x06x07' + file_content_bin = b"x00x01x02x03x04x05x06x07" # prepare data _upload_file = UploadFile() @@ -162,7 +161,6 @@ def test_normal_2(self, client, db): # Parameter Error # Invalid def test_error_1(self, client, db): - # request target API resp = client.get( self.base_url.format(file_id="file_id_1"), @@ -174,24 +172,20 @@ def test_error_1(self, client, db): # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # # Not Found # unset header def test_error_2_1(self, client, db): - # request target API resp = client.get( self.base_url.format(file_id="file_id_1"), @@ -200,24 +194,22 @@ def test_error_2_1(self, client, db): # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "file not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "file not found", } # # Not Found # set header def test_error_2_2(self, client, db): - - file_content_bin = b'x00x01x02x03x04x05x06x07' + file_content_bin = b"x00x01x02x03x04x05x06x07" # prepare data _upload_file = UploadFile() _upload_file.file_id = "file_id_1" - _upload_file.issuer_address = "0x1234567890123456789012345678900000000002" # not target + _upload_file.issuer_address = ( + "0x1234567890123456789012345678900000000002" # not target + ) _upload_file.relation = self.token_address _upload_file.file_name = "file_name_1" _upload_file.content = file_content_bin @@ -237,9 +229,6 @@ def test_error_2_2(self, client, db): # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "file not found" - } \ No newline at end of file + "meta": {"code": 1, "title": "NotFound"}, + "detail": "file not found", + } diff --git a/tests/test_app_routers_healthcheck_GET.py b/tests/test_app_routers_healthcheck_GET.py index 5efe66c5..d6562760 100644 --- a/tests/test_app_routers_healthcheck_GET.py +++ b/tests/test_app_routers_healthcheck_GET.py @@ -17,7 +17,6 @@ SPDX-License-Identifier: Apache-2.0 """ from datetime import datetime - from unittest import mock from unittest.mock import MagicMock @@ -59,13 +58,18 @@ def test_normal_1(self, client, db): # # Node not sync # E2EE key invalid - @mock.patch("app.utils.e2ee_utils.E2EEUtils.cache", { - "private_key": None, - "public_key": None, - "encrypted_length": None, - "expiration_datetime": datetime.min - }) - @mock.patch("app.utils.e2ee_utils.E2EE_RSA_RESOURCE", "tests/data/account_config.yml") + @mock.patch( + "app.utils.e2ee_utils.E2EEUtils.cache", + { + "private_key": None, + "public_key": None, + "encrypted_length": None, + "expiration_datetime": datetime.min, + }, + ) + @mock.patch( + "app.utils.e2ee_utils.E2EE_RSA_RESOURCE", "tests/data/account_config.yml" + ) def test_error_1(self, client, db): _node = Node() _node.endpoint_uri = "http://test1" @@ -85,33 +89,29 @@ def test_error_1(self, client, db): # assertion assert resp.status_code == 503 assert resp.json() == { - "meta": { - "code": 1, - "title": "ServiceUnavailableError" - }, + "meta": {"code": 1, "title": "ServiceUnavailableError"}, "detail": [ "Ethereum node's block synchronization is down", - "Setting E2EE key is invalid" - ] + "Setting E2EE key is invalid", + ], } # # DB connect error def test_error_2(self, client, db): # request target api - with mock.patch("sqlalchemy.orm.session.Session.connection", - MagicMock(side_effect=Exception())): + with mock.patch( + "sqlalchemy.orm.session.Session.connection", + MagicMock(side_effect=Exception()), + ): resp = client.get(self.apiurl) print(resp.json()) # assertion assert resp.status_code == 503 assert resp.json() == { - "meta": { - "code": 1, - "title": "ServiceUnavailableError" - }, + "meta": {"code": 1, "title": "ServiceUnavailableError"}, "detail": [ "Can't connect to database", - ] + ], } diff --git a/tests/test_app_routers_ledger_{token_address}_details_data_GET.py b/tests/test_app_routers_ledger_{token_address}_details_data_GET.py index 9662c402..d9287407 100644 --- a/tests/test_app_routers_ledger_{token_address}_details_data_GET.py +++ b/tests/test_app_routers_ledger_{token_address}_details_data_GET.py @@ -18,11 +18,7 @@ """ from datetime import datetime -from app.model.db import ( - Token, - TokenType, - LedgerDetailsData -) +from app.model.db import LedgerDetailsData, Token, TokenType from tests.account_config import config_eth_account @@ -53,50 +49,57 @@ def test_normal_1_1(self, client, db): _details_data_1_1 = LedgerDetailsData() _details_data_1_1.token_address = token_address _details_data_1_1.data_id = "data_id_1" - _details_data_1_1.data_created = datetime.strptime("2022/01/01 15:20:30.000001", - '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/02 + _details_data_1_1.data_created = datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/02 db.add(_details_data_1_1) _details_data_2_1 = LedgerDetailsData() _details_data_2_1.token_address = token_address _details_data_2_1.data_id = "data_id_2" - _details_data_2_1.data_created = datetime.strptime("2022/01/02 00:20:30.000001", - '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/02 + _details_data_2_1.data_created = datetime.strptime( + "2022/01/02 00:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/02 db.add(_details_data_2_1) _details_data_2_2 = LedgerDetailsData() _details_data_2_2.token_address = token_address _details_data_2_2.data_id = "data_id_2" - _details_data_2_2.data_created = datetime.strptime("2022/01/02 00:20:30.000002", - '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/02 + _details_data_2_2.data_created = datetime.strptime( + "2022/01/02 00:20:30.000002", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/02 db.add(_details_data_2_2) _details_data_3_1 = LedgerDetailsData() _details_data_3_1.token_address = token_address _details_data_3_1.data_id = "data_id_3" - _details_data_3_1.data_created = datetime.strptime("2022/01/02 15:20:30.000010", - '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/03 + _details_data_3_1.data_created = datetime.strptime( + "2022/01/02 15:20:30.000010", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/03 db.add(_details_data_3_1) _details_data_3_2 = LedgerDetailsData() _details_data_3_2.token_address = token_address _details_data_3_2.data_id = "data_id_3" - _details_data_3_2.data_created = datetime.strptime("2022/01/02 15:20:30.000009", - '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/03 + _details_data_3_2.data_created = datetime.strptime( + "2022/01/02 15:20:30.000009", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/03 db.add(_details_data_3_2) _details_data_3_3 = LedgerDetailsData() _details_data_3_3.token_address = token_address _details_data_3_3.data_id = "data_id_3" - _details_data_3_3.data_created = datetime.strptime("2022/01/02 15:20:30.000008", - '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/03 + _details_data_3_3.data_created = datetime.strptime( + "2022/01/02 15:20:30.000008", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/03 db.add(_details_data_3_3) _details_data_4_1 = LedgerDetailsData() _details_data_4_1.token_address = token_address _details_data_4_1.data_id = "data_id_4" - _details_data_4_1.data_created = datetime.strptime("2022/01/03 00:20:30.000001", - '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/03 + _details_data_4_1.data_created = datetime.strptime( + "2022/01/03 00:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/03 db.add(_details_data_4_1) # Not Target @@ -109,18 +112,13 @@ def test_normal_1_1(self, client, db): self.base_url.format(token_address=token_address), headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 4, - "offset": None, - "limit": None, - "total": 4 - }, + "result_set": {"count": 4, "offset": None, "limit": None, "total": 4}, "details_data": [ { "data_id": "data_id_1", @@ -142,7 +140,7 @@ def test_normal_1_1(self, client, db): "count": 1, "created": "2022-01-03T09:20:30.000001+09:00", }, - ] + ], } # @@ -164,50 +162,57 @@ def test_normal_1_2(self, client, db): _details_data_1_1 = LedgerDetailsData() _details_data_1_1.token_address = token_address _details_data_1_1.data_id = "data_id_1" - _details_data_1_1.data_created = datetime.strptime("2022/01/01 15:20:30.000001", - '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/02 + _details_data_1_1.data_created = datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/02 db.add(_details_data_1_1) _details_data_2_1 = LedgerDetailsData() _details_data_2_1.token_address = token_address _details_data_2_1.data_id = "data_id_2" - _details_data_2_1.data_created = datetime.strptime("2022/01/02 00:20:30.000001", - '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/02 + _details_data_2_1.data_created = datetime.strptime( + "2022/01/02 00:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/02 db.add(_details_data_2_1) _details_data_2_2 = LedgerDetailsData() _details_data_2_2.token_address = token_address _details_data_2_2.data_id = "data_id_2" - _details_data_2_2.data_created = datetime.strptime("2022/01/02 00:20:30.000002", - '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/02 + _details_data_2_2.data_created = datetime.strptime( + "2022/01/02 00:20:30.000002", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/02 db.add(_details_data_2_2) _details_data_3_1 = LedgerDetailsData() _details_data_3_1.token_address = token_address _details_data_3_1.data_id = "data_id_3" - _details_data_3_1.data_created = datetime.strptime("2022/01/02 15:20:30.000010", - '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/03 + _details_data_3_1.data_created = datetime.strptime( + "2022/01/02 15:20:30.000010", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/03 db.add(_details_data_3_1) _details_data_3_2 = LedgerDetailsData() _details_data_3_2.token_address = token_address _details_data_3_2.data_id = "data_id_3" - _details_data_3_2.data_created = datetime.strptime("2022/01/02 15:20:30.000009", - '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/03 + _details_data_3_2.data_created = datetime.strptime( + "2022/01/02 15:20:30.000009", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/03 db.add(_details_data_3_2) _details_data_3_3 = LedgerDetailsData() _details_data_3_3.token_address = token_address _details_data_3_3.data_id = "data_id_3" - _details_data_3_3.data_created = datetime.strptime("2022/01/02 15:20:30.000008", - '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/03 + _details_data_3_3.data_created = datetime.strptime( + "2022/01/02 15:20:30.000008", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/03 db.add(_details_data_3_3) _details_data_4_1 = LedgerDetailsData() _details_data_4_1.token_address = token_address _details_data_4_1.data_id = "data_id_4" - _details_data_4_1.data_created = datetime.strptime("2022/01/03 00:20:30.000001", - '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/03 + _details_data_4_1.data_created = datetime.strptime( + "2022/01/03 00:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/03 db.add(_details_data_4_1) # Not Target @@ -223,12 +228,7 @@ def test_normal_1_2(self, client, db): # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 4, - "offset": None, - "limit": None, - "total": 4 - }, + "result_set": {"count": 4, "offset": None, "limit": None, "total": 4}, "details_data": [ { "data_id": "data_id_1", @@ -250,7 +250,7 @@ def test_normal_1_2(self, client, db): "count": 1, "created": "2022-01-03T09:20:30.000001+09:00", }, - ] + ], } # @@ -272,50 +272,57 @@ def test_normal_2(self, client, db): _details_data_1_1 = LedgerDetailsData() _details_data_1_1.token_address = token_address _details_data_1_1.data_id = "data_id_1" - _details_data_1_1.data_created = datetime.strptime("2022/01/01 15:20:30.000001", - '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/02 + _details_data_1_1.data_created = datetime.strptime( + "2022/01/01 15:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/02 db.add(_details_data_1_1) _details_data_2_1 = LedgerDetailsData() _details_data_2_1.token_address = token_address _details_data_2_1.data_id = "data_id_2" - _details_data_2_1.data_created = datetime.strptime("2022/01/02 00:20:30.000001", - '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/02 + _details_data_2_1.data_created = datetime.strptime( + "2022/01/02 00:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/02 db.add(_details_data_2_1) _details_data_2_2 = LedgerDetailsData() _details_data_2_2.token_address = token_address _details_data_2_2.data_id = "data_id_2" - _details_data_2_2.data_created = datetime.strptime("2022/01/02 00:20:30.000002", - '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/02 + _details_data_2_2.data_created = datetime.strptime( + "2022/01/02 00:20:30.000002", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/02 db.add(_details_data_2_2) _details_data_3_1 = LedgerDetailsData() _details_data_3_1.token_address = token_address _details_data_3_1.data_id = "data_id_3" - _details_data_3_1.data_created = datetime.strptime("2022/01/02 15:20:30.000010", - '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/03 + _details_data_3_1.data_created = datetime.strptime( + "2022/01/02 15:20:30.000010", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/03 db.add(_details_data_3_1) _details_data_3_2 = LedgerDetailsData() _details_data_3_2.token_address = token_address _details_data_3_2.data_id = "data_id_3" - _details_data_3_2.data_created = datetime.strptime("2022/01/02 15:20:30.000009", - '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/03 + _details_data_3_2.data_created = datetime.strptime( + "2022/01/02 15:20:30.000009", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/03 db.add(_details_data_3_2) _details_data_3_3 = LedgerDetailsData() _details_data_3_3.token_address = token_address _details_data_3_3.data_id = "data_id_3" - _details_data_3_3.data_created = datetime.strptime("2022/01/02 15:20:30.000008", - '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/03 + _details_data_3_3.data_created = datetime.strptime( + "2022/01/02 15:20:30.000008", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/03 db.add(_details_data_3_3) _details_data_4_1 = LedgerDetailsData() _details_data_4_1.token_address = token_address _details_data_4_1.data_id = "data_id_4" - _details_data_4_1.data_created = datetime.strptime("2022/01/03 00:20:30.000001", - '%Y/%m/%d %H:%M:%S.%f') # JST 2022/01/03 + _details_data_4_1.data_created = datetime.strptime( + "2022/01/03 00:20:30.000001", "%Y/%m/%d %H:%M:%S.%f" + ) # JST 2022/01/03 db.add(_details_data_4_1) # Not Target @@ -326,24 +333,16 @@ def test_normal_2(self, client, db): resp = client.get( self.base_url.format(token_address=token_address), - params={ - "offset": 1, - "limit": 2 - }, + params={"offset": 1, "limit": 2}, headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 4, - "offset": 1, - "limit": 2, - "total": 4 - }, + "result_set": {"count": 4, "offset": 1, "limit": 2, "total": 4}, "details_data": [ { "data_id": "data_id_2", @@ -355,7 +354,7 @@ def test_normal_2(self, client, db): "count": 3, "created": "2022-01-03T00:20:30.000010+09:00", }, - ] + ], } ########################################################################### @@ -372,23 +371,20 @@ def test_error_1(self, client, db): self.base_url.format(token_address=token_address), headers={ "issuer-address": "test", - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -403,7 +399,9 @@ def test_error_2_1(self, client, db): _token = Token() _token.type = TokenType.IBET_STRAIGHT_BOND.value _token.tx_hash = "" - _token.issuer_address = "0x1234567890123456789012345678901234567899" # not target + _token.issuer_address = ( + "0x1234567890123456789012345678901234567899" # not target + ) _token.token_address = token_address _token.abi = {} _token.token_status = 2 @@ -418,17 +416,14 @@ def test_error_2_1(self, client, db): }, headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token does not exist" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token does not exist", } # @@ -449,11 +444,8 @@ def test_error_2_2(self, client, db): # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token does not exist" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token does not exist", } # @@ -482,15 +474,12 @@ def test_error_3(self, client, db): }, headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } diff --git a/tests/test_app_routers_ledger_{token_address}_details_data_POST.py b/tests/test_app_routers_ledger_{token_address}_details_data_POST.py index 971f9d48..82387b61 100644 --- a/tests/test_app_routers_ledger_{token_address}_details_data_POST.py +++ b/tests/test_app_routers_ledger_{token_address}_details_data_POST.py @@ -16,11 +16,7 @@ SPDX-License-Identifier: Apache-2.0 """ -from app.model.db import ( - Token, - TokenType, - LedgerDetailsData -) +from app.model.db import LedgerDetailsData, Token, TokenType from tests.account_config import config_eth_account @@ -71,15 +67,15 @@ def test_normal_1(self, client, db): json=req_param, headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 200 assert resp.json()["data_id"] is not None - _details_data_list = db.query(LedgerDetailsData). \ - order_by(LedgerDetailsData.id). \ - all() + _details_data_list = ( + db.query(LedgerDetailsData).order_by(LedgerDetailsData.id).all() + ) assert len(_details_data_list) == 2 _details_data = _details_data_list[0] assert _details_data.id == 1 @@ -117,22 +113,19 @@ def test_error_1(self, client, db): # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, { "loc": ["body"], "msg": "field required", - "type": "value_error.missing" - } - ] + "type": "value_error.missing", + }, + ], } # @@ -164,23 +157,20 @@ def test_error_2(self, client, db): json=req_param, headers={ "issuer-address": "test", - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -194,8 +184,8 @@ def test_error_3(self, client, db): req_param = [ { "name": "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" - "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" - "1", + "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" + "1", "address": "address_test_1", "amount": 1_000_000_000_001, "price": -1, @@ -205,8 +195,8 @@ def test_error_3(self, client, db): { "name": "name_test_2", "address": "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" - "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" - "1", + "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" + "1", "amount": -1, "price": 5_000_000_001, "balance": -1, @@ -218,77 +208,74 @@ def test_error_3(self, client, db): json=req_param, headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "ctx": {"limit_value": 200}, "loc": ["body", 0, "name"], "msg": "ensure this value has at most 200 characters", - "type": "value_error.any_str.max_length" + "type": "value_error.any_str.max_length", }, { "ctx": {"limit_value": 1_000_000_000_000}, "loc": ["body", 0, "amount"], "msg": "ensure this value is less than or equal to 1000000000000", - "type": "value_error.number.not_le" + "type": "value_error.number.not_le", }, { "ctx": {"limit_value": 0}, "loc": ["body", 0, "price"], "msg": "ensure this value is greater than or equal to 0", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, { "ctx": {"limit_value": 5_000_000_000_000_000_000_000}, "loc": ["body", 0, "balance"], "msg": "ensure this value is less than or equal to 5000000000000000000000", - "type": "value_error.number.not_le" + "type": "value_error.number.not_le", }, { "ctx": {"limit_value": 10}, "loc": ["body", 0, "acquisition_date"], "msg": "ensure this value has at most 10 characters", - "type": "value_error.any_str.max_length" + "type": "value_error.any_str.max_length", }, { "ctx": {"limit_value": 200}, "loc": ["body", 1, "address"], "msg": "ensure this value has at most 200 characters", - "type": "value_error.any_str.max_length" + "type": "value_error.any_str.max_length", }, { "ctx": {"limit_value": 0}, "loc": ["body", 1, "amount"], "msg": "ensure this value is greater than or equal to 0", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, { "ctx": {"limit_value": 5000000000}, "loc": ["body", 1, "price"], "msg": "ensure this value is less than or equal to 5000000000", - "type": "value_error.number.not_le" + "type": "value_error.number.not_le", }, { "ctx": {"limit_value": 0}, "loc": ["body", 1, "balance"], "msg": "ensure this value is greater than or equal to 0", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, { "loc": ["body", 1, "acquisition_date"], "msg": "The date format must be YYYY/MM/DD", - "type": "value_error" - } - ] + "type": "value_error", + }, + ], } # @@ -322,17 +309,14 @@ def test_error_4(self, client, db): json=req_param, headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token does not exist" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token does not exist", } # @@ -376,15 +360,12 @@ def test_error_5(self, client, db): json=req_param, headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } diff --git a/tests/test_app_routers_ledger_{token_address}_details_data_{data_id}_DELETE.py b/tests/test_app_routers_ledger_{token_address}_details_data_{data_id}_DELETE.py index a674a613..7b2c3af3 100644 --- a/tests/test_app_routers_ledger_{token_address}_details_data_{data_id}_DELETE.py +++ b/tests/test_app_routers_ledger_{token_address}_details_data_{data_id}_DELETE.py @@ -16,11 +16,7 @@ SPDX-License-Identifier: Apache-2.0 """ -from app.model.db import ( - Token, - TokenType, - LedgerDetailsData -) +from app.model.db import LedgerDetailsData, Token, TokenType from tests.account_config import config_eth_account @@ -87,7 +83,7 @@ def test_normal_1(self, client, db): self.base_url.format(token_address=token_address, data_id=data_id), headers={ "issuer-address": issuer_address, - } + }, ) # assertion @@ -116,17 +112,14 @@ def test_error_1(self, client, db): # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", } - ] + ], } # @@ -140,23 +133,20 @@ def test_error_2(self, client, db): self.base_url.format(token_address=token_address, data_id=data_id), headers={ "issuer-address": "test", - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -172,17 +162,14 @@ def test_error_3(self, client, db): self.base_url.format(token_address=token_address, data_id=data_id), headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token does not exist" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token does not exist", } # @@ -208,15 +195,12 @@ def test_error_4(self, client, db): self.base_url.format(token_address=token_address, data_id=data_id), headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } diff --git a/tests/test_app_routers_ledger_{token_address}_details_data_{data_id}_GET.py b/tests/test_app_routers_ledger_{token_address}_details_data_{data_id}_GET.py index c244658f..6949cde2 100644 --- a/tests/test_app_routers_ledger_{token_address}_details_data_{data_id}_GET.py +++ b/tests/test_app_routers_ledger_{token_address}_details_data_{data_id}_GET.py @@ -16,11 +16,7 @@ SPDX-License-Identifier: Apache-2.0 """ -from app.model.db import ( - Token, - TokenType, - LedgerDetailsData -) +from app.model.db import LedgerDetailsData, Token, TokenType from tests.account_config import config_eth_account @@ -88,7 +84,7 @@ def test_normal_1_1(self, client, db): self.base_url.format(token_address=token_address, data_id=data_id), headers={ "issuer-address": issuer_address, - } + }, ) # assertion @@ -245,7 +241,7 @@ def test_normal_2(self, client, db): self.base_url.format(token_address=token_address, data_id=data_id), headers={ "issuer-address": issuer_address, - } + }, ) # assertion @@ -284,23 +280,20 @@ def test_error_1(self, client, db): self.base_url.format(token_address=token_address, data_id=data_id), headers={ "issuer-address": "test", - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -316,7 +309,9 @@ def test_error_2_1(self, client, db): _token = Token() _token.type = TokenType.IBET_STRAIGHT_BOND.value _token.tx_hash = "" - _token.issuer_address = "0x1234567890123456789012345678901234567899" # not target + _token.issuer_address = ( + "0x1234567890123456789012345678901234567899" # not target + ) _token.token_address = token_address _token.abi = {} _token.token_status = 2 @@ -327,17 +322,14 @@ def test_error_2_1(self, client, db): self.base_url.format(token_address=token_address, data_id=data_id), headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token does not exist" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token does not exist", } # @@ -355,11 +347,8 @@ def test_error_2_2(self, client, db): # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token does not exist" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token does not exist", } # @@ -385,15 +374,12 @@ def test_error_3(self, client, db): self.base_url.format(token_address=token_address, data_id=data_id), headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } diff --git a/tests/test_app_routers_ledger_{token_address}_details_data_{data_id}_POST.py b/tests/test_app_routers_ledger_{token_address}_details_data_{data_id}_POST.py index 1e0b78c8..cfbbfe10 100644 --- a/tests/test_app_routers_ledger_{token_address}_details_data_{data_id}_POST.py +++ b/tests/test_app_routers_ledger_{token_address}_details_data_{data_id}_POST.py @@ -18,11 +18,7 @@ """ from unittest import mock -from app.model.db import ( - Token, - TokenType, - LedgerDetailsData -) +from app.model.db import LedgerDetailsData, Token, TokenType from tests.account_config import config_eth_account @@ -86,15 +82,15 @@ def test_normal_1(self, mock_func, client, db): json=req_param, headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 200 assert resp.json() is None - _details_data_list = db.query(LedgerDetailsData). \ - order_by(LedgerDetailsData.id). \ - all() + _details_data_list = ( + db.query(LedgerDetailsData).order_by(LedgerDetailsData.id).all() + ) assert len(_details_data_list) == 2 _details_data = _details_data_list[0] assert _details_data.id == 2 @@ -135,22 +131,19 @@ def test_error_1(self, client, db): # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, { "loc": ["body"], "msg": "field required", - "type": "value_error.missing" - } - ] + "type": "value_error.missing", + }, + ], } # @@ -183,23 +176,20 @@ def test_error_2(self, client, db): json=req_param, headers={ "issuer-address": "test", - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -214,8 +204,8 @@ def test_error_3(self, client, db): req_param = [ { "name": "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" - "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" - "1", + "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" + "1", "address": "address_test_1", "amount": 1_000_000_000_001, "price": -1, @@ -225,8 +215,8 @@ def test_error_3(self, client, db): { "name": "name_test_2", "address": "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" - "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" - "1", + "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" + "1", "amount": -1, "price": 5_000_000_001, "balance": -1, @@ -238,77 +228,74 @@ def test_error_3(self, client, db): json=req_param, headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "ctx": {"limit_value": 200}, "loc": ["body", 0, "name"], "msg": "ensure this value has at most 200 characters", - "type": "value_error.any_str.max_length" + "type": "value_error.any_str.max_length", }, { "ctx": {"limit_value": 1_000_000_000_000}, "loc": ["body", 0, "amount"], "msg": "ensure this value is less than or equal to 1000000000000", - "type": "value_error.number.not_le" + "type": "value_error.number.not_le", }, { "ctx": {"limit_value": 0}, "loc": ["body", 0, "price"], "msg": "ensure this value is greater than or equal to 0", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, { "ctx": {"limit_value": 5_000_000_000_000_000_000_000}, "loc": ["body", 0, "balance"], "msg": "ensure this value is less than or equal to 5000000000000000000000", - "type": "value_error.number.not_le" + "type": "value_error.number.not_le", }, { "ctx": {"limit_value": 10}, "loc": ["body", 0, "acquisition_date"], "msg": "ensure this value has at most 10 characters", - "type": "value_error.any_str.max_length" + "type": "value_error.any_str.max_length", }, { "ctx": {"limit_value": 200}, "loc": ["body", 1, "address"], "msg": "ensure this value has at most 200 characters", - "type": "value_error.any_str.max_length" + "type": "value_error.any_str.max_length", }, { "ctx": {"limit_value": 0}, "loc": ["body", 1, "amount"], "msg": "ensure this value is greater than or equal to 0", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, { "ctx": {"limit_value": 5000000000}, "loc": ["body", 1, "price"], "msg": "ensure this value is less than or equal to 5000000000", - "type": "value_error.number.not_le" + "type": "value_error.number.not_le", }, { "ctx": {"limit_value": 0}, "loc": ["body", 1, "balance"], "msg": "ensure this value is greater than or equal to 0", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, { "loc": ["body", 1, "acquisition_date"], "msg": "The date format must be YYYY/MM/DD", - "type": "value_error" - } - ] + "type": "value_error", + }, + ], } # @@ -343,17 +330,14 @@ def test_error_4(self, client, db): json=req_param, headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token does not exist" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token does not exist", } # @@ -398,15 +382,12 @@ def test_error_5(self, client, db): json=req_param, headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } diff --git a/tests/test_app_routers_ledger_{token_address}_history_GET.py b/tests/test_app_routers_ledger_{token_address}_history_GET.py index 5d0e0b73..201d6cf9 100644 --- a/tests/test_app_routers_ledger_{token_address}_history_GET.py +++ b/tests/test_app_routers_ledger_{token_address}_history_GET.py @@ -18,11 +18,7 @@ """ from datetime import datetime -from app.model.db import ( - Token, - TokenType, - Ledger -) +from app.model.db import Ledger, Token, TokenType from tests.account_config import config_eth_account @@ -54,14 +50,18 @@ def test_normal_1_1(self, client, db): _ledger_1.token_address = token_address _ledger_1.token_type = TokenType.IBET_STRAIGHT_BOND.value _ledger_1.ledger = {} - _ledger_1.ledger_created = datetime.strptime("2022/01/01 15:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/02 + _ledger_1.ledger_created = datetime.strptime( + "2022/01/01 15:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/02 db.add(_ledger_1) _ledger_2 = Ledger() _ledger_2.token_address = token_address _ledger_2.token_type = TokenType.IBET_STRAIGHT_BOND.value _ledger_2.ledger = {} - _ledger_2.ledger_created = datetime.strptime("2022/01/02 00:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/02 + _ledger_2.ledger_created = datetime.strptime( + "2022/01/02 00:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/02 db.add(_ledger_2) # request target API @@ -69,18 +69,13 @@ def test_normal_1_1(self, client, db): self.base_url.format(token_address=token_address), headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 2, - "offset": None, - "limit": None, - "total": 2 - }, + "result_set": {"count": 2, "offset": None, "limit": None, "total": 2}, "ledgers": [ { "id": 2, @@ -93,8 +88,8 @@ def test_normal_1_1(self, client, db): "token_address": token_address, "token_type": TokenType.IBET_STRAIGHT_BOND.value, "created": "2022-01-02T00:20:30+09:00", - } - ] + }, + ], } # @@ -117,14 +112,18 @@ def test_normal_1_2(self, client, db): _ledger_1.token_address = token_address _ledger_1.token_type = TokenType.IBET_STRAIGHT_BOND.value _ledger_1.ledger = {} - _ledger_1.ledger_created = datetime.strptime("2022/01/01 15:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/02 + _ledger_1.ledger_created = datetime.strptime( + "2022/01/01 15:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/02 db.add(_ledger_1) _ledger_2 = Ledger() _ledger_2.token_address = token_address _ledger_2.token_type = TokenType.IBET_STRAIGHT_BOND.value _ledger_2.ledger = {} - _ledger_2.ledger_created = datetime.strptime("2022/01/02 00:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/02 + _ledger_2.ledger_created = datetime.strptime( + "2022/01/02 00:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/02 db.add(_ledger_2) # request target API @@ -135,12 +134,7 @@ def test_normal_1_2(self, client, db): # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 2, - "offset": None, - "limit": None, - "total": 2 - }, + "result_set": {"count": 2, "offset": None, "limit": None, "total": 2}, "ledgers": [ { "id": 2, @@ -153,8 +147,8 @@ def test_normal_1_2(self, client, db): "token_address": token_address, "token_type": TokenType.IBET_STRAIGHT_BOND.value, "created": "2022-01-02T00:20:30+09:00", - } - ] + }, + ], } # @@ -177,51 +171,51 @@ def test_normal_2(self, client, db): _ledger_1.token_address = token_address _ledger_1.token_type = TokenType.IBET_STRAIGHT_BOND.value _ledger_1.ledger = {} - _ledger_1.ledger_created = datetime.strptime("2022/01/01 15:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/02 + _ledger_1.ledger_created = datetime.strptime( + "2022/01/01 15:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/02 db.add(_ledger_1) _ledger_2 = Ledger() _ledger_2.token_address = token_address _ledger_2.token_type = TokenType.IBET_STRAIGHT_BOND.value _ledger_2.ledger = {} - _ledger_2.ledger_created = datetime.strptime("2022/01/02 00:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/02 + _ledger_2.ledger_created = datetime.strptime( + "2022/01/02 00:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/02 db.add(_ledger_2) _ledger_3 = Ledger() _ledger_3.token_address = token_address _ledger_3.token_type = TokenType.IBET_STRAIGHT_BOND.value _ledger_3.ledger = {} - _ledger_3.ledger_created = datetime.strptime("2022/01/02 15:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/03 + _ledger_3.ledger_created = datetime.strptime( + "2022/01/02 15:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/03 db.add(_ledger_3) _ledger_4 = Ledger() _ledger_4.token_address = token_address _ledger_4.token_type = TokenType.IBET_STRAIGHT_BOND.value _ledger_4.ledger = {} - _ledger_4.ledger_created = datetime.strptime("2022/01/03 00:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/03 + _ledger_4.ledger_created = datetime.strptime( + "2022/01/03 00:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/03 db.add(_ledger_4) # request target API resp = client.get( self.base_url.format(token_address=token_address), - params={ - "offset": 1, - "limit": 2 - }, + params={"offset": 1, "limit": 2}, headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 4, - "offset": 1, - "limit": 2, - "total": 4 - }, + "result_set": {"count": 4, "offset": 1, "limit": 2, "total": 4}, "ledgers": [ { "id": 3, @@ -234,8 +228,8 @@ def test_normal_2(self, client, db): "token_address": token_address, "token_type": TokenType.IBET_STRAIGHT_BOND.value, "created": "2022-01-02T09:20:30+09:00", - } - ] + }, + ], } ########################################################################### @@ -252,23 +246,20 @@ def test_error_1(self, client, db): self.base_url.format(token_address=token_address), headers={ "issuer-address": "test", - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -283,7 +274,9 @@ def test_error_2_1(self, client, db): _token = Token() _token.type = TokenType.IBET_STRAIGHT_BOND.value _token.tx_hash = "" - _token.issuer_address = "0x1234567890123456789012345678901234567899" # not target + _token.issuer_address = ( + "0x1234567890123456789012345678901234567899" # not target + ) _token.token_address = token_address _token.abi = {} _token.token_status = 2 @@ -298,17 +291,14 @@ def test_error_2_1(self, client, db): }, headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token does not exist" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token does not exist", } # @@ -329,11 +319,8 @@ def test_error_2_2(self, client, db): # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token does not exist" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token does not exist", } # @@ -362,15 +349,12 @@ def test_error_3(self, client, db): }, headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } diff --git a/tests/test_app_routers_ledger_{token_address}_history_{ledger_id}_GET.py b/tests/test_app_routers_ledger_{token_address}_history_{ledger_id}_GET.py index db529dd1..ed92f17b 100644 --- a/tests/test_app_routers_ledger_{token_address}_history_{ledger_id}_GET.py +++ b/tests/test_app_routers_ledger_{token_address}_history_{ledger_id}_GET.py @@ -20,15 +20,15 @@ from unittest import mock from unittest.mock import call +from app.model.blockchain import IbetStraightBondContract from app.model.db import ( - Token, - TokenType, IDXPersonalInfo, Ledger, + LedgerDetailsDataType, LedgerDetailsTemplate, - LedgerDetailsDataType + Token, + TokenType, ) -from app.model.blockchain import IbetStraightBondContract from tests.account_config import config_eth_account @@ -72,7 +72,7 @@ def test_normal_1_1(self, client, db): { "hoge": "aaaa", "fuga": "bbbb", - } + }, ], "details": [ { @@ -82,10 +82,7 @@ def test_normal_1_1(self, client, db): "key": "aaa", "value": "aaa", }, - { - "test1": "a", - "test2": "b" - } + {"test1": "a", "test2": "b"}, ], "data": [ { @@ -95,7 +92,7 @@ def test_normal_1_1(self, client, db): "amount": 10, "price": 20, "balance": 30, - "acquisition_date": "2022/12/02" + "acquisition_date": "2022/12/02", }, { "account_address": account_address_2, @@ -104,18 +101,15 @@ def test_normal_1_1(self, client, db): "amount": 100, "price": 200, "balance": 300, - "acquisition_date": "2022/12/03" - } + "acquisition_date": "2022/12/03", + }, ], "footers": [ { "key": "aaa", "value": "aaa", }, - { - "f-test1": "a", - "f-test2": "b" - } + {"f-test1": "a", "f-test2": "b"}, ], }, { @@ -125,10 +119,7 @@ def test_normal_1_1(self, client, db): "key": "aaa", "value": "aaa", }, - { - "test1-1": "a", - "test2-1": "b" - } + {"test1-1": "a", "test2-1": "b"}, ], "data": [ { @@ -148,17 +139,14 @@ def test_normal_1_1(self, client, db): "price": 30, "balance": 600, "acquisition_date": "2020/01/02", - } + }, ], "footers": [ { "key": "aaa", "value": "aaa", }, - { - "f-test1-1": "a", - "f-test2-1": "b" - } + {"f-test1-1": "a", "f-test2-1": "b"}, ], }, ], @@ -170,10 +158,12 @@ def test_normal_1_1(self, client, db): { "f-hoge": "aaaa", "f-fuga": "bbbb", - } + }, ], } - _ledger_1.ledger_created = datetime.strptime("2022/01/01 15:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/02 + _ledger_1.ledger_created = datetime.strptime( + "2022/01/01 15:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/02 db.add(_ledger_1) # request target AsPI @@ -184,7 +174,7 @@ def test_normal_1_1(self, client, db): }, headers={ "issuer-address": issuer_address, - } + }, ) # assertion @@ -200,7 +190,7 @@ def test_normal_1_1(self, client, db): { "hoge": "aaaa", "fuga": "bbbb", - } + }, ], "details": [ { @@ -210,10 +200,7 @@ def test_normal_1_1(self, client, db): "key": "aaa", "value": "aaa", }, - { - "test1": "a", - "test2": "b" - } + {"test1": "a", "test2": "b"}, ], "data": [ { @@ -223,7 +210,7 @@ def test_normal_1_1(self, client, db): "amount": 10, "price": 20, "balance": 30, - "acquisition_date": "2022/12/02" + "acquisition_date": "2022/12/02", }, { "account_address": account_address_2, @@ -232,18 +219,15 @@ def test_normal_1_1(self, client, db): "amount": 100, "price": 200, "balance": 300, - "acquisition_date": "2022/12/03" - } + "acquisition_date": "2022/12/03", + }, ], "footers": [ { "key": "aaa", "value": "aaa", }, - { - "f-test1": "a", - "f-test2": "b" - } + {"f-test1": "a", "f-test2": "b"}, ], }, { @@ -253,10 +237,7 @@ def test_normal_1_1(self, client, db): "key": "aaa", "value": "aaa", }, - { - "test1-1": "a", - "test2-1": "b" - } + {"test1-1": "a", "test2-1": "b"}, ], "data": [ { @@ -276,17 +257,14 @@ def test_normal_1_1(self, client, db): "price": 30, "balance": 600, "acquisition_date": "2020/01/02", - } + }, ], "footers": [ { "key": "aaa", "value": "aaa", }, - { - "f-test1-1": "a", - "f-test2-1": "b" - } + {"f-test1-1": "a", "f-test2-1": "b"}, ], }, ], @@ -298,7 +276,7 @@ def test_normal_1_1(self, client, db): { "f-hoge": "aaaa", "f-fuga": "bbbb", - } + }, ], } @@ -334,7 +312,7 @@ def test_normal_1_2(self, client, db): { "hoge": "aaaa", "fuga": "bbbb", - } + }, ], "details": [ { @@ -344,10 +322,7 @@ def test_normal_1_2(self, client, db): "key": "aaa", "value": "aaa", }, - { - "test1": "a", - "test2": "b" - } + {"test1": "a", "test2": "b"}, ], "data": [ { @@ -357,7 +332,7 @@ def test_normal_1_2(self, client, db): "amount": 10, "price": 20, "balance": 30, - "acquisition_date": "2022/12/02" + "acquisition_date": "2022/12/02", }, { "account_address": account_address_2, @@ -366,18 +341,15 @@ def test_normal_1_2(self, client, db): "amount": 100, "price": 200, "balance": 300, - "acquisition_date": "2022/12/03" - } + "acquisition_date": "2022/12/03", + }, ], "footers": [ { "key": "aaa", "value": "aaa", }, - { - "f-test1": "a", - "f-test2": "b" - } + {"f-test1": "a", "f-test2": "b"}, ], }, { @@ -387,10 +359,7 @@ def test_normal_1_2(self, client, db): "key": "aaa", "value": "aaa", }, - { - "test1-1": "a", - "test2-1": "b" - } + {"test1-1": "a", "test2-1": "b"}, ], "data": [ { @@ -410,17 +379,14 @@ def test_normal_1_2(self, client, db): "price": 30, "balance": 600, "acquisition_date": "2020/01/02", - } + }, ], "footers": [ { "key": "aaa", "value": "aaa", }, - { - "f-test1-1": "a", - "f-test2-1": "b" - } + {"f-test1-1": "a", "f-test2-1": "b"}, ], }, ], @@ -432,10 +398,12 @@ def test_normal_1_2(self, client, db): { "f-hoge": "aaaa", "f-fuga": "bbbb", - } + }, ], } - _ledger_1.ledger_created = datetime.strptime("2022/01/01 15:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/02 + _ledger_1.ledger_created = datetime.strptime( + "2022/01/01 15:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/02 db.add(_ledger_1) # request target AsPI @@ -459,7 +427,7 @@ def test_normal_1_2(self, client, db): { "hoge": "aaaa", "fuga": "bbbb", - } + }, ], "details": [ { @@ -469,10 +437,7 @@ def test_normal_1_2(self, client, db): "key": "aaa", "value": "aaa", }, - { - "test1": "a", - "test2": "b" - } + {"test1": "a", "test2": "b"}, ], "data": [ { @@ -482,7 +447,7 @@ def test_normal_1_2(self, client, db): "amount": 10, "price": 20, "balance": 30, - "acquisition_date": "2022/12/02" + "acquisition_date": "2022/12/02", }, { "account_address": account_address_2, @@ -491,18 +456,15 @@ def test_normal_1_2(self, client, db): "amount": 100, "price": 200, "balance": 300, - "acquisition_date": "2022/12/03" - } + "acquisition_date": "2022/12/03", + }, ], "footers": [ { "key": "aaa", "value": "aaa", }, - { - "f-test1": "a", - "f-test2": "b" - } + {"f-test1": "a", "f-test2": "b"}, ], }, { @@ -512,10 +474,7 @@ def test_normal_1_2(self, client, db): "key": "aaa", "value": "aaa", }, - { - "test1-1": "a", - "test2-1": "b" - } + {"test1-1": "a", "test2-1": "b"}, ], "data": [ { @@ -535,17 +494,14 @@ def test_normal_1_2(self, client, db): "price": 30, "balance": 600, "acquisition_date": "2020/01/02", - } + }, ], "footers": [ { "key": "aaa", "value": "aaa", }, - { - "f-test1-1": "a", - "f-test2-1": "b" - } + {"f-test1-1": "a", "f-test2-1": "b"}, ], }, ], @@ -557,7 +513,7 @@ def test_normal_1_2(self, client, db): { "f-hoge": "aaaa", "f-fuga": "bbbb", - } + }, ], } @@ -596,7 +552,7 @@ def test_normal_2_1(self, client, db): { "hoge": "aaaa", "fuga": "bbbb", - } + }, ], "details": [ { @@ -606,10 +562,7 @@ def test_normal_2_1(self, client, db): "key": "aaa", "value": "aaa", }, - { - "test1": "a", - "test2": "b" - } + {"test1": "a", "test2": "b"}, ], "data": [ { @@ -619,7 +572,7 @@ def test_normal_2_1(self, client, db): "amount": 10, "price": 20, "balance": 30, - "acquisition_date": "2022/12/02" + "acquisition_date": "2022/12/02", }, { "account_address": account_address_2, @@ -628,18 +581,15 @@ def test_normal_2_1(self, client, db): "amount": 100, "price": 200, "balance": 300, - "acquisition_date": "2022/12/03" - } + "acquisition_date": "2022/12/03", + }, ], "footers": [ { "key": "aaa", "value": "aaa", }, - { - "f-test1": "a", - "f-test2": "b" - } + {"f-test1": "a", "f-test2": "b"}, ], }, { @@ -649,10 +599,7 @@ def test_normal_2_1(self, client, db): "key": "aaa", "value": "aaa", }, - { - "test1-1": "a", - "test2-1": "b" - } + {"test1-1": "a", "test2-1": "b"}, ], "data": [ { @@ -672,17 +619,14 @@ def test_normal_2_1(self, client, db): "price": 30, "balance": 600, "acquisition_date": "2020/01/02", - } + }, ], "footers": [ { "key": "aaa", "value": "aaa", }, - { - "f-test1-1": "a", - "f-test2-1": "b" - } + {"f-test1-1": "a", "f-test2-1": "b"}, ], }, ], @@ -694,18 +638,22 @@ def test_normal_2_1(self, client, db): { "f-hoge": "aaaa", "f-fuga": "bbbb", - } + }, ], } - _ledger_1.ledger_created = datetime.strptime("2022/01/01 15:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/02 + _ledger_1.ledger_created = datetime.strptime( + "2022/01/01 15:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/02 db.add(_ledger_1) - _idx_personal_info_1 = IDXPersonalInfo() # Note: account_address_1 has personal information in DB + _idx_personal_info_1 = ( + IDXPersonalInfo() + ) # Note: account_address_1 has personal information in DB _idx_personal_info_1.account_address = account_address_1 _idx_personal_info_1.issuer_address = issuer_address _idx_personal_info_1.personal_info = { "name": "name_db_1", - "address": "address_db_1" + "address": "address_db_1", } db.add(_idx_personal_info_1) @@ -717,20 +665,14 @@ def test_normal_2_1(self, client, db): "key": "aaa", "value": "aaa", }, - { - "test1": "a", - "test2": "b" - } + {"test1": "a", "test2": "b"}, ] _details_1.footers = [ { "key": "aaa", "value": "aaa", }, - { - "f-test1": "a", - "f-test2": "b" - } + {"f-test1": "a", "f-test2": "b"}, ] _details_1.data_type = LedgerDetailsDataType.IBET_FIN.value _details_1.data_source = token_address @@ -740,18 +682,24 @@ def test_normal_2_1(self, client, db): token = IbetStraightBondContract() token.personal_info_contract_address = personal_info_contract_address token.issuer_address = issuer_address - token_get_mock = mock.patch("app.model.blockchain.IbetStraightBondContract.get", return_value=token) - personal_get_info_mock = mock.patch("app.model.blockchain.PersonalInfoContract.get_info") + token_get_mock = mock.patch( + "app.model.blockchain.IbetStraightBondContract.get", return_value=token + ) + personal_get_info_mock = mock.patch( + "app.model.blockchain.PersonalInfoContract.get_info" + ) # request target API with token_get_mock as token_get_mock_patch, personal_get_info_mock as personal_get_info_mock_patch: # Note: # account_address_2 has no personal information in the DB # and gets information from the contract - personal_get_info_mock_patch.side_effect = [{ - "name": "name_contract_2", - "address": "address_contract_2", - }] + personal_get_info_mock_patch.side_effect = [ + { + "name": "name_contract_2", + "address": "address_contract_2", + } + ] resp = client.get( self.base_url.format(token_address=token_address, ledger_id=1), @@ -760,12 +708,12 @@ def test_normal_2_1(self, client, db): }, headers={ "issuer-address": issuer_address, - } + }, ) # assertion - personal_get_info_mock_patch.assert_has_calls([ - call(account_address=account_address_2, default_value=None) - ]) + personal_get_info_mock_patch.assert_has_calls( + [call(account_address=account_address_2, default_value=None)] + ) # assertion assert resp.status_code == 200 @@ -780,7 +728,7 @@ def test_normal_2_1(self, client, db): { "hoge": "aaaa", "fuga": "bbbb", - } + }, ], "details": [ { @@ -790,10 +738,7 @@ def test_normal_2_1(self, client, db): "key": "aaa", "value": "aaa", }, - { - "test1": "a", - "test2": "b" - } + {"test1": "a", "test2": "b"}, ], "data": [ { @@ -803,7 +748,7 @@ def test_normal_2_1(self, client, db): "amount": 10, "price": 20, "balance": 30, - "acquisition_date": "2022/12/02" + "acquisition_date": "2022/12/02", }, { "account_address": account_address_2, @@ -812,18 +757,15 @@ def test_normal_2_1(self, client, db): "amount": 100, "price": 200, "balance": 300, - "acquisition_date": "2022/12/03" - } + "acquisition_date": "2022/12/03", + }, ], "footers": [ { "key": "aaa", "value": "aaa", }, - { - "f-test1": "a", - "f-test2": "b" - } + {"f-test1": "a", "f-test2": "b"}, ], }, { @@ -833,10 +775,7 @@ def test_normal_2_1(self, client, db): "key": "aaa", "value": "aaa", }, - { - "test1-1": "a", - "test2-1": "b" - } + {"test1-1": "a", "test2-1": "b"}, ], "data": [ { @@ -856,17 +795,14 @@ def test_normal_2_1(self, client, db): "price": 30, "balance": 600, "acquisition_date": "2020/01/02", - } + }, ], "footers": [ { "key": "aaa", "value": "aaa", }, - { - "f-test1-1": "a", - "f-test2-1": "b" - } + {"f-test1-1": "a", "f-test2-1": "b"}, ], }, ], @@ -878,7 +814,7 @@ def test_normal_2_1(self, client, db): { "f-hoge": "aaaa", "f-fuga": "bbbb", - } + }, ], } @@ -917,7 +853,7 @@ def test_normal_2_2(self, client, db): { "hoge": "aaaa", "fuga": "bbbb", - } + }, ], "details": [ { @@ -927,10 +863,7 @@ def test_normal_2_2(self, client, db): "key": "aaa", "value": "aaa", }, - { - "test1": "a", - "test2": "b" - } + {"test1": "a", "test2": "b"}, ], "data": [ { @@ -940,7 +873,7 @@ def test_normal_2_2(self, client, db): "amount": 10, "price": 20, "balance": 30, - "acquisition_date": "2022/12/02" + "acquisition_date": "2022/12/02", }, { "account_address": account_address_2, @@ -949,18 +882,15 @@ def test_normal_2_2(self, client, db): "amount": 100, "price": 200, "balance": 300, - "acquisition_date": "2022/12/03" - } + "acquisition_date": "2022/12/03", + }, ], "footers": [ { "key": "aaa", "value": "aaa", }, - { - "f-test1": "a", - "f-test2": "b" - } + {"f-test1": "a", "f-test2": "b"}, ], }, { @@ -970,10 +900,7 @@ def test_normal_2_2(self, client, db): "key": "aaa", "value": "aaa", }, - { - "test1-1": "a", - "test2-1": "b" - } + {"test1-1": "a", "test2-1": "b"}, ], "data": [ { @@ -993,17 +920,14 @@ def test_normal_2_2(self, client, db): "price": 30, "balance": 600, "acquisition_date": "2020/01/02", - } + }, ], "footers": [ { "key": "aaa", "value": "aaa", }, - { - "f-test1-1": "a", - "f-test2-1": "b" - } + {"f-test1-1": "a", "f-test2-1": "b"}, ], }, ], @@ -1015,19 +939,20 @@ def test_normal_2_2(self, client, db): { "f-hoge": "aaaa", "f-fuga": "bbbb", - } + }, ], } - _ledger_1.ledger_created = datetime.strptime("2022/01/01 15:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/02 + _ledger_1.ledger_created = datetime.strptime( + "2022/01/01 15:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/02 db.add(_ledger_1) - _idx_personal_info_1 = IDXPersonalInfo() # Note: account_address_1 has partial personal information in DB + _idx_personal_info_1 = ( + IDXPersonalInfo() + ) # Note: account_address_1 has partial personal information in DB _idx_personal_info_1.account_address = account_address_1 _idx_personal_info_1.issuer_address = issuer_address - _idx_personal_info_1.personal_info = { - "name": None, - "address": None - } + _idx_personal_info_1.personal_info = {"name": None, "address": None} db.add(_idx_personal_info_1) _details_1 = LedgerDetailsTemplate() @@ -1038,20 +963,14 @@ def test_normal_2_2(self, client, db): "key": "aaa", "value": "aaa", }, - { - "test1": "a", - "test2": "b" - } + {"test1": "a", "test2": "b"}, ] _details_1.footers = [ { "key": "aaa", "value": "aaa", }, - { - "f-test1": "a", - "f-test2": "b" - } + {"f-test1": "a", "f-test2": "b"}, ] _details_1.data_type = LedgerDetailsDataType.IBET_FIN.value _details_1.data_source = token_address @@ -1061,18 +980,24 @@ def test_normal_2_2(self, client, db): token = IbetStraightBondContract() token.personal_info_contract_address = personal_info_contract_address token.issuer_address = issuer_address - token_get_mock = mock.patch("app.model.blockchain.IbetStraightBondContract.get", return_value=token) - personal_get_info_mock = mock.patch("app.model.blockchain.PersonalInfoContract.get_info") + token_get_mock = mock.patch( + "app.model.blockchain.IbetStraightBondContract.get", return_value=token + ) + personal_get_info_mock = mock.patch( + "app.model.blockchain.PersonalInfoContract.get_info" + ) # request target API with token_get_mock as token_get_mock_patch, personal_get_info_mock as personal_get_info_mock_patch: # Note: # account_address_2 has no personal information in the DB # and gets information from the contract - personal_get_info_mock_patch.side_effect = [{ - "name": "name_contract_2", - "address": "address_contract_2", - }] + personal_get_info_mock_patch.side_effect = [ + { + "name": "name_contract_2", + "address": "address_contract_2", + } + ] resp = client.get( self.base_url.format(token_address=token_address, ledger_id=1), @@ -1081,12 +1006,12 @@ def test_normal_2_2(self, client, db): }, headers={ "issuer-address": issuer_address, - } + }, ) # assertion - personal_get_info_mock_patch.assert_has_calls([ - call(account_address=account_address_2, default_value=None) - ]) + personal_get_info_mock_patch.assert_has_calls( + [call(account_address=account_address_2, default_value=None)] + ) # assertion assert resp.status_code == 200 @@ -1101,7 +1026,7 @@ def test_normal_2_2(self, client, db): { "hoge": "aaaa", "fuga": "bbbb", - } + }, ], "details": [ { @@ -1111,10 +1036,7 @@ def test_normal_2_2(self, client, db): "key": "aaa", "value": "aaa", }, - { - "test1": "a", - "test2": "b" - } + {"test1": "a", "test2": "b"}, ], "data": [ { @@ -1125,7 +1047,7 @@ def test_normal_2_2(self, client, db): "amount": 10, "price": 20, "balance": 30, - "acquisition_date": "2022/12/02" + "acquisition_date": "2022/12/02", }, { "account_address": account_address_2, @@ -1134,18 +1056,15 @@ def test_normal_2_2(self, client, db): "amount": 100, "price": 200, "balance": 300, - "acquisition_date": "2022/12/03" - } + "acquisition_date": "2022/12/03", + }, ], "footers": [ { "key": "aaa", "value": "aaa", }, - { - "f-test1": "a", - "f-test2": "b" - } + {"f-test1": "a", "f-test2": "b"}, ], }, { @@ -1155,10 +1074,7 @@ def test_normal_2_2(self, client, db): "key": "aaa", "value": "aaa", }, - { - "test1-1": "a", - "test2-1": "b" - } + {"test1-1": "a", "test2-1": "b"}, ], "data": [ { @@ -1178,17 +1094,14 @@ def test_normal_2_2(self, client, db): "price": 30, "balance": 600, "acquisition_date": "2020/01/02", - } + }, ], "footers": [ { "key": "aaa", "value": "aaa", }, - { - "f-test1-1": "a", - "f-test2-1": "b" - } + {"f-test1-1": "a", "f-test2-1": "b"}, ], }, ], @@ -1200,7 +1113,7 @@ def test_normal_2_2(self, client, db): { "f-hoge": "aaaa", "f-fuga": "bbbb", - } + }, ], } @@ -1238,7 +1151,7 @@ def test_normal_3(self, client, db): { "hoge": "aaaa", "fuga": "bbbb", - } + }, ], "details": [ { @@ -1248,10 +1161,7 @@ def test_normal_3(self, client, db): "key": "aaa", "value": "aaa", }, - { - "test1": "a", - "test2": "b" - } + {"test1": "a", "test2": "b"}, ], "data": [ { @@ -1261,7 +1171,7 @@ def test_normal_3(self, client, db): "amount": 10, "price": 20, "balance": 30, - "acquisition_date": "2022/12/02" + "acquisition_date": "2022/12/02", }, { "account_address": account_address_2, @@ -1270,18 +1180,15 @@ def test_normal_3(self, client, db): "amount": 100, "price": 200, "balance": 300, - "acquisition_date": "2022/12/03" - } + "acquisition_date": "2022/12/03", + }, ], "footers": [ { "key": "aaa", "value": "aaa", }, - { - "f-test1": "a", - "f-test2": "b" - } + {"f-test1": "a", "f-test2": "b"}, ], }, { @@ -1291,10 +1198,7 @@ def test_normal_3(self, client, db): "key": "aaa", "value": "aaa", }, - { - "test1-1": "a", - "test2-1": "b" - } + {"test1-1": "a", "test2-1": "b"}, ], "data": [ { @@ -1314,17 +1218,14 @@ def test_normal_3(self, client, db): "price": 30, "balance": 600, "acquisition_date": "2020/01/02", - } + }, ], "footers": [ { "key": "aaa", "value": "aaa", }, - { - "f-test1-1": "a", - "f-test2-1": "b" - } + {"f-test1-1": "a", "f-test2-1": "b"}, ], }, ], @@ -1336,10 +1237,12 @@ def test_normal_3(self, client, db): { "f-hoge": "aaaa", "f-fuga": "bbbb", - } + }, ], } - _ledger_1.ledger_created = datetime.strptime("2022/01/01 15:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/02 + _ledger_1.ledger_created = datetime.strptime( + "2022/01/01 15:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/02 db.add(_ledger_1) _details_1 = LedgerDetailsTemplate() @@ -1350,20 +1253,14 @@ def test_normal_3(self, client, db): "key": "aaa", "value": "aaa", }, - { - "test1": "a", - "test2": "b" - } + {"test1": "a", "test2": "b"}, ] _details_1.footers = [ { "key": "aaa", "value": "aaa", }, - { - "f-test1": "a", - "f-test2": "b" - } + {"f-test1": "a", "f-test2": "b"}, ] _details_1.data_type = LedgerDetailsDataType.IBET_FIN.value _details_1.data_source = token_address @@ -1382,7 +1279,7 @@ def test_normal_3(self, client, db): }, headers={ "issuer-address": issuer_address, - } + }, ) # assertion @@ -1398,7 +1295,7 @@ def test_normal_3(self, client, db): { "hoge": "aaaa", "fuga": "bbbb", - } + }, ], "details": [ { @@ -1408,10 +1305,7 @@ def test_normal_3(self, client, db): "key": "aaa", "value": "aaa", }, - { - "test1": "a", - "test2": "b" - } + {"test1": "a", "test2": "b"}, ], "data": [ { @@ -1422,7 +1316,7 @@ def test_normal_3(self, client, db): "amount": 10, "price": 20, "balance": 30, - "acquisition_date": "2022/12/02" + "acquisition_date": "2022/12/02", }, { "account_address": account_address_2, @@ -1431,18 +1325,15 @@ def test_normal_3(self, client, db): "amount": 100, "price": 200, "balance": 300, - "acquisition_date": "2022/12/03" - } + "acquisition_date": "2022/12/03", + }, ], "footers": [ { "key": "aaa", "value": "aaa", }, - { - "f-test1": "a", - "f-test2": "b" - } + {"f-test1": "a", "f-test2": "b"}, ], }, { @@ -1452,10 +1343,7 @@ def test_normal_3(self, client, db): "key": "aaa", "value": "aaa", }, - { - "test1-1": "a", - "test2-1": "b" - } + {"test1-1": "a", "test2-1": "b"}, ], "data": [ { @@ -1475,17 +1363,14 @@ def test_normal_3(self, client, db): "price": 30, "balance": 600, "acquisition_date": "2020/01/02", - } + }, ], "footers": [ { "key": "aaa", "value": "aaa", }, - { - "f-test1-1": "a", - "f-test2-1": "b" - } + {"f-test1-1": "a", "f-test2-1": "b"}, ], }, ], @@ -1497,7 +1382,7 @@ def test_normal_3(self, client, db): { "f-hoge": "aaaa", "f-fuga": "bbbb", - } + }, ], } @@ -1518,23 +1403,20 @@ def test_error_1(self, client, db): }, headers={ "issuer-address": "test", - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -1552,26 +1434,21 @@ def test_error_2(self, client, db): }, headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "ctx": { - "limit_value": 0 - }, + "ctx": {"limit_value": 0}, "loc": ["query", "latest_flg"], "msg": "ensure this value is greater than or equal to 0", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", } - ] + ], } # @@ -1589,26 +1466,21 @@ def test_error_3(self, client, db): }, headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "ctx": { - "limit_value": 1 - }, + "ctx": {"limit_value": 1}, "loc": ["query", "latest_flg"], "msg": "ensure this value is less than or equal to 1", - "type": "value_error.number.not_le" + "type": "value_error.number.not_le", } - ] + ], } # @@ -1623,7 +1495,9 @@ def test_error_4_1(self, client, db): _token = Token() _token.type = TokenType.IBET_STRAIGHT_BOND.value _token.tx_hash = "" - _token.issuer_address = "0x1234567890123456789012345678901234567899" # not target + _token.issuer_address = ( + "0x1234567890123456789012345678901234567899" # not target + ) _token.token_address = token_address _token.abi = {} _token.token_status = 2 @@ -1637,17 +1511,14 @@ def test_error_4_1(self, client, db): }, headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token does not exist" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token does not exist", } # @@ -1667,11 +1538,8 @@ def test_error_4_2(self, client, db): # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token does not exist" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token does not exist", } # @@ -1699,17 +1567,14 @@ def test_error_5(self, client, db): }, headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } # @@ -1736,16 +1601,12 @@ def test_error_6(self, client, db): }, headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "ledger does not exist" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "ledger does not exist", } - diff --git a/tests/test_app_routers_ledger_{token_address}_template_DELETE.py b/tests/test_app_routers_ledger_{token_address}_template_DELETE.py index 2644f546..6f69fe33 100644 --- a/tests/test_app_routers_ledger_{token_address}_template_DELETE.py +++ b/tests/test_app_routers_ledger_{token_address}_template_DELETE.py @@ -17,17 +17,16 @@ SPDX-License-Identifier: Apache-2.0 """ from app.model.db import ( + LedgerDetailsDataType, + LedgerDetailsTemplate, + LedgerTemplate, Token, TokenType, - LedgerTemplate, - LedgerDetailsTemplate, - LedgerDetailsDataType ) from tests.account_config import config_eth_account class TestAppRoutersLedgerTokenAddressTemplateDELETE: - # target API endpoint base_url = "/ledger/{token_address}/template" @@ -62,7 +61,7 @@ def test_normal_1(self, client, db): { "hoge": "aaaa", "fuga": "bbbb", - } + }, ] _template.footers = [ { @@ -72,7 +71,7 @@ def test_normal_1(self, client, db): { "f-hoge": "f-aaaa", "f-fuga": "f-bbbb", - } + }, ] db.add(_template) @@ -84,20 +83,14 @@ def test_normal_1(self, client, db): "key": "aaa", "value": "bbb", }, - { - "test1": "a", - "test2": "b" - } + {"test1": "a", "test2": "b"}, ] _details_1.footers = [ { "key": "aaa", "value": "bbb", }, - { - "f-test1": "a", - "f-test2": "b" - } + {"f-test1": "a", "f-test2": "b"}, ] _details_1.data_type = LedgerDetailsDataType.IBET_FIN.value _details_1.data_source = token_address @@ -111,20 +104,14 @@ def test_normal_1(self, client, db): "key": "aaa", "value": "bbb", }, - { - "test3": "a", - "test4": "b" - } + {"test3": "a", "test4": "b"}, ] _details_2.footers = [ { "key": "aaa", "value": "bbb", }, - { - "f-test3": "a", - "f-test4": "b" - } + {"f-test3": "a", "f-test4": "b"}, ] _details_2.data_type = LedgerDetailsDataType.DB.value _details_2.data_source = "data_id_2" @@ -135,7 +122,7 @@ def test_normal_1(self, client, db): self.base_url.format(token_address=token_address), headers={ "issuer-address": issuer_address, - } + }, ) # assertion @@ -163,17 +150,14 @@ def test_error_1(self, client, db): # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", } - ] + ], } # @@ -186,23 +170,20 @@ def test_error_2(self, client, db): self.base_url.format(token_address=token_address), headers={ "issuer-address": "test", - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -217,17 +198,14 @@ def test_error_3(self, client, db): self.base_url.format(token_address=token_address), headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token does not exist" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token does not exist", } # @@ -252,17 +230,14 @@ def test_error_4(self, client, db): self.base_url.format(token_address=token_address), headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } # @@ -286,15 +261,12 @@ def test_error_5(self, client, db): self.base_url.format(token_address=token_address), headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "ledger template does not exist" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "ledger template does not exist", } diff --git a/tests/test_app_routers_ledger_{token_address}_template_GET.py b/tests/test_app_routers_ledger_{token_address}_template_GET.py index cd10eb87..61d70832 100644 --- a/tests/test_app_routers_ledger_{token_address}_template_GET.py +++ b/tests/test_app_routers_ledger_{token_address}_template_GET.py @@ -17,11 +17,11 @@ SPDX-License-Identifier: Apache-2.0 """ from app.model.db import ( + LedgerDetailsDataType, + LedgerDetailsTemplate, + LedgerTemplate, Token, TokenType, - LedgerTemplate, - LedgerDetailsTemplate, - LedgerDetailsDataType ) from tests.account_config import config_eth_account @@ -62,7 +62,7 @@ def test_normal_1_1(self, client, db): { "hoge": "aaaa", "fuga": "bbbb", - } + }, ] _template.footers = [ { @@ -72,7 +72,7 @@ def test_normal_1_1(self, client, db): { "f-hoge": "f-aaaa", "f-fuga": "f-bbbb", - } + }, ] db.add(_template) @@ -84,20 +84,14 @@ def test_normal_1_1(self, client, db): "key": "aaa", "value": "bbb", }, - { - "test1": "a", - "test2": "b" - } + {"test1": "a", "test2": "b"}, ] _details_1.footers = [ { "key": "aaa", "value": "bbb", }, - { - "f-test1": "a", - "f-test2": "b" - } + {"f-test1": "a", "f-test2": "b"}, ] _details_1.data_type = LedgerDetailsDataType.IBET_FIN.value _details_1.data_source = token_address @@ -111,20 +105,14 @@ def test_normal_1_1(self, client, db): "key": "aaa", "value": "bbb", }, - { - "test3": "a", - "test4": "b" - } + {"test3": "a", "test4": "b"}, ] _details_2.footers = [ { "key": "aaa", "value": "bbb", }, - { - "f-test3": "a", - "f-test4": "b" - } + {"f-test3": "a", "f-test4": "b"}, ] _details_2.data_type = LedgerDetailsDataType.DB.value _details_2.data_source = "data_id_2" @@ -135,7 +123,7 @@ def test_normal_1_1(self, client, db): self.base_url.format(token_address=token_address), headers={ "issuer-address": issuer_address, - } + }, ) # assertion @@ -150,7 +138,7 @@ def test_normal_1_1(self, client, db): { "hoge": "aaaa", "fuga": "bbbb", - } + }, ], "details": [ { @@ -160,10 +148,7 @@ def test_normal_1_1(self, client, db): "key": "aaa", "value": "bbb", }, - { - "test1": "a", - "test2": "b" - } + {"test1": "a", "test2": "b"}, ], "data": { "type": "ibetfin", @@ -174,10 +159,7 @@ def test_normal_1_1(self, client, db): "key": "aaa", "value": "bbb", }, - { - "f-test1": "a", - "f-test2": "b" - } + {"f-test1": "a", "f-test2": "b"}, ], }, { @@ -187,10 +169,7 @@ def test_normal_1_1(self, client, db): "key": "aaa", "value": "bbb", }, - { - "test3": "a", - "test4": "b" - } + {"test3": "a", "test4": "b"}, ], "data": { "type": "db", @@ -201,12 +180,9 @@ def test_normal_1_1(self, client, db): "key": "aaa", "value": "bbb", }, - { - "f-test3": "a", - "f-test4": "b" - } + {"f-test3": "a", "f-test4": "b"}, ], - } + }, ], "footers": [ { @@ -216,7 +192,7 @@ def test_normal_1_1(self, client, db): { "f-hoge": "f-aaaa", "f-fuga": "f-bbbb", - } + }, ], } @@ -248,7 +224,7 @@ def test_normal_1_2(self, client, db): { "hoge": "aaaa", "fuga": "bbbb", - } + }, ] _template.footers = [ { @@ -258,7 +234,7 @@ def test_normal_1_2(self, client, db): { "f-hoge": "f-aaaa", "f-fuga": "f-bbbb", - } + }, ] db.add(_template) @@ -270,20 +246,14 @@ def test_normal_1_2(self, client, db): "key": "aaa", "value": "bbb", }, - { - "test1": "a", - "test2": "b" - } + {"test1": "a", "test2": "b"}, ] _details_1.footers = [ { "key": "aaa", "value": "bbb", }, - { - "f-test1": "a", - "f-test2": "b" - } + {"f-test1": "a", "f-test2": "b"}, ] _details_1.data_type = LedgerDetailsDataType.IBET_FIN.value _details_1.data_source = token_address @@ -297,20 +267,14 @@ def test_normal_1_2(self, client, db): "key": "aaa", "value": "bbb", }, - { - "test3": "a", - "test4": "b" - } + {"test3": "a", "test4": "b"}, ] _details_2.footers = [ { "key": "aaa", "value": "bbb", }, - { - "f-test3": "a", - "f-test4": "b" - } + {"f-test3": "a", "f-test4": "b"}, ] _details_2.data_type = LedgerDetailsDataType.DB.value _details_2.data_source = "data_id_2" @@ -333,7 +297,7 @@ def test_normal_1_2(self, client, db): { "hoge": "aaaa", "fuga": "bbbb", - } + }, ], "details": [ { @@ -343,10 +307,7 @@ def test_normal_1_2(self, client, db): "key": "aaa", "value": "bbb", }, - { - "test1": "a", - "test2": "b" - } + {"test1": "a", "test2": "b"}, ], "data": { "type": "ibetfin", @@ -357,10 +318,7 @@ def test_normal_1_2(self, client, db): "key": "aaa", "value": "bbb", }, - { - "f-test1": "a", - "f-test2": "b" - } + {"f-test1": "a", "f-test2": "b"}, ], }, { @@ -370,10 +328,7 @@ def test_normal_1_2(self, client, db): "key": "aaa", "value": "bbb", }, - { - "test3": "a", - "test4": "b" - } + {"test3": "a", "test4": "b"}, ], "data": { "type": "db", @@ -384,12 +339,9 @@ def test_normal_1_2(self, client, db): "key": "aaa", "value": "bbb", }, - { - "f-test3": "a", - "f-test4": "b" - } + {"f-test3": "a", "f-test4": "b"}, ], - } + }, ], "footers": [ { @@ -399,7 +351,7 @@ def test_normal_1_2(self, client, db): { "f-hoge": "f-aaaa", "f-fuga": "f-bbbb", - } + }, ], } @@ -441,7 +393,7 @@ def test_normal_2(self, client, db): self.base_url.format(token_address=token_address), headers={ "issuer-address": issuer_address, - } + }, ) # assertion @@ -477,23 +429,20 @@ def test_error_1(self, client, db): self.base_url.format(token_address=token_address), headers={ "issuer-address": "test", - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -508,7 +457,9 @@ def test_error_2(self, client, db): _token = Token() _token.type = TokenType.IBET_STRAIGHT_BOND.value _token.tx_hash = "" - _token.issuer_address = "0x1234567890123456789012345678901234567899" # not target + _token.issuer_address = ( + "0x1234567890123456789012345678901234567899" # not target + ) _token.token_address = token_address _token.abi = {} _token.token_status = 2 @@ -519,17 +470,14 @@ def test_error_2(self, client, db): self.base_url.format(token_address=token_address), headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token does not exist" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token does not exist", } # @@ -546,11 +494,8 @@ def test_error_2_2(self, client, db): # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token does not exist" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token does not exist", } # @@ -575,17 +520,14 @@ def test_error_3(self, client, db): self.base_url.format(token_address=token_address), headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } # @@ -609,15 +551,12 @@ def test_error_4(self, client, db): self.base_url.format(token_address=token_address), headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "ledger template does not exist" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "ledger template does not exist", } diff --git a/tests/test_app_routers_ledger_{token_address}_template_POST.py b/tests/test_app_routers_ledger_{token_address}_template_POST.py index 7a0048ae..1a2e79de 100644 --- a/tests/test_app_routers_ledger_{token_address}_template_POST.py +++ b/tests/test_app_routers_ledger_{token_address}_template_POST.py @@ -19,11 +19,11 @@ from unittest import mock from app.model.db import ( + LedgerDetailsDataType, + LedgerDetailsTemplate, + LedgerTemplate, Token, TokenType, - LedgerTemplate, - LedgerDetailsTemplate, - LedgerDetailsDataType ) from tests.account_config import config_eth_account @@ -64,7 +64,7 @@ def test_normal_1(self, mock_func, client, db): { "hoge": "aaa", "fuga": "bbb", - } + }, ], "details": [ { @@ -77,7 +77,7 @@ def test_normal_1(self, mock_func, client, db): { "hoge-1": "aaa-1", "fuga-1": "bbb-1", - } + }, ], "data": { "type": LedgerDetailsDataType.IBET_FIN.value, @@ -91,7 +91,7 @@ def test_normal_1(self, mock_func, client, db): { "f-hoge-1": "aaa-1", "f-fuga-1": "bbb-1", - } + }, ], }, { @@ -104,7 +104,7 @@ def test_normal_1(self, mock_func, client, db): { "hoge-2": "aaa-2", "fuga-2": "bbb-2", - } + }, ], "data": { "type": LedgerDetailsDataType.DB.value, @@ -118,9 +118,9 @@ def test_normal_1(self, mock_func, client, db): { "f-hoge-2": "aaa-2", "f-fuga-2": "bbb-2", - } + }, ], - } + }, ], "footers": [ { @@ -130,7 +130,7 @@ def test_normal_1(self, mock_func, client, db): { "f-hoge": "aaa", "f-fuga": "bbb", - } + }, ], } resp = client.post( @@ -138,14 +138,13 @@ def test_normal_1(self, mock_func, client, db): json=req_param, headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 200 assert resp.json() is None - _template = db.query(LedgerTemplate). \ - first() + _template = db.query(LedgerTemplate).first() assert _template.token_address == token_address assert _template.issuer_address == issuer_address assert _template.token_name == "テスト原簿" @@ -157,7 +156,7 @@ def test_normal_1(self, mock_func, client, db): { "hoge": "aaa", "fuga": "bbb", - } + }, ] assert _template.footers == [ { @@ -167,11 +166,11 @@ def test_normal_1(self, mock_func, client, db): { "f-hoge": "aaa", "f-fuga": "bbb", - } + }, ] - _details_list = db.query(LedgerDetailsTemplate). \ - order_by(LedgerDetailsTemplate.id). \ - all() + _details_list = ( + db.query(LedgerDetailsTemplate).order_by(LedgerDetailsTemplate.id).all() + ) assert len(_details_list) == 2 _details = _details_list[0] assert _details.id == 1 @@ -185,7 +184,7 @@ def test_normal_1(self, mock_func, client, db): { "hoge-1": "aaa-1", "fuga-1": "bbb-1", - } + }, ] assert _details.footers == [ { @@ -195,7 +194,7 @@ def test_normal_1(self, mock_func, client, db): { "f-hoge-1": "aaa-1", "f-fuga-1": "bbb-1", - } + }, ] assert _details.data_type == LedgerDetailsDataType.IBET_FIN.value assert _details.data_source == token_address @@ -211,7 +210,7 @@ def test_normal_1(self, mock_func, client, db): { "hoge-2": "aaa-2", "fuga-2": "bbb-2", - } + }, ] assert _details.footers == [ { @@ -221,7 +220,7 @@ def test_normal_1(self, mock_func, client, db): { "f-hoge-2": "aaa-2", "f-fuga-2": "bbb-2", - } + }, ] assert _details.data_type == LedgerDetailsDataType.DB.value assert _details.data_source == "data_id_2" @@ -257,7 +256,7 @@ def test_normal_2(self, mock_func, client, db): { "hoge": "aaa", "fuga": "bbb", - } + }, ] _template.footers = [ { @@ -267,7 +266,7 @@ def test_normal_2(self, mock_func, client, db): { "f-hoge": "aaa", "f-fuga": "bbb", - } + }, ] db.add(_template) @@ -282,7 +281,7 @@ def test_normal_2(self, mock_func, client, db): { "hoge-2": "aaa-2", "fuga-2": "bbb-2", - } + }, ] _details_1.footers = [ { @@ -292,7 +291,7 @@ def test_normal_2(self, mock_func, client, db): { "f-hoge-2": "aaa-2", "f-fuga-2": "bbb-2", - } + }, ] _details_1.data_type = LedgerDetailsDataType.DB.value _details_1.data_source = "data_id_1" @@ -309,7 +308,7 @@ def test_normal_2(self, mock_func, client, db): { "hoge-3": "aaa-3", "fuga-3": "bbb-3", - } + }, ] _details_2.footers = [ { @@ -319,7 +318,7 @@ def test_normal_2(self, mock_func, client, db): { "f-hoge-3": "aaa-3", "f-fuga-3": "bbb-3", - } + }, ] _details_2.data_type = LedgerDetailsDataType.DB.value _details_2.data_source = "data_id_2" @@ -336,7 +335,7 @@ def test_normal_2(self, mock_func, client, db): { "hoge_update": "aaa_update", "fuga_update": "bbb_update", - } + }, ], "details": [ { @@ -349,7 +348,7 @@ def test_normal_2(self, mock_func, client, db): { "hoge-1": "aaa-1", "fuga-1": "bbb-1", - } + }, ], "data": { "type": LedgerDetailsDataType.IBET_FIN.value, @@ -363,7 +362,7 @@ def test_normal_2(self, mock_func, client, db): { "f-hoge-1": "aaa-1", "f-fuga-1": "bbb-1", - } + }, ], }, { @@ -390,9 +389,9 @@ def test_normal_2(self, mock_func, client, db): { "f-hoge-2_update": "aaa-2_update", "f-fuga-2_update": "bbb-2_update", - } + }, ], - } + }, ], "footers": [ { @@ -402,7 +401,7 @@ def test_normal_2(self, mock_func, client, db): { "f-hoge_update": "aaa_update", "f-fuga_update": "bbb_update", - } + }, ], } resp = client.post( @@ -410,13 +409,12 @@ def test_normal_2(self, mock_func, client, db): json=req_param, headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 200 - _template = db.query(LedgerTemplate). \ - first() + _template = db.query(LedgerTemplate).first() assert _template.token_address == token_address assert _template.issuer_address == issuer_address assert _template.token_name == "テスト原簿_update" @@ -428,7 +426,7 @@ def test_normal_2(self, mock_func, client, db): { "hoge_update": "aaa_update", "fuga_update": "bbb_update", - } + }, ] assert _template.footers == [ { @@ -438,11 +436,11 @@ def test_normal_2(self, mock_func, client, db): { "f-hoge_update": "aaa_update", "f-fuga_update": "bbb_update", - } + }, ] - _details_list = db.query(LedgerDetailsTemplate). \ - order_by(LedgerDetailsTemplate.id). \ - all() + _details_list = ( + db.query(LedgerDetailsTemplate).order_by(LedgerDetailsTemplate.id).all() + ) assert len(_details_list) == 2 _details = _details_list[0] assert _details.id == 1 @@ -456,7 +454,7 @@ def test_normal_2(self, mock_func, client, db): { "hoge-2_update": "aaa-2_update", "fuga-2_update": "bbb-2_update", - } + }, ] assert _details.footers == [ { @@ -466,7 +464,7 @@ def test_normal_2(self, mock_func, client, db): { "f-hoge-2_update": "aaa-2_update", "f-fuga-2_update": "bbb-2_update", - } + }, ] assert _details.data_type == LedgerDetailsDataType.IBET_FIN.value assert _details.data_source == token_address @@ -482,7 +480,7 @@ def test_normal_2(self, mock_func, client, db): { "hoge-1": "aaa-1", "fuga-1": "bbb-1", - } + }, ] assert _details.footers == [ { @@ -492,7 +490,7 @@ def test_normal_2(self, mock_func, client, db): { "f-hoge-1": "aaa-1", "f-fuga-1": "bbb-1", - } + }, ] assert _details.data_type == LedgerDetailsDataType.IBET_FIN.value assert _details.data_source == token_address @@ -516,22 +514,19 @@ def test_error_1(self, client, db): # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, { "loc": ["body"], "msg": "field required", - "type": "value_error.missing" - } - ] + "type": "value_error.missing", + }, + ], } # @@ -550,7 +545,7 @@ def test_error_2(self, client, db): { "hoge": "aaa", "fuga": "bbb", - } + }, ], "details": [ { @@ -563,7 +558,7 @@ def test_error_2(self, client, db): { "hoge-1": "aaa-1", "fuga-1": "bbb-1", - } + }, ], "data": { "type": LedgerDetailsDataType.IBET_FIN.value, @@ -577,7 +572,7 @@ def test_error_2(self, client, db): { "f-hoge-1": "aaa-1", "f-fuga-1": "bbb-1", - } + }, ], }, { @@ -590,7 +585,7 @@ def test_error_2(self, client, db): { "hoge-2": "aaa-2", "fuga-2": "bbb-2", - } + }, ], "data": { "type": LedgerDetailsDataType.DB.value, @@ -604,9 +599,9 @@ def test_error_2(self, client, db): { "f-hoge-2": "aaa-2", "f-fuga-2": "bbb-2", - } + }, ], - } + }, ], "footers": [ { @@ -616,7 +611,7 @@ def test_error_2(self, client, db): { "f-hoge": "aaa", "f-fuga": "bbb", - } + }, ], } resp = client.post( @@ -624,23 +619,20 @@ def test_error_2(self, client, db): json=req_param, headers={ "issuer-address": "test", - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -659,28 +651,25 @@ def test_error_3(self, client, db): json=req_param, headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "token_name"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, { "loc": ["body", "details"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, - ] + ], } # @@ -693,8 +682,8 @@ def test_error_4(self, client, db): # request target API req_param = { "token_name": "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" - "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" - "1", + "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" + "1", "headers": [ { "key": "aaa", @@ -703,7 +692,7 @@ def test_error_4(self, client, db): { "hoge": "aaa", "fuga": "bbb", - } + }, ], "details": [], "footers": [ @@ -714,7 +703,7 @@ def test_error_4(self, client, db): { "hoge": "aaa", "fuga": "bbb", - } + }, ], } resp = client.post( @@ -722,29 +711,26 @@ def test_error_4(self, client, db): json=req_param, headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "ctx": {"limit_value": 200}, "loc": ["body", "token_name"], "msg": "ensure this value has at most 200 characters", - "type": "value_error.any_str.max_length" + "type": "value_error.any_str.max_length", }, { "loc": ["body", "details"], "msg": "The length must be greater than or equal to 1", - "type": "value_error" - } - ] + "type": "value_error", + }, + ], } # @@ -765,7 +751,7 @@ def test_error_5(self, client, db): { "hoge": "aaa", "fuga": "bbb", - } + }, ], "details": [ { @@ -778,7 +764,7 @@ def test_error_5(self, client, db): { "hoge-1": "aaa-1", "fuga-1": "bbb-1", - } + }, ], "data": { "type": "ibetfina", @@ -792,7 +778,7 @@ def test_error_5(self, client, db): { "f-hoge-1": "d-aaa-1", "f-fuga-1": "d-bbb-1", - } + }, ], }, { @@ -808,7 +794,7 @@ def test_error_5(self, client, db): { "hoge-1": "aaa-1", "fuga-1": "bbb-1", - } + }, ], "data": { "dummy": "dummy", @@ -821,7 +807,7 @@ def test_error_5(self, client, db): { "f-hoge-1": "aaa-1", "f-fuga-1": "bbb-1", - } + }, ], }, ], @@ -833,7 +819,7 @@ def test_error_5(self, client, db): { "hoge": "aaa", "fuga": "bbb", - } + }, ], } resp = client.post( @@ -841,53 +827,48 @@ def test_error_5(self, client, db): json=req_param, headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "ctx": {"limit_value": 100}, "loc": ["body", "details", 0, "token_detail_type"], "msg": "ensure this value has at most 100 characters", - "type": "value_error.any_str.max_length" - + "type": "value_error.any_str.max_length", }, { "ctx": {"enum_values": ["ibetfin", "db"]}, "loc": ["body", "details", 0, "data", "type"], "msg": "value is not a valid enumeration member; permitted: 'ibetfin', 'db'", - "type": "type_error.enum" + "type": "type_error.enum", }, { - "ctx": {"limit_value": 42}, "loc": ["body", "details", 0, "data", "source"], "msg": "ensure this value has at most 42 characters", - "type": "value_error.any_str.max_length" + "type": "value_error.any_str.max_length", }, { "loc": ["body", "details", 1, "token_detail_type"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, { "loc": ["body", "details", 1, "data"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, { "loc": ["body", "details", 2, "data", "type"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, - ] + ], } # @@ -940,38 +921,35 @@ def test_error_6(self, client, db): json=req_param, headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "headers"], "msg": "value is not a valid list", - "type": "type_error.list" + "type": "type_error.list", }, { "loc": ["body", "details", 0, "headers"], "msg": "value is not a valid list", - "type": "type_error.list" + "type": "type_error.list", }, { "loc": ["body", "details", 0, "footers"], "msg": "value is not a valid list", - "type": "type_error.list" + "type": "type_error.list", }, { "loc": ["body", "footers"], "msg": "value is not a valid list", - "type": "type_error.list" + "type": "type_error.list", }, - ] + ], } # @@ -992,7 +970,7 @@ def test_error_7(self, client, db): { "hoge": "aaa", "fuga": "bbb", - } + }, ], "details": [ { @@ -1005,7 +983,7 @@ def test_error_7(self, client, db): { "hoge-1": "aaa-1", "fuga-1": "bbb-1", - } + }, ], "data": { "type": LedgerDetailsDataType.IBET_FIN.value, @@ -1019,7 +997,7 @@ def test_error_7(self, client, db): { "f-hoge-1": "aaa-1", "f-fuga-1": "bbb-1", - } + }, ], }, { @@ -1032,7 +1010,7 @@ def test_error_7(self, client, db): { "hoge-2": "aaa-2", "fuga-2": "bbb-2", - } + }, ], "data": { "type": LedgerDetailsDataType.DB.value, @@ -1046,9 +1024,9 @@ def test_error_7(self, client, db): { "f-hoge-2": "aaa-2", "f-fuga-2": "bbb-2", - } + }, ], - } + }, ], "footers": [ { @@ -1058,7 +1036,7 @@ def test_error_7(self, client, db): { "f-hoge": "aaa", "f-fuga": "bbb", - } + }, ], } resp = client.post( @@ -1066,17 +1044,14 @@ def test_error_7(self, client, db): json=req_param, headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token does not exist" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token does not exist", } # @@ -1107,7 +1082,7 @@ def test_error_8(self, client, db): { "hoge": "aaa", "fuga": "bbb", - } + }, ], "details": [ { @@ -1120,7 +1095,7 @@ def test_error_8(self, client, db): { "hoge-1": "aaa-1", "fuga-1": "bbb-1", - } + }, ], "data": { "type": LedgerDetailsDataType.IBET_FIN.value, @@ -1134,7 +1109,7 @@ def test_error_8(self, client, db): { "f-hoge-1": "aaa-1", "f-fuga-1": "bbb-1", - } + }, ], }, { @@ -1147,7 +1122,7 @@ def test_error_8(self, client, db): { "hoge-2": "aaa-2", "fuga-2": "bbb-2", - } + }, ], "data": { "type": LedgerDetailsDataType.DB.value, @@ -1161,9 +1136,9 @@ def test_error_8(self, client, db): { "f-hoge-2": "aaa-2", "f-fuga-2": "bbb-2", - } + }, ], - } + }, ], "footers": [ { @@ -1173,7 +1148,7 @@ def test_error_8(self, client, db): { "f-hoge": "aaa", "f-fuga": "bbb", - } + }, ], } resp = client.post( @@ -1181,15 +1156,12 @@ def test_error_8(self, client, db): json=req_param, headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } diff --git a/tests/test_app_routers_notifications_GET.py b/tests/test_app_routers_notifications_GET.py index d03d9b4d..6950465c 100644 --- a/tests/test_app_routers_notifications_GET.py +++ b/tests/test_app_routers_notifications_GET.py @@ -21,10 +21,10 @@ from unittest.mock import ANY from app.model.db import ( + BatchIssueRedeemProcessingCategory, Notification, NotificationType, TokenType, - BatchIssueRedeemProcessingCategory ) from tests.account_config import config_eth_account @@ -55,9 +55,11 @@ def test_normal_1(self, client, db): _notification_1.metainfo = { "upload_id": str(uuid.uuid4()), "token_type": TokenType.IBET_STRAIGHT_BOND.value, - "error_transfer_id": [] + "error_transfer_id": [], } - _notification_1.created = datetime.strptime("2022/01/01 15:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/02 + _notification_1.created = datetime.strptime( + "2022/01/01 15:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/02 db.add(_notification_1) _notification_2 = Notification() @@ -69,9 +71,11 @@ def test_normal_1(self, client, db): _notification_2.metainfo = { "scheduled_event_id": "1", "token_address": "0x0000000000000000000000000000000000000000", - "token_type": TokenType.IBET_STRAIGHT_BOND.value + "token_type": TokenType.IBET_STRAIGHT_BOND.value, } - _notification_2.created = datetime.strptime("2022/01/02 00:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/02 + _notification_2.created = datetime.strptime( + "2022/01/02 00:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/02 db.add(_notification_2) _notification_3 = Notification() @@ -83,9 +87,11 @@ def test_normal_1(self, client, db): _notification_3.metainfo = { "token_address": "0x0000000000000000000000000000000000000000", "token_type": TokenType.IBET_STRAIGHT_BOND.value, - "arguments": {} + "arguments": {}, } - _notification_3.created = datetime.strptime("2022/01/02 15:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/03 + _notification_3.created = datetime.strptime( + "2022/01/02 15:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/03 db.add(_notification_3) _notification_4 = Notification() @@ -97,9 +103,11 @@ def test_normal_1(self, client, db): _notification_4.metainfo = { "id": 1, "token_address": "0x0000000000000000000000000000000000000000", - "token_type": TokenType.IBET_STRAIGHT_BOND.value + "token_type": TokenType.IBET_STRAIGHT_BOND.value, } - _notification_4.created = datetime.strptime("2022/01/03 00:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/03 + _notification_4.created = datetime.strptime( + "2022/01/03 00:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/03 db.add(_notification_4) _notification_5 = Notification() @@ -111,12 +119,13 @@ def test_normal_1(self, client, db): _notification_5.metainfo = { "token_address": "0x0000000000000000000000000000000000000000", "token_type": TokenType.IBET_STRAIGHT_BOND.value, - "ledger_id": 1 + "ledger_id": 1, } - _notification_5.created = datetime.strptime("2022/01/05 00:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/03 + _notification_5.created = datetime.strptime( + "2022/01/05 00:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/03 db.add(_notification_5) - _notification_6 = Notification() _notification_6.notice_id = "notice_id_6" _notification_6.issuer_address = issuer_address_2 @@ -127,10 +136,11 @@ def test_normal_1(self, client, db): "upload_id": str(uuid.uuid4()), "error_registration_id": [1, 2, 3], } - _notification_6.created = datetime.strptime("2022/01/06 00:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/03 + _notification_6.created = datetime.strptime( + "2022/01/06 00:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/03 db.add(_notification_6) - _notification_7 = Notification() _notification_7.notice_id = "notice_id_7" _notification_7.issuer_address = issuer_address_2 @@ -142,9 +152,11 @@ def test_normal_1(self, client, db): "upload_id": str(uuid.uuid4()), "error_data_id": [1, 2, 3], "token_address": "0x0000000000000000000000000000000000000000", - "token_type": TokenType.IBET_STRAIGHT_BOND.value + "token_type": TokenType.IBET_STRAIGHT_BOND.value, } - _notification_7.created = datetime.strptime("2022/01/07 00:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/03 + _notification_7.created = datetime.strptime( + "2022/01/07 00:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/03 db.add(_notification_7) _notification_8 = Notification() @@ -159,11 +171,11 @@ def test_normal_1(self, client, db): "lock_address": "0x0000000000000000000000000000000000000000", "account_address": "0x0000000000000000000000000000000000000000", "value": 30, - "data": { - "message": "lock1" - } + "data": {"message": "lock1"}, } - _notification_8.created = datetime.strptime("2022/01/08 00:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/03 + _notification_8.created = datetime.strptime( + "2022/01/08 00:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/03 db.add(_notification_8) _notification_9 = Notification() @@ -179,11 +191,11 @@ def test_normal_1(self, client, db): "account_address": "0x0000000000000000000000000000000000000000", "recipient_address": "0x0000000000000000000000000000000000000000", "value": 30, - "data": { - "message": "unlock1" - } + "data": {"message": "unlock1"}, } - _notification_9.created = datetime.strptime("2022/01/09 00:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/03 + _notification_9.created = datetime.strptime( + "2022/01/09 00:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/03 db.add(_notification_9) # request target API @@ -194,12 +206,7 @@ def test_normal_1(self, client, db): # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 9, - "offset": None, - "limit": None, - "total": 9 - }, + "result_set": {"count": 9, "offset": None, "limit": None, "total": 9}, "notifications": [ { "notice_id": "notice_id_1", @@ -210,9 +217,9 @@ def test_normal_1(self, client, db): "metainfo": { "upload_id": ANY, "token_type": TokenType.IBET_STRAIGHT_BOND.value, - "error_transfer_id": [] + "error_transfer_id": [], }, - "created": "2022-01-02T00:20:30+09:00" + "created": "2022-01-02T00:20:30+09:00", }, { "notice_id": "notice_id_2", @@ -223,9 +230,9 @@ def test_normal_1(self, client, db): "metainfo": { "scheduled_event_id": "1", "token_address": "0x0000000000000000000000000000000000000000", - "token_type": TokenType.IBET_STRAIGHT_BOND.value + "token_type": TokenType.IBET_STRAIGHT_BOND.value, }, - "created": "2022-01-02T09:20:30+09:00" + "created": "2022-01-02T09:20:30+09:00", }, { "notice_id": "notice_id_3", @@ -236,9 +243,9 @@ def test_normal_1(self, client, db): "metainfo": { "token_address": "0x0000000000000000000000000000000000000000", "token_type": TokenType.IBET_STRAIGHT_BOND.value, - "arguments": {} + "arguments": {}, }, - "created": "2022-01-03T00:20:30+09:00" + "created": "2022-01-03T00:20:30+09:00", }, { "notice_id": "notice_id_4", @@ -249,9 +256,9 @@ def test_normal_1(self, client, db): "metainfo": { "id": 1, "token_address": "0x0000000000000000000000000000000000000000", - "token_type": TokenType.IBET_STRAIGHT_BOND + "token_type": TokenType.IBET_STRAIGHT_BOND, }, - "created": "2022-01-03T09:20:30+09:00" + "created": "2022-01-03T09:20:30+09:00", }, { "notice_id": "notice_id_5", @@ -262,9 +269,9 @@ def test_normal_1(self, client, db): "metainfo": { "token_address": "0x0000000000000000000000000000000000000000", "token_type": TokenType.IBET_STRAIGHT_BOND.value, - "ledger_id": 1 + "ledger_id": 1, }, - "created": "2022-01-05T09:20:30+09:00" + "created": "2022-01-05T09:20:30+09:00", }, { "notice_id": "notice_id_6", @@ -272,11 +279,8 @@ def test_normal_1(self, client, db): "priority": 0, "notice_type": NotificationType.BATCH_REGISTER_PERSONAL_INFO_ERROR, "notice_code": 1, - "metainfo": { - "upload_id": ANY, - "error_registration_id": [1, 2, 3] - }, - "created": "2022-01-06T09:20:30+09:00" + "metainfo": {"upload_id": ANY, "error_registration_id": [1, 2, 3]}, + "created": "2022-01-06T09:20:30+09:00", }, { "notice_id": "notice_id_7", @@ -289,9 +293,9 @@ def test_normal_1(self, client, db): "upload_id": ANY, "error_data_id": [1, 2, 3], "token_address": "0x0000000000000000000000000000000000000000", - "token_type": TokenType.IBET_STRAIGHT_BOND + "token_type": TokenType.IBET_STRAIGHT_BOND, }, - "created": "2022-01-07T09:20:30+09:00" + "created": "2022-01-07T09:20:30+09:00", }, { "notice_id": "notice_id_8", @@ -305,11 +309,9 @@ def test_normal_1(self, client, db): "lock_address": "0x0000000000000000000000000000000000000000", "account_address": "0x0000000000000000000000000000000000000000", "value": 30, - "data": { - "message": "lock1" - } + "data": {"message": "lock1"}, }, - "created": "2022-01-08T09:20:30+09:00" + "created": "2022-01-08T09:20:30+09:00", }, { "notice_id": "notice_id_9", @@ -324,13 +326,11 @@ def test_normal_1(self, client, db): "account_address": "0x0000000000000000000000000000000000000000", "recipient_address": "0x0000000000000000000000000000000000000000", "value": 30, - "data": { - "message": "unlock1" - } + "data": {"message": "unlock1"}, }, - "created": "2022-01-09T09:20:30+09:00" + "created": "2022-01-09T09:20:30+09:00", }, - ] + ], } # @@ -351,9 +351,11 @@ def test_normal_2(self, client, db): _notification_1.metainfo = { "upload_id": str(uuid.uuid4()), "token_type": TokenType.IBET_STRAIGHT_BOND.value, - "error_transfer_id": [] + "error_transfer_id": [], } - _notification_1.created = datetime.strptime("2022/01/01 15:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/02 + _notification_1.created = datetime.strptime( + "2022/01/01 15:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/02 db.add(_notification_1) _notification_2 = Notification() @@ -364,9 +366,11 @@ def test_normal_2(self, client, db): _notification_2.code = 1 _notification_2.metainfo = { "scheduled_event_id": "1", - "token_type": TokenType.IBET_STRAIGHT_BOND.value + "token_type": TokenType.IBET_STRAIGHT_BOND.value, } - _notification_2.created = datetime.strptime("2022/01/02 00:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/02 + _notification_2.created = datetime.strptime( + "2022/01/02 00:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/02 db.add(_notification_2) _notification_3 = Notification() @@ -378,9 +382,11 @@ def test_normal_2(self, client, db): _notification_3.metainfo = { "upload_id": str(uuid.uuid4()), "token_type": TokenType.IBET_STRAIGHT_BOND.value, - "error_transfer_id": [] + "error_transfer_id": [], } - _notification_3.created = datetime.strptime("2022/01/02 15:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/03 + _notification_3.created = datetime.strptime( + "2022/01/02 15:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/03 db.add(_notification_3) _notification_4 = Notification() @@ -391,9 +397,11 @@ def test_normal_2(self, client, db): _notification_4.code = 3 _notification_4.metainfo = { "scheduled_event_id": "1", - "token_type": TokenType.IBET_STRAIGHT_BOND.value + "token_type": TokenType.IBET_STRAIGHT_BOND.value, } - _notification_4.created = datetime.strptime("2022/01/03 00:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/03 + _notification_4.created = datetime.strptime( + "2022/01/03 00:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/03 db.add(_notification_4) # request target API @@ -404,18 +412,13 @@ def test_normal_2(self, client, db): }, headers={ "issuer-address": issuer_address_1, - } + }, ) # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 1, - "offset": None, - "limit": None, - "total": 4 - }, + "result_set": {"count": 1, "offset": None, "limit": None, "total": 4}, "notifications": [ { "notice_id": "notice_id_2", @@ -426,11 +429,11 @@ def test_normal_2(self, client, db): "metainfo": { "scheduled_event_id": "1", "token_address": None, - "token_type": TokenType.IBET_STRAIGHT_BOND.value + "token_type": TokenType.IBET_STRAIGHT_BOND.value, }, - "created": "2022-01-02T09:20:30+09:00" + "created": "2022-01-02T09:20:30+09:00", }, - ] + ], } # @@ -451,9 +454,11 @@ def test_normal_3(self, client, db): _notification_1.metainfo = { "upload_id": str(uuid.uuid4()), "token_type": TokenType.IBET_STRAIGHT_BOND.value, - "error_transfer_id": [] + "error_transfer_id": [], } - _notification_1.created = datetime.strptime("2022/01/01 15:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/02 + _notification_1.created = datetime.strptime( + "2022/01/01 15:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/02 db.add(_notification_1) _notification_2 = Notification() @@ -464,9 +469,11 @@ def test_normal_3(self, client, db): _notification_2.code = 1 _notification_2.metainfo = { "scheduled_event_id": "1", - "token_type": TokenType.IBET_STRAIGHT_BOND.value + "token_type": TokenType.IBET_STRAIGHT_BOND.value, } - _notification_2.created = datetime.strptime("2022/01/02 00:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/02 + _notification_2.created = datetime.strptime( + "2022/01/02 00:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/02 db.add(_notification_2) _notification_3 = Notification() @@ -478,9 +485,11 @@ def test_normal_3(self, client, db): _notification_3.metainfo = { "id": 1, "token_type": TokenType.IBET_STRAIGHT_BOND.value, - "token_address": "0x0000000000000000000000000000000000000000" + "token_address": "0x0000000000000000000000000000000000000000", } - _notification_3.created = datetime.strptime("2022/01/02 15:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/03 + _notification_3.created = datetime.strptime( + "2022/01/02 15:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/03 db.add(_notification_3) _notification_4 = Notification() @@ -491,29 +500,20 @@ def test_normal_3(self, client, db): _notification_4.code = 3 _notification_4.metainfo = { "scheduled_event_id": "1", - "token_type": TokenType.IBET_STRAIGHT_BOND.value + "token_type": TokenType.IBET_STRAIGHT_BOND.value, } - _notification_4.created = datetime.strptime("2022/01/03 00:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/03 + _notification_4.created = datetime.strptime( + "2022/01/03 00:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/03 db.add(_notification_4) # request target API - resp = client.get( - self.base_url, - params={ - "offset": 1, - "limit": 2 - } - ) + resp = client.get(self.base_url, params={"offset": 1, "limit": 2}) # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 4, - "offset": 1, - "limit": 2, - "total": 4 - }, + "result_set": {"count": 4, "offset": 1, "limit": 2, "total": 4}, "notifications": [ { "notice_id": "notice_id_2", @@ -524,9 +524,9 @@ def test_normal_3(self, client, db): "metainfo": { "scheduled_event_id": "1", "token_address": None, - "token_type": TokenType.IBET_STRAIGHT_BOND.value + "token_type": TokenType.IBET_STRAIGHT_BOND.value, }, - "created": "2022-01-02T09:20:30+09:00" + "created": "2022-01-02T09:20:30+09:00", }, { "notice_id": "notice_id_3", @@ -537,11 +537,11 @@ def test_normal_3(self, client, db): "metainfo": { "id": 1, "token_type": TokenType.IBET_STRAIGHT_BOND.value, - "token_address": "0x0000000000000000000000000000000000000000" + "token_address": "0x0000000000000000000000000000000000000000", }, - "created": "2022-01-03T00:20:30+09:00" + "created": "2022-01-03T00:20:30+09:00", }, - ] + ], } ########################################################################### @@ -556,21 +556,18 @@ def test_error_1(self, client, db): self.base_url, headers={ "issuer-address": "test", - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } diff --git a/tests/test_app_routers_notifications_{notice_id}_DELETE.py b/tests/test_app_routers_notifications_{notice_id}_DELETE.py index 7fb9f78a..71283e8f 100644 --- a/tests/test_app_routers_notifications_{notice_id}_DELETE.py +++ b/tests/test_app_routers_notifications_{notice_id}_DELETE.py @@ -18,10 +18,7 @@ """ from datetime import datetime -from app.model.db import ( - Notification, - NotificationType -) +from app.model.db import Notification, NotificationType from tests.account_config import config_eth_account @@ -48,10 +45,10 @@ def test_normal_1(self, client, db): _notification_1.priority = 0 _notification_1.type = NotificationType.BULK_TRANSFER_ERROR _notification_1.code = 0 - _notification_1.metainfo = { - "test_1": "test_1" - } - _notification_1.created = datetime.strptime("2022/01/01 15:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/02 + _notification_1.metainfo = {"test_1": "test_1"} + _notification_1.created = datetime.strptime( + "2022/01/01 15:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/02 db.add(_notification_1) _notification_2 = Notification() @@ -60,10 +57,10 @@ def test_normal_1(self, client, db): _notification_2.priority = 1 _notification_2.type = NotificationType.SCHEDULE_EVENT_ERROR _notification_2.code = 1 - _notification_2.metainfo = { - "test_2": "test_2" - } - _notification_2.created = datetime.strptime("2022/01/02 00:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/02 + _notification_2.metainfo = {"test_2": "test_2"} + _notification_2.created = datetime.strptime( + "2022/01/02 00:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/02 db.add(_notification_2) _notification_3 = Notification() @@ -72,10 +69,10 @@ def test_normal_1(self, client, db): _notification_3.priority = 2 _notification_3.type = NotificationType.BULK_TRANSFER_ERROR _notification_3.code = 2 - _notification_3.metainfo = { - "test_3": "test_3" - } - _notification_3.created = datetime.strptime("2022/01/02 15:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/03 + _notification_3.metainfo = {"test_3": "test_3"} + _notification_3.created = datetime.strptime( + "2022/01/02 15:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/03 db.add(_notification_3) _notification_4 = Notification() @@ -84,10 +81,10 @@ def test_normal_1(self, client, db): _notification_4.priority = 0 _notification_4.type = NotificationType.SCHEDULE_EVENT_ERROR _notification_4.code = 3 - _notification_4.metainfo = { - "test_4": "test_4" - } - _notification_4.created = datetime.strptime("2022/01/03 00:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/03 + _notification_4.metainfo = {"test_4": "test_4"} + _notification_4.created = datetime.strptime( + "2022/01/03 00:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/03 db.add(_notification_4) # request target API @@ -95,7 +92,7 @@ def test_normal_1(self, client, db): self.base_url.format(notice_id="notice_id_2"), headers={ "issuer-address": issuer_address_1, - } + }, ) # assertion @@ -110,9 +107,7 @@ def test_normal_1(self, client, db): assert _notification.priority == 0 assert _notification.type == NotificationType.BULK_TRANSFER_ERROR assert _notification.code == 0 - assert _notification.metainfo == { - "test_1": "test_1" - } + assert _notification.metainfo == {"test_1": "test_1"} _notification = _notification_list[1] assert _notification.id == 3 assert _notification.notice_id == "notice_id_3" @@ -120,9 +115,7 @@ def test_normal_1(self, client, db): assert _notification.priority == 2 assert _notification.type == NotificationType.BULK_TRANSFER_ERROR assert _notification.code == 2 - assert _notification.metainfo == { - "test_3": "test_3" - } + assert _notification.metainfo == {"test_3": "test_3"} _notification = _notification_list[2] assert _notification.id == 4 assert _notification.notice_id == "notice_id_4" @@ -130,9 +123,7 @@ def test_normal_1(self, client, db): assert _notification.priority == 0 assert _notification.type == NotificationType.SCHEDULE_EVENT_ERROR assert _notification.code == 3 - assert _notification.metainfo == { - "test_4": "test_4" - } + assert _notification.metainfo == {"test_4": "test_4"} ########################################################################### # Error Case @@ -149,17 +140,14 @@ def test_error_1(self, client, db): # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", } - ] + ], } # @@ -170,23 +158,20 @@ def test_error_2(self, client, db): self.base_url.format(notice_id="notice_id_2"), headers={ "issuer-address": "test", - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -200,15 +185,12 @@ def test_error_3(self, client, db): self.base_url.format(notice_id="notice_id_2"), headers={ "issuer-address": issuer_address_1, - } + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "notification does not exist" - } \ No newline at end of file + "meta": {"code": 1, "title": "NotFound"}, + "detail": "notification does not exist", + } diff --git a/tests/test_app_routers_positions_{account_address}_GET.py b/tests/test_app_routers_positions_{account_address}_GET.py index e19e33e2..7921a13d 100644 --- a/tests/test_app_routers_positions_{account_address}_GET.py +++ b/tests/test_app_routers_positions_{account_address}_GET.py @@ -18,16 +18,8 @@ """ from unittest import mock -from app.model.db import ( - IDXPosition, - IDXLockedPosition, - Token, - TokenType -) -from app.model.blockchain import ( - IbetStraightBondContract, - IbetShareContract -) +from app.model.blockchain import IbetShareContract, IbetStraightBondContract +from app.model.db import IDXLockedPosition, IDXPosition, Token, TokenType class TestAppRoutersPositionsAccountAddressGET: @@ -55,7 +47,9 @@ def test_normal_1(self, client, db): # prepare data: Position _position = IDXPosition() _position.token_address = "0x1234567890123456789012345678900000000010" - _position.account_address = "0x1234567890123456789012345678900000000001" # not target + _position.account_address = ( + "0x1234567890123456789012345678900000000001" # not target + ) _position.balance = 10 _position.exchange_balance = 11 _position.exchange_commitment = 12 @@ -76,7 +70,7 @@ def test_normal_1(self, client, db): "limit": None, "total": 0, }, - "positions": [] + "positions": [], } # @@ -110,14 +104,18 @@ def test_normal_2(self, mock_IbetStraightBondContract_get, client, db): # prepare data: Locked Position _locked_position = IDXLockedPosition() _locked_position.token_address = token_address_1 - _locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + _locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) _locked_position.account_address = account_address _locked_position.value = 5 db.add(_locked_position) _locked_position = IDXLockedPosition() _locked_position.token_address = token_address_1 - _locked_position.lock_address = "0x1234567890123456789012345678900000000002" # lock address 2 + _locked_position.lock_address = ( + "0x1234567890123456789012345678900000000002" # lock address 2 + ) _locked_position.account_address = account_address _locked_position.value = 5 db.add(_locked_position) @@ -158,16 +156,18 @@ def test_normal_2(self, mock_IbetStraightBondContract_get, client, db): "exchange_balance": 11, "exchange_commitment": 12, "pending_transfer": 13, - "locked": 10 + "locked": 10, }, - ] + ], } # # multi record @mock.patch("app.model.blockchain.token.IbetShareContract.get") @mock.patch("app.model.blockchain.token.IbetStraightBondContract.get") - def test_normal_3_1(self, mock_IbetStraightBondContract_get, mock_IbetShareContract_get, client, db): + def test_normal_3_1( + self, mock_IbetStraightBondContract_get, mock_IbetShareContract_get, client, db + ): issuer_address = "0x1234567890123456789012345678900000000100" account_address = "0x1234567890123456789012345678900000000000" token_address_1 = "0x1234567890123456789012345678900000000010" @@ -196,14 +196,18 @@ def test_normal_3_1(self, mock_IbetStraightBondContract_get, mock_IbetShareContr # prepare data: Locked Position 1 _locked_position = IDXLockedPosition() _locked_position.token_address = token_address_1 - _locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + _locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) _locked_position.account_address = account_address _locked_position.value = 5 db.add(_locked_position) _locked_position = IDXLockedPosition() _locked_position.token_address = token_address_1 - _locked_position.lock_address = "0x1234567890123456789012345678900000000002" # lock address 2 + _locked_position.lock_address = ( + "0x1234567890123456789012345678900000000002" # lock address 2 + ) _locked_position.account_address = account_address _locked_position.value = 5 db.add(_locked_position) @@ -230,14 +234,18 @@ def test_normal_3_1(self, mock_IbetStraightBondContract_get, mock_IbetShareContr # prepare data: Locked Position 2 _locked_position = IDXLockedPosition() _locked_position.token_address = token_address_2 - _locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + _locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) _locked_position.account_address = account_address _locked_position.value = 10 db.add(_locked_position) _locked_position = IDXLockedPosition() _locked_position.token_address = token_address_2 - _locked_position.lock_address = "0x1234567890123456789012345678900000000002" # lock address 2 + _locked_position.lock_address = ( + "0x1234567890123456789012345678900000000002" # lock address 2 + ) _locked_position.account_address = account_address _locked_position.value = 10 db.add(_locked_position) @@ -264,14 +272,18 @@ def test_normal_3_1(self, mock_IbetStraightBondContract_get, mock_IbetShareContr # prepare data: Locked Position 3 _locked_position = IDXLockedPosition() _locked_position.token_address = token_address_3 - _locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + _locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) _locked_position.account_address = account_address _locked_position.value = 15 db.add(_locked_position) _locked_position = IDXLockedPosition() _locked_position.token_address = token_address_3 - _locked_position.lock_address = "0x1234567890123456789012345678900000000002" # lock address 2 + _locked_position.lock_address = ( + "0x1234567890123456789012345678900000000002" # lock address 2 + ) _locked_position.account_address = account_address _locked_position.value = 15 db.add(_locked_position) @@ -310,7 +322,7 @@ def test_normal_3_1(self, mock_IbetStraightBondContract_get, mock_IbetShareContr "exchange_balance": 11, "exchange_commitment": 12, "pending_transfer": 13, - "locked": 10 + "locked": 10, }, { "issuer_address": issuer_address, @@ -321,7 +333,7 @@ def test_normal_3_1(self, mock_IbetStraightBondContract_get, mock_IbetShareContr "exchange_balance": 21, "exchange_commitment": 22, "pending_transfer": 23, - "locked": 20 + "locked": 20, }, { "issuer_address": issuer_address, @@ -332,16 +344,18 @@ def test_normal_3_1(self, mock_IbetStraightBondContract_get, mock_IbetShareContr "exchange_balance": 31, "exchange_commitment": 32, "pending_transfer": 33, - "locked": 30 + "locked": 30, }, - ] + ], } # # multi record (Including former holder) @mock.patch("app.model.blockchain.token.IbetShareContract.get") @mock.patch("app.model.blockchain.token.IbetStraightBondContract.get") - def test_normal_3_2(self, mock_IbetStraightBondContract_get, mock_IbetShareContract_get, client, db): + def test_normal_3_2( + self, mock_IbetStraightBondContract_get, mock_IbetShareContract_get, client, db + ): issuer_address = "0x1234567890123456789012345678900000000100" account_address = "0x1234567890123456789012345678900000000000" token_address_1 = "0x1234567890123456789012345678900000000010" @@ -389,7 +403,9 @@ def test_normal_3_2(self, mock_IbetStraightBondContract_get, mock_IbetShareContr # prepare data: Locked Position 2 _locked_position = IDXLockedPosition() _locked_position.token_address = token_address_2 - _locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + _locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) _locked_position.account_address = account_address _locked_position.value = 0 db.add(_locked_position) @@ -416,7 +432,9 @@ def test_normal_3_2(self, mock_IbetStraightBondContract_get, mock_IbetShareContr # prepare data: Locked Position 3 _locked_position = IDXLockedPosition() _locked_position.token_address = token_address_3 - _locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + _locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) _locked_position.account_address = account_address _locked_position.value = 0 db.add(_locked_position) @@ -455,7 +473,7 @@ def test_normal_3_2(self, mock_IbetStraightBondContract_get, mock_IbetShareContr "exchange_balance": 11, "exchange_commitment": 12, "pending_transfer": 13, - "locked": 0 + "locked": 0, }, { "issuer_address": issuer_address, @@ -466,16 +484,18 @@ def test_normal_3_2(self, mock_IbetStraightBondContract_get, mock_IbetShareContr "exchange_balance": 0, "exchange_commitment": 22, "pending_transfer": 23, - "locked": 0 - } - ] + "locked": 0, + }, + ], } # # specify header @mock.patch("app.model.blockchain.token.IbetShareContract.get") @mock.patch("app.model.blockchain.token.IbetStraightBondContract.get") - def test_normal_4(self, mock_IbetStraightBondContract_get, mock_IbetShareContract_get, client, db): + def test_normal_4( + self, mock_IbetStraightBondContract_get, mock_IbetShareContract_get, client, db + ): account_address = "0x1234567890123456789012345678900000000000" # prepare data: Token @@ -500,7 +520,9 @@ def test_normal_4(self, mock_IbetStraightBondContract_get, mock_IbetShareContrac # prepare data: Token _token = Token() _token.token_address = "0x1234567890123456789012345678900000000011" - _token.issuer_address = "0x1234567890123456789012345678900000000101" # not target + _token.issuer_address = ( + "0x1234567890123456789012345678900000000101" # not target + ) _token.type = TokenType.IBET_STRAIGHT_BOND.value _token.tx_hash = "" _token.abi = "" @@ -548,7 +570,7 @@ def test_normal_4(self, mock_IbetStraightBondContract_get, mock_IbetShareContrac # request target api resp = client.get( self.base_url.format(account_address=account_address), - headers={"issuer-address": "0x1234567890123456789012345678900000000100"} + headers={"issuer-address": "0x1234567890123456789012345678900000000100"}, ) # assertion @@ -570,7 +592,7 @@ def test_normal_4(self, mock_IbetStraightBondContract_get, mock_IbetShareContrac "exchange_balance": 11, "exchange_commitment": 12, "pending_transfer": 13, - "locked": 0 + "locked": 0, }, { "issuer_address": "0x1234567890123456789012345678900000000100", @@ -581,9 +603,9 @@ def test_normal_4(self, mock_IbetStraightBondContract_get, mock_IbetShareContrac "exchange_balance": 31, "exchange_commitment": 32, "pending_transfer": 33, - "locked": 0 + "locked": 0, }, - ] + ], } # @@ -661,7 +683,7 @@ def test_normal_5_1(self, mock_IbetStraightBondContract_get, client, db): # request target api resp = client.get( self.base_url.format(account_address=account_address), - params={"token_type": TokenType.IBET_STRAIGHT_BOND.value} + params={"token_type": TokenType.IBET_STRAIGHT_BOND.value}, ) # assertion @@ -683,7 +705,7 @@ def test_normal_5_1(self, mock_IbetStraightBondContract_get, client, db): "exchange_balance": 11, "exchange_commitment": 12, "pending_transfer": 13, - "locked": 0 + "locked": 0, }, { "issuer_address": "0x1234567890123456789012345678900000000101", @@ -694,9 +716,9 @@ def test_normal_5_1(self, mock_IbetStraightBondContract_get, client, db): "exchange_balance": 21, "exchange_commitment": 22, "pending_transfer": 23, - "locked": 0 + "locked": 0, }, - ] + ], } # @@ -772,7 +794,7 @@ def test_normal_5_2(self, mock_IbetShareContract_get, client, db): # request target api resp = client.get( self.base_url.format(account_address=account_address), - params={"token_type": TokenType.IBET_SHARE.value} + params={"token_type": TokenType.IBET_SHARE.value}, ) # assertion @@ -794,9 +816,9 @@ def test_normal_5_2(self, mock_IbetShareContract_get, client, db): "exchange_balance": 31, "exchange_commitment": 32, "pending_transfer": 33, - "locked": 0 + "locked": 0, }, - ] + ], } # @@ -804,7 +826,9 @@ def test_normal_5_2(self, mock_IbetShareContract_get, client, db): # including_former_position @mock.patch("app.model.blockchain.token.IbetShareContract.get") @mock.patch("app.model.blockchain.token.IbetStraightBondContract.get") - def test_normal_5_3(self, mock_IbetStraightBondContract_get, mock_IbetShareContract_get, client, db): + def test_normal_5_3( + self, mock_IbetStraightBondContract_get, mock_IbetShareContract_get, client, db + ): account_address = "0x1234567890123456789012345678900000000000" # prepare data: Token @@ -898,9 +922,7 @@ def test_normal_5_3(self, mock_IbetStraightBondContract_get, mock_IbetShareContr # request target api resp = client.get( self.base_url.format(account_address=account_address), - params={ - "include_former_position": "true" - } + params={"include_former_position": "true"}, ) # assertion @@ -922,7 +944,7 @@ def test_normal_5_3(self, mock_IbetStraightBondContract_get, mock_IbetShareContr "exchange_balance": 11, "exchange_commitment": 12, "pending_transfer": 13, - "locked": 0 + "locked": 0, }, { "issuer_address": "0x1234567890123456789012345678900000000101", @@ -933,7 +955,7 @@ def test_normal_5_3(self, mock_IbetStraightBondContract_get, mock_IbetShareContr "exchange_balance": 0, "exchange_commitment": 0, "pending_transfer": 0, - "locked": 0 + "locked": 0, }, { "issuer_address": "0x1234567890123456789012345678900000000100", @@ -944,7 +966,7 @@ def test_normal_5_3(self, mock_IbetStraightBondContract_get, mock_IbetShareContr "exchange_balance": 20, "exchange_commitment": 10, "pending_transfer": 1, - "locked": 0 + "locked": 0, }, { "issuer_address": "0x1234567890123456789012345678900000000101", @@ -955,16 +977,18 @@ def test_normal_5_3(self, mock_IbetStraightBondContract_get, mock_IbetShareContr "exchange_balance": 0, "exchange_commitment": 0, "pending_transfer": 0, - "locked": 0 - } - ] + "locked": 0, + }, + ], } # # Pagination @mock.patch("app.model.blockchain.token.IbetShareContract.get") @mock.patch("app.model.blockchain.token.IbetStraightBondContract.get") - def test_normal_6(self, mock_IbetStraightBondContract_get, mock_IbetShareContract_get, client, db): + def test_normal_6( + self, mock_IbetStraightBondContract_get, mock_IbetShareContract_get, client, db + ): account_address = "0x1234567890123456789012345678900000000000" # prepare data: Token @@ -1057,7 +1081,7 @@ def test_normal_6(self, mock_IbetStraightBondContract_get, mock_IbetShareContrac params={ "offset": 1, "limit": 2, - } + }, ) # assertion @@ -1079,7 +1103,7 @@ def test_normal_6(self, mock_IbetStraightBondContract_get, mock_IbetShareContrac "exchange_balance": 21, "exchange_commitment": 22, "pending_transfer": 23, - "locked": 0 + "locked": 0, }, { "issuer_address": "0x1234567890123456789012345678900000000100", @@ -1090,9 +1114,9 @@ def test_normal_6(self, mock_IbetStraightBondContract_get, mock_IbetShareContrac "exchange_balance": 31, "exchange_commitment": 32, "pending_transfer": 33, - "locked": 0 + "locked": 0, }, - ] + ], } ########################################################################### @@ -1110,23 +1134,20 @@ def test_error_1_1(self, client, db): self.base_url.format(account_address=account_address), headers={ "issuer-address": "test", - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -1142,32 +1163,29 @@ def test_error_1_2(self, client, db): "token_type": "test", "offset": "test", "limit": "test", - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["query", "token_type"], "ctx": {"enum_values": ["IbetStraightBond", "IbetShare"]}, "msg": "value is not a valid enumeration member; permitted: 'IbetStraightBond', 'IbetShare'", - "type": "type_error.enum" + "type": "type_error.enum", }, { "loc": ["query", "offset"], "msg": "value is not a valid integer", - "type": "type_error.integer" + "type": "type_error.integer", }, { "loc": ["query", "limit"], "msg": "value is not a valid integer", - "type": "type_error.integer" + "type": "type_error.integer", }, - ] + ], } diff --git a/tests/test_app_routers_positions_{account_address}_forceunlock_POST.py b/tests/test_app_routers_positions_{account_address}_forceunlock_POST.py index f83d8322..177f83d3 100644 --- a/tests/test_app_routers_positions_{account_address}_forceunlock_POST.py +++ b/tests/test_app_routers_positions_{account_address}_forceunlock_POST.py @@ -20,22 +20,13 @@ from unittest import mock from unittest.mock import ANY, MagicMock -from app.model.db import ( - Account, - AuthToken, - Token, - TokenType -) +from app.exceptions import ContractRevertError, SendTransactionError +from app.model.db import Account, AuthToken, Token, TokenType from app.utils.e2ee_utils import E2EEUtils -from app.exceptions import ( - SendTransactionError, - ContractRevertError -) from tests.account_config import config_eth_account class TestAppRoutersForceUnlockPOST: - # target API endpoint test_url = "/positions/{account_address}/force_unlock" @@ -80,15 +71,15 @@ def test_normal_1(self, IbetSecurityTokenInterface_mock, client, db): "lock_address": _lock_address, "account_address": _admin_address, "recipient_address": _recipient_address, - "value": 10 + "value": 10, } resp = client.post( self.test_url, json=req_param, headers={ "issuer-address": _admin_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion @@ -98,10 +89,10 @@ def test_normal_1(self, IbetSecurityTokenInterface_mock, client, db): "account_address": _admin_address, "recipient_address": _recipient_address, "value": 10, - "data": "" + "data": "", }, tx_from=_admin_address, - private_key=ANY + private_key=ANY, ) assert resp.status_code == 200 @@ -150,15 +141,12 @@ def test_normal_2(self, IbetSecurityTokenInterface_mock, client, db): "lock_address": _lock_address, "account_address": _admin_address, "recipient_address": _recipient_address, - "value": 10 + "value": 10, } resp = client.post( self.test_url, json=req_param, - headers={ - "issuer-address": _admin_address, - "auth-token": "test_auth_token" - } + headers={"issuer-address": _admin_address, "auth-token": "test_auth_token"}, ) # assertion @@ -168,10 +156,10 @@ def test_normal_2(self, IbetSecurityTokenInterface_mock, client, db): "account_address": _admin_address, "recipient_address": _recipient_address, "value": 10, - "data": "" + "data": "", }, tx_from=_admin_address, - private_key=ANY + private_key=ANY, ) assert resp.status_code == 200 @@ -188,47 +176,40 @@ def test_error_1(self, client, db): # request target API req_param = {} resp = client.post( - self.test_url, - json=req_param, - headers={ - "issuer-address": "issuer-address" - } + self.test_url, json=req_param, headers={"issuer-address": "issuer-address"} ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['body', 'token_address'], - 'msg': 'field required', - 'type': 'value_error.missing' + "loc": ["body", "token_address"], + "msg": "field required", + "type": "value_error.missing", }, { - 'loc': ['body', 'lock_address'], - 'msg': 'field required', - 'type': 'value_error.missing' + "loc": ["body", "lock_address"], + "msg": "field required", + "type": "value_error.missing", }, { - 'loc': ['body', 'account_address'], - 'msg': 'field required', - 'type': 'value_error.missing' + "loc": ["body", "account_address"], + "msg": "field required", + "type": "value_error.missing", }, { - 'loc': ['body', 'recipient_address'], - 'msg': 'field required', - 'type': 'value_error.missing' + "loc": ["body", "recipient_address"], + "msg": "field required", + "type": "value_error.missing", }, { - 'loc': ['body', 'value'], - 'msg': 'field required', - 'type': 'value_error.missing' - } - ] + "loc": ["body", "value"], + "msg": "field required", + "type": "value_error.missing", + }, + ], } # @@ -239,7 +220,9 @@ def test_error_1_2(self, client, db): _token_address = "0xd9F55747DE740297ff1eEe537aBE0f8d73B7D78" # short address _lock_address = "0xd9F55747DE740297ff1eEe537aBE0f8d73B7D78" # short address _admin_address = "0xd9F55747DE740297ff1eEe537aBE0f8d73B7D78" # short address - _recipient_address = "0xd9F55747DE740297ff1eEe537aBE0f8d73B7D78" # short address + _recipient_address = ( + "0xd9F55747DE740297ff1eEe537aBE0f8d73B7D78" # short address + ) # request target API req_param = { @@ -247,51 +230,44 @@ def test_error_1_2(self, client, db): "lock_address": _lock_address, "account_address": _admin_address, "recipient_address": _recipient_address, - "value": 0 + "value": 0, } resp = client.post( - self.test_url, - json=req_param, - headers={ - "issuer-address": "issuer-address" - } + self.test_url, json=req_param, headers={"issuer-address": "issuer-address"} ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['body', 'token_address'], - 'msg': 'token_address is not a valid address', - 'type': 'value_error' + "loc": ["body", "token_address"], + "msg": "token_address is not a valid address", + "type": "value_error", }, { - 'loc': ['body', 'lock_address'], - 'msg': 'lock_address is not a valid address', - 'type': 'value_error' + "loc": ["body", "lock_address"], + "msg": "lock_address is not a valid address", + "type": "value_error", }, { - 'loc': ['body', 'account_address'], - 'msg': 'account_address is not a valid address', - 'type': 'value_error' + "loc": ["body", "account_address"], + "msg": "account_address is not a valid address", + "type": "value_error", }, { - 'loc': ['body', 'recipient_address'], - 'msg': 'recipient_address is not a valid address', - 'type': 'value_error' + "loc": ["body", "recipient_address"], + "msg": "recipient_address is not a valid address", + "type": "value_error", }, { - 'loc': ['body', 'value'], - 'msg': 'ensure this value is greater than 0', - 'type': 'value_error.number.not_gt', - 'ctx': {'limit_value': 0} - } - ] + "loc": ["body", "value"], + "msg": "ensure this value is greater than 0", + "type": "value_error.number.not_gt", + "ctx": {"limit_value": 0}, + }, + ], } # @@ -299,29 +275,24 @@ def test_error_1_2(self, client, db): # Header and body are required def test_error_1_3(self, client, db): # request target API - resp = client.post( - self.test_url - ) + resp = client.post(self.test_url) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, { "loc": ["body"], "msg": "field required", - "type": "value_error.missing" - } - ] + "type": "value_error.missing", + }, + ], } # @@ -343,30 +314,25 @@ def test_error_1_4(self, client, db): "lock_address": _lock_address, "account_address": _admin_address, "recipient_address": _recipient_address, - "value": 10 + "value": 10, } resp = client.post( self.test_url, json=req_param, - headers={ - "issuer-address": "issuer-address" # dummy address - } + headers={"issuer-address": "issuer-address"}, # dummy address ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -388,29 +354,28 @@ def test_error_1_5(self, client, db): "lock_address": _lock_address, "account_address": _admin_address, "recipient_address": _recipient_address, - "value": 10 + "value": 10, } resp = client.post( self.test_url, json=req_param, headers={ "issuer-address": _admin_address, - "eoa-password": "password" # not encrypted - } + "eoa-password": "password", # not encrypted + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, - "detail": [{ - "loc": ["header", "eoa-password"], - "msg": "eoa-password is not a Base64-encoded encrypted data", - "type": "value_error" - }] + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ + { + "loc": ["header", "eoa-password"], + "msg": "eoa-password is not a Base64-encoded encrypted data", + "type": "value_error", + } + ], } # @@ -432,25 +397,22 @@ def test_error_2_1(self, client, db): "lock_address": _lock_address, "account_address": _admin_address, "recipient_address": _recipient_address, - "value": 10 + "value": 10, } resp = client.post( self.test_url, json=req_param, headers={ "issuer-address": _admin_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -479,25 +441,22 @@ def test_error_2_2(self, client, db): "lock_address": _lock_address, "account_address": _admin_address, "recipient_address": _recipient_address, - "value": 10 + "value": 10, } resp = client.post( self.test_url, json=req_param, headers={ "issuer-address": _admin_address, - "eoa-password": E2EEUtils.encrypt("password_test") - } + "eoa-password": E2EEUtils.encrypt("password_test"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -526,25 +485,22 @@ def test_error_3_1(self, client, db): "lock_address": _lock_address, "account_address": _admin_address, "recipient_address": _recipient_address, - "value": 10 + "value": 10, } resp = client.post( self.test_url, json=req_param, headers={ "issuer-address": _admin_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "token not found", } # @@ -582,31 +538,30 @@ def test_error_3_2(self, client, db): "lock_address": _lock_address, "account_address": _admin_address, "recipient_address": _recipient_address, - "value": 10 + "value": 10, } resp = client.post( self.test_url, json=req_param, headers={ "issuer-address": _admin_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } # # ContractRevertError - @mock.patch("app.model.blockchain.token.IbetSecurityTokenInterface.force_unlock", - MagicMock(side_effect=ContractRevertError(code_msg="111201"))) + @mock.patch( + "app.model.blockchain.token.IbetSecurityTokenInterface.force_unlock", + MagicMock(side_effect=ContractRevertError(code_msg="111201")), + ) def test_error_4(self, client, db): _admin_account = config_eth_account("user1") _admin_address = _admin_account["address"] @@ -638,31 +593,30 @@ def test_error_4(self, client, db): "lock_address": _lock_address, "account_address": _admin_address, "recipient_address": _recipient_address, - "value": 10 + "value": 10, } resp = client.post( self.test_url, json=req_param, headers={ "issuer-address": _admin_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - 'meta': { - 'code': 111201, - 'title': 'ContractRevertError' - }, - 'detail': 'Unlock amount is greater than locked amount.' + "meta": {"code": 111201, "title": "ContractRevertError"}, + "detail": "Unlock amount is greater than locked amount.", } # # SendTransactionError - @mock.patch("app.model.blockchain.token.IbetSecurityTokenInterface.force_unlock", - MagicMock(side_effect=SendTransactionError())) + @mock.patch( + "app.model.blockchain.token.IbetSecurityTokenInterface.force_unlock", + MagicMock(side_effect=SendTransactionError()), + ) def test_error_5(self, client, db): _admin_account = config_eth_account("user1") _admin_address = _admin_account["address"] @@ -694,23 +648,20 @@ def test_error_5(self, client, db): "lock_address": _lock_address, "account_address": _admin_address, "recipient_address": _recipient_address, - "value": 10 + "value": 10, } resp = client.post( self.test_url, json=req_param, headers={ "issuer-address": _admin_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 2, - "title": "SendTransactionError" - }, - "detail": "failed to send transaction" + "meta": {"code": 2, "title": "SendTransactionError"}, + "detail": "failed to send transaction", } diff --git a/tests/test_app_routers_positions_{account_address}_lock_GET.py b/tests/test_app_routers_positions_{account_address}_lock_GET.py index c5a5db33..1f9fed7a 100644 --- a/tests/test_app_routers_positions_{account_address}_lock_GET.py +++ b/tests/test_app_routers_positions_{account_address}_lock_GET.py @@ -18,19 +18,11 @@ """ from unittest import mock -from app.model.db import ( - IDXLockedPosition, - Token, - TokenType -) -from app.model.blockchain import ( - IbetStraightBondContract, - IbetShareContract -) +from app.model.blockchain import IbetShareContract, IbetStraightBondContract +from app.model.db import IDXLockedPosition, Token, TokenType class TestAppRoutersLockedPositions: - # target API endpoint base_url = "/positions/{account_address}/lock" @@ -66,7 +58,7 @@ def test_normal_1(self, client, db): "limit": None, "total": 0, }, - "locked_positions": [] + "locked_positions": [], } # Normal_2_1 @@ -153,7 +145,7 @@ def test_normal_2_1(self, mock_IbetStraightBondContract_get, client, db): "token_type": TokenType.IBET_STRAIGHT_BOND.value, "token_name": "test_bond_1", "lock_address": lock_address_1, - "locked": 5 + "locked": 5, }, { "issuer_address": issuer_address, @@ -161,9 +153,9 @@ def test_normal_2_1(self, mock_IbetStraightBondContract_get, client, db): "token_type": TokenType.IBET_STRAIGHT_BOND.value, "token_name": "test_bond_2", "lock_address": lock_address_2, - "locked": 5 + "locked": 5, }, - ] + ], } # Normal_2_2 @@ -250,7 +242,7 @@ def test_normal_2_2(self, mock_IbetShareContract_get, client, db): "token_type": TokenType.IBET_SHARE.value, "token_name": "test_share_1", "lock_address": lock_address_1, - "locked": 5 + "locked": 5, }, { "issuer_address": issuer_address, @@ -258,9 +250,9 @@ def test_normal_2_2(self, mock_IbetShareContract_get, client, db): "token_type": TokenType.IBET_SHARE.value, "token_name": "test_share_2", "lock_address": lock_address_2, - "locked": 5 + "locked": 5, }, - ] + ], } # Normal_3_1 @@ -305,7 +297,7 @@ def test_normal_3_1(self, client, db): "limit": None, "total": 0, }, - "locked_positions": [] + "locked_positions": [], } # Normal_3_2 @@ -384,9 +376,9 @@ def test_normal_3_2(self, mock_IbetStraightBondContract_get, client, db): "token_type": TokenType.IBET_STRAIGHT_BOND.value, "token_name": "test_bond_2", "lock_address": lock_address_2, - "locked": 5 + "locked": 5, }, - ] + ], } # Normal_4 @@ -448,7 +440,7 @@ def test_normal_4(self, mock_IbetStraightBondContract_get, client, db): # request target api resp = client.get( self.base_url.format(account_address=account_address), - headers={"issuer-address": issuer_address} + headers={"issuer-address": issuer_address}, ) # assertion @@ -467,9 +459,9 @@ def test_normal_4(self, mock_IbetStraightBondContract_get, client, db): "token_type": TokenType.IBET_STRAIGHT_BOND.value, "token_name": "test_bond_1", "lock_address": lock_address_1, - "locked": 5 + "locked": 5, }, - ] + ], } # Normal_5 @@ -528,7 +520,7 @@ def test_normal_5(self, mock_IbetStraightBondContract_get, client, db): # request target api resp = client.get( self.base_url.format(account_address=account_address), - params={"token_type": TokenType.IBET_STRAIGHT_BOND.value} + params={"token_type": TokenType.IBET_STRAIGHT_BOND.value}, ) # assertion @@ -547,9 +539,9 @@ def test_normal_5(self, mock_IbetStraightBondContract_get, client, db): "token_type": TokenType.IBET_STRAIGHT_BOND.value, "token_name": "test_bond_1", "lock_address": lock_address_2, - "locked": 5 + "locked": 5, }, - ] + ], } # Normal_6 @@ -607,10 +599,7 @@ def test_normal_6(self, mock_IbetStraightBondContract_get, client, db): # request target api resp = client.get( self.base_url.format(account_address=account_address), - params={ - "offset": 1, - "limit": 1 - } + params={"offset": 1, "limit": 1}, ) # assertion @@ -629,9 +618,9 @@ def test_normal_6(self, mock_IbetStraightBondContract_get, client, db): "token_type": TokenType.IBET_STRAIGHT_BOND.value, "token_name": "test_bond_1", "lock_address": lock_address_2, - "locked": 5 + "locked": 5, }, - ] + ], } ########################################################################### @@ -649,23 +638,20 @@ def test_error_1_1(self, client, db): self.base_url.format(account_address=account_address), headers={ "issuer-address": "test", - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # Error_1_2 @@ -681,32 +667,29 @@ def test_error_1_2(self, client, db): "token_type": "test", "offset": "test", "limit": "test", - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["query", "token_type"], "ctx": {"enum_values": ["IbetStraightBond", "IbetShare"]}, "msg": "value is not a valid enumeration member; permitted: 'IbetStraightBond', 'IbetShare'", - "type": "type_error.enum" + "type": "type_error.enum", }, { "loc": ["query", "offset"], "msg": "value is not a valid integer", - "type": "type_error.integer" + "type": "type_error.integer", }, { "loc": ["query", "limit"], "msg": "value is not a valid integer", - "type": "type_error.integer" + "type": "type_error.integer", }, - ] + ], } diff --git a/tests/test_app_routers_positions_{account_address}_lock_events_GET.py b/tests/test_app_routers_positions_{account_address}_lock_events_GET.py index 4bbf286c..5a874ce5 100644 --- a/tests/test_app_routers_positions_{account_address}_lock_events_GET.py +++ b/tests/test_app_routers_positions_{account_address}_lock_events_GET.py @@ -20,20 +20,11 @@ from unittest import mock from unittest.mock import ANY -from app.model.db import ( - IDXLock, - IDXUnlock, - Token, - TokenType -) -from app.model.blockchain import ( - IbetStraightBondContract, - IbetShareContract -) +from app.model.blockchain import IbetShareContract, IbetStraightBondContract +from app.model.db import IDXLock, IDXUnlock, Token, TokenType class TestAppRoutersLockEvents: - # target API endpoint base_url = "/positions/{account_address}/lock/events" @@ -69,7 +60,7 @@ def test_normal_1(self, client, db): "limit": None, "total": 0, }, - "events": [] + "events": [], } # Normal_2_1 @@ -134,42 +125,37 @@ def test_normal_2_1(self, mock_IbetStraightBondContract_get, client, db): # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 2, - 'offset': None, - 'limit': None, - 'total': 2 - }, - 'events': [ + "result_set": {"count": 2, "offset": None, "limit": None, "total": 2}, + "events": [ { - 'category': 'Unlock', - 'transaction_hash': 'tx_hash_2', - 'issuer_address': issuer_address, - 'token_address': token_address_1, - 'token_type': TokenType.IBET_STRAIGHT_BOND.value, - 'token_name': token_name_1, - 'lock_address': lock_address_1, - 'account_address': account_address, - 'recipient_address': other_account_address, - 'value': 1, - 'data': {'message': 'unlocked_1'}, - 'block_timestamp': ANY + "category": "Unlock", + "transaction_hash": "tx_hash_2", + "issuer_address": issuer_address, + "token_address": token_address_1, + "token_type": TokenType.IBET_STRAIGHT_BOND.value, + "token_name": token_name_1, + "lock_address": lock_address_1, + "account_address": account_address, + "recipient_address": other_account_address, + "value": 1, + "data": {"message": "unlocked_1"}, + "block_timestamp": ANY, }, { - 'category': 'Lock', - 'transaction_hash': 'tx_hash_1', - 'issuer_address': issuer_address, - 'token_address': token_address_1, - 'token_type': TokenType.IBET_STRAIGHT_BOND.value, - 'token_name': token_name_1, - 'lock_address': lock_address_1, - 'account_address': account_address, - 'recipient_address': None, - 'value': 1, - 'data': {'message': 'locked_1'}, - 'block_timestamp': ANY - } - ] + "category": "Lock", + "transaction_hash": "tx_hash_1", + "issuer_address": issuer_address, + "token_address": token_address_1, + "token_type": TokenType.IBET_STRAIGHT_BOND.value, + "token_name": token_name_1, + "lock_address": lock_address_1, + "account_address": account_address, + "recipient_address": None, + "value": 1, + "data": {"message": "locked_1"}, + "block_timestamp": ANY, + }, + ], } # Normal_2_2 @@ -234,42 +220,37 @@ def test_normal_2_2(self, mock_IbetShareContract_get, client, db): # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 2, - 'offset': None, - 'limit': None, - 'total': 2 - }, - 'events': [ + "result_set": {"count": 2, "offset": None, "limit": None, "total": 2}, + "events": [ { - 'category': 'Unlock', - 'transaction_hash': 'tx_hash_2', - 'issuer_address': issuer_address, - 'token_address': token_address_1, - 'token_type': TokenType.IBET_SHARE.value, - 'token_name': token_name_1, - 'lock_address': lock_address_1, - 'account_address': account_address, - 'recipient_address': other_account_address, - 'value': 1, - 'data': {'message': 'unlocked_1'}, - 'block_timestamp': ANY + "category": "Unlock", + "transaction_hash": "tx_hash_2", + "issuer_address": issuer_address, + "token_address": token_address_1, + "token_type": TokenType.IBET_SHARE.value, + "token_name": token_name_1, + "lock_address": lock_address_1, + "account_address": account_address, + "recipient_address": other_account_address, + "value": 1, + "data": {"message": "unlocked_1"}, + "block_timestamp": ANY, }, { - 'category': 'Lock', - 'transaction_hash': 'tx_hash_1', - 'issuer_address': issuer_address, - 'token_address': token_address_1, - 'token_type': TokenType.IBET_SHARE.value, - 'token_name': token_name_1, - 'lock_address': lock_address_1, - 'account_address': account_address, - 'recipient_address': None, - 'value': 1, - 'data': {'message': 'locked_1'}, - 'block_timestamp': ANY - } - ] + "category": "Lock", + "transaction_hash": "tx_hash_1", + "issuer_address": issuer_address, + "token_address": token_address_1, + "token_type": TokenType.IBET_SHARE.value, + "token_name": token_name_1, + "lock_address": lock_address_1, + "account_address": account_address, + "recipient_address": None, + "value": 1, + "data": {"message": "locked_1"}, + "block_timestamp": ANY, + }, + ], } # Normal_3_1 @@ -335,13 +316,8 @@ def test_normal_3_1(self, mock_IbetStraightBondContract_get, client, db): # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 0, - 'offset': None, - 'limit': None, - 'total': 0 - }, - 'events': [] + "result_set": {"count": 0, "offset": None, "limit": None, "total": 0}, + "events": [], } # Normal_3_2 @@ -408,13 +384,8 @@ def test_normal_3_2(self, mock_IbetStraightBondContract_get, client, db): # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 0, - 'offset': None, - 'limit': None, - 'total': 0 - }, - 'events': [] + "result_set": {"count": 0, "offset": None, "limit": None, "total": 0}, + "events": [], } # Normal_4 @@ -507,48 +478,43 @@ def test_normal_4(self, mock_IbetStraightBondContract_get, client, db): # request target api resp = client.get( self.base_url.format(account_address=account_address), - headers={"issuer-address": issuer_address} + headers={"issuer-address": issuer_address}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 2, - 'offset': None, - 'limit': None, - 'total': 2 - }, - 'events': [ + "result_set": {"count": 2, "offset": None, "limit": None, "total": 2}, + "events": [ { - 'category': 'Unlock', - 'transaction_hash': 'tx_hash_2', - 'issuer_address': issuer_address, - 'token_address': token_address_1, - 'token_type': TokenType.IBET_STRAIGHT_BOND.value, - 'token_name': token_name_1, - 'lock_address': lock_address_1, - 'account_address': account_address, - 'recipient_address': other_account_address, - 'value': 1, - 'data': {'message': 'unlocked_1'}, - 'block_timestamp': ANY + "category": "Unlock", + "transaction_hash": "tx_hash_2", + "issuer_address": issuer_address, + "token_address": token_address_1, + "token_type": TokenType.IBET_STRAIGHT_BOND.value, + "token_name": token_name_1, + "lock_address": lock_address_1, + "account_address": account_address, + "recipient_address": other_account_address, + "value": 1, + "data": {"message": "unlocked_1"}, + "block_timestamp": ANY, }, { - 'category': 'Lock', - 'transaction_hash': 'tx_hash_1', - 'issuer_address': issuer_address, - 'token_address': token_address_1, - 'token_type': TokenType.IBET_STRAIGHT_BOND.value, - 'token_name': token_name_1, - 'lock_address': lock_address_1, - 'account_address': account_address, - 'recipient_address': None, - 'value': 1, - 'data': {'message': 'locked_1'}, - 'block_timestamp': ANY - } - ] + "category": "Lock", + "transaction_hash": "tx_hash_1", + "issuer_address": issuer_address, + "token_address": token_address_1, + "token_type": TokenType.IBET_STRAIGHT_BOND.value, + "token_name": token_name_1, + "lock_address": lock_address_1, + "account_address": account_address, + "recipient_address": None, + "value": 1, + "data": {"message": "locked_1"}, + "block_timestamp": ANY, + }, + ], } # Normal_5_1 @@ -608,34 +574,29 @@ def test_normal_5_1(self, mock_IbetStraightBondContract_get, client, db): # request target api resp = client.get( self.base_url.format(account_address=account_address), - params={"category": "Unlock"} + params={"category": "Unlock"}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 1, - 'offset': None, - 'limit': None, - 'total': 2 - }, - 'events': [ + "result_set": {"count": 1, "offset": None, "limit": None, "total": 2}, + "events": [ { - 'category': 'Unlock', - 'transaction_hash': 'tx_hash_2', - 'issuer_address': issuer_address, - 'token_address': token_address_1, - 'token_type': TokenType.IBET_STRAIGHT_BOND.value, - 'token_name': token_name_1, - 'lock_address': lock_address_1, - 'account_address': account_address, - 'recipient_address': other_account_address, - 'value': 1, - 'data': {'message': 'unlocked_1'}, - 'block_timestamp': ANY + "category": "Unlock", + "transaction_hash": "tx_hash_2", + "issuer_address": issuer_address, + "token_address": token_address_1, + "token_type": TokenType.IBET_STRAIGHT_BOND.value, + "token_name": token_name_1, + "lock_address": lock_address_1, + "account_address": account_address, + "recipient_address": other_account_address, + "value": 1, + "data": {"message": "unlocked_1"}, + "block_timestamp": ANY, } - ] + ], } # Normal_5_2 @@ -704,34 +665,29 @@ def test_normal_5_2(self, mock_IbetStraightBondContract_get, client, db): # request target api resp = client.get( self.base_url.format(account_address=account_address), - params={"token_address": token_address_1} + params={"token_address": token_address_1}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 1, - 'offset': None, - 'limit': None, - 'total': 2 - }, - 'events': [ + "result_set": {"count": 1, "offset": None, "limit": None, "total": 2}, + "events": [ { - 'category': 'Lock', - 'transaction_hash': 'tx_hash_1', - 'issuer_address': issuer_address, - 'token_address': token_address_1, - 'token_type': TokenType.IBET_STRAIGHT_BOND.value, - 'token_name': token_name_1, - 'lock_address': lock_address_1, - 'account_address': account_address, - 'recipient_address': None, - 'value': 1, - 'data': {'message': 'locked_1'}, - 'block_timestamp': ANY + "category": "Lock", + "transaction_hash": "tx_hash_1", + "issuer_address": issuer_address, + "token_address": token_address_1, + "token_type": TokenType.IBET_STRAIGHT_BOND.value, + "token_name": token_name_1, + "lock_address": lock_address_1, + "account_address": account_address, + "recipient_address": None, + "value": 1, + "data": {"message": "locked_1"}, + "block_timestamp": ANY, } - ] + ], } # Normal_5_3 @@ -800,34 +756,29 @@ def test_normal_5_3(self, mock_IbetStraightBondContract_get, client, db): # request target api resp = client.get( self.base_url.format(account_address=account_address), - params={"token_type": TokenType.IBET_STRAIGHT_BOND.value} + params={"token_type": TokenType.IBET_STRAIGHT_BOND.value}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 1, - 'offset': None, - 'limit': None, - 'total': 2 - }, - 'events': [ + "result_set": {"count": 1, "offset": None, "limit": None, "total": 2}, + "events": [ { - 'category': 'Lock', - 'transaction_hash': 'tx_hash_1', - 'issuer_address': issuer_address, - 'token_address': token_address_1, - 'token_type': TokenType.IBET_STRAIGHT_BOND.value, - 'token_name': token_name_1, - 'lock_address': lock_address_1, - 'account_address': account_address, - 'recipient_address': None, - 'value': 1, - 'data': {'message': 'locked_1'}, - 'block_timestamp': ANY + "category": "Lock", + "transaction_hash": "tx_hash_1", + "issuer_address": issuer_address, + "token_address": token_address_1, + "token_type": TokenType.IBET_STRAIGHT_BOND.value, + "token_name": token_name_1, + "lock_address": lock_address_1, + "account_address": account_address, + "recipient_address": None, + "value": 1, + "data": {"message": "locked_1"}, + "block_timestamp": ANY, } - ] + ], } # Normal_5_4 @@ -886,34 +837,29 @@ def test_normal_5_4(self, mock_IbetStraightBondContract_get, client, db): # request target api resp = client.get( self.base_url.format(account_address=account_address), - params={"lock_address": lock_address_1} + params={"lock_address": lock_address_1}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 1, - 'offset': None, - 'limit': None, - 'total': 2 - }, - 'events': [ + "result_set": {"count": 1, "offset": None, "limit": None, "total": 2}, + "events": [ { - 'category': 'Lock', - 'transaction_hash': 'tx_hash_1', - 'issuer_address': issuer_address, - 'token_address': token_address_1, - 'token_type': TokenType.IBET_STRAIGHT_BOND.value, - 'token_name': token_name_1, - 'lock_address': lock_address_1, - 'account_address': account_address, - 'recipient_address': None, - 'value': 1, - 'data': {'message': 'locked_1'}, - 'block_timestamp': ANY + "category": "Lock", + "transaction_hash": "tx_hash_1", + "issuer_address": issuer_address, + "token_address": token_address_1, + "token_type": TokenType.IBET_STRAIGHT_BOND.value, + "token_name": token_name_1, + "lock_address": lock_address_1, + "account_address": account_address, + "recipient_address": None, + "value": 1, + "data": {"message": "locked_1"}, + "block_timestamp": ANY, } - ] + ], } # Normal_5_5 @@ -975,34 +921,29 @@ def test_normal_5_5(self, mock_IbetStraightBondContract_get, client, db): # request target api resp = client.get( self.base_url.format(account_address=account_address), - params={"recipient_address": other_account_address_1} + params={"recipient_address": other_account_address_1}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 1, - 'offset': None, - 'limit': None, - 'total': 2 - }, - 'events': [ + "result_set": {"count": 1, "offset": None, "limit": None, "total": 2}, + "events": [ { - 'category': 'Unlock', - 'transaction_hash': 'tx_hash_1', - 'issuer_address': issuer_address, - 'token_address': token_address_1, - 'token_type': TokenType.IBET_STRAIGHT_BOND.value, - 'token_name': token_name_1, - 'lock_address': lock_address_1, - 'account_address': account_address, - 'recipient_address': other_account_address_1, - 'value': 1, - 'data': {'message': 'unlocked_1'}, - 'block_timestamp': ANY + "category": "Unlock", + "transaction_hash": "tx_hash_1", + "issuer_address": issuer_address, + "token_address": token_address_1, + "token_type": TokenType.IBET_STRAIGHT_BOND.value, + "token_name": token_name_1, + "lock_address": lock_address_1, + "account_address": account_address, + "recipient_address": other_account_address_1, + "value": 1, + "data": {"message": "unlocked_1"}, + "block_timestamp": ANY, } - ] + ], } # Normal_6 @@ -1083,79 +1024,71 @@ def test_normal_6(self, mock_IbetStraightBondContract_get, client, db): # request target api resp = client.get( self.base_url.format(account_address=account_address), - params={ - "sort_item": "lock_address", - "sort_order": 0 - } + params={"sort_item": "lock_address", "sort_order": 0}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 4, - 'offset': None, - 'limit': None, - 'total': 4 - }, - 'events': [ + "result_set": {"count": 4, "offset": None, "limit": None, "total": 4}, + "events": [ { - 'category': 'Lock', - 'transaction_hash': 'tx_hash_3', - 'issuer_address': issuer_address, - 'token_address': token_address_1, - 'token_type': TokenType.IBET_STRAIGHT_BOND.value, - 'token_name': token_name_1, - 'lock_address': lock_address_1, - 'account_address': account_address, - 'recipient_address': None, - 'value': 1, - 'data': {'message': 'locked_3'}, - 'block_timestamp': ANY + "category": "Lock", + "transaction_hash": "tx_hash_3", + "issuer_address": issuer_address, + "token_address": token_address_1, + "token_type": TokenType.IBET_STRAIGHT_BOND.value, + "token_name": token_name_1, + "lock_address": lock_address_1, + "account_address": account_address, + "recipient_address": None, + "value": 1, + "data": {"message": "locked_3"}, + "block_timestamp": ANY, }, { - 'category': 'Lock', - 'transaction_hash': 'tx_hash_1', - 'issuer_address': issuer_address, - 'token_address': token_address_1, - 'token_type': TokenType.IBET_STRAIGHT_BOND.value, - 'token_name': token_name_1, - 'lock_address': lock_address_1, - 'account_address': account_address, - 'recipient_address': None, - 'value': 1, - 'data': {'message': 'locked_1'}, - 'block_timestamp': ANY + "category": "Lock", + "transaction_hash": "tx_hash_1", + "issuer_address": issuer_address, + "token_address": token_address_1, + "token_type": TokenType.IBET_STRAIGHT_BOND.value, + "token_name": token_name_1, + "lock_address": lock_address_1, + "account_address": account_address, + "recipient_address": None, + "value": 1, + "data": {"message": "locked_1"}, + "block_timestamp": ANY, }, { - 'category': 'Lock', - 'transaction_hash': 'tx_hash_4', - 'issuer_address': issuer_address, - 'token_address': token_address_1, - 'token_type': TokenType.IBET_STRAIGHT_BOND.value, - 'token_name': token_name_1, - 'lock_address': lock_address_2, - 'account_address': account_address, - 'recipient_address': None, - 'value': 1, - 'data': {'message': 'locked_4'}, - 'block_timestamp': ANY + "category": "Lock", + "transaction_hash": "tx_hash_4", + "issuer_address": issuer_address, + "token_address": token_address_1, + "token_type": TokenType.IBET_STRAIGHT_BOND.value, + "token_name": token_name_1, + "lock_address": lock_address_2, + "account_address": account_address, + "recipient_address": None, + "value": 1, + "data": {"message": "locked_4"}, + "block_timestamp": ANY, }, { - 'category': 'Lock', - 'transaction_hash': 'tx_hash_2', - 'issuer_address': issuer_address, - 'token_address': token_address_1, - 'token_type': TokenType.IBET_STRAIGHT_BOND.value, - 'token_name': token_name_1, - 'lock_address': lock_address_2, - 'account_address': account_address, - 'recipient_address': None, - 'value': 1, - 'data': {'message': 'locked_2'}, - 'block_timestamp': ANY - } - ] + "category": "Lock", + "transaction_hash": "tx_hash_2", + "issuer_address": issuer_address, + "token_address": token_address_1, + "token_type": TokenType.IBET_STRAIGHT_BOND.value, + "token_name": token_name_1, + "lock_address": lock_address_2, + "account_address": account_address, + "recipient_address": None, + "value": 1, + "data": {"message": "locked_2"}, + "block_timestamp": ANY, + }, + ], } # Normal_7 @@ -1224,37 +1157,29 @@ def test_normal_7(self, mock_IbetStraightBondContract_get, client, db): # request target api resp = client.get( self.base_url.format(account_address=account_address), - params={ - "offset": 1, - "limit": 1 - } + params={"offset": 1, "limit": 1}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 3, - 'offset': 1, - 'limit': 1, - 'total': 3 - }, - 'events': [ + "result_set": {"count": 3, "offset": 1, "limit": 1, "total": 3}, + "events": [ { - 'category': 'Lock', - 'transaction_hash': 'tx_hash_2', - 'issuer_address': issuer_address, - 'token_address': token_address_1, - 'token_type': TokenType.IBET_STRAIGHT_BOND.value, - 'token_name': token_name_1, - 'lock_address': lock_address_1, - 'account_address': account_address, - 'recipient_address': None, - 'value': 1, - 'data': {'message': 'locked_2'}, - 'block_timestamp': ANY + "category": "Lock", + "transaction_hash": "tx_hash_2", + "issuer_address": issuer_address, + "token_address": token_address_1, + "token_type": TokenType.IBET_STRAIGHT_BOND.value, + "token_name": token_name_1, + "lock_address": lock_address_1, + "account_address": account_address, + "recipient_address": None, + "value": 1, + "data": {"message": "locked_2"}, + "block_timestamp": ANY, } - ] + ], } # ########################################################################### @@ -1272,23 +1197,20 @@ def test_error_1_1(self, client, db): self.base_url.format(account_address=account_address), headers={ "issuer-address": "test", - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # Error_1_2 @@ -1306,44 +1228,49 @@ def test_error_1_2(self, client, db): "sort_item": "test", "offset": "test", "limit": "test", - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['query', 'offset'], - 'msg': 'value is not a valid integer', - 'type': 'type_error.integer' + "loc": ["query", "offset"], + "msg": "value is not a valid integer", + "type": "type_error.integer", }, { - 'loc': ['query', 'limit'], - 'msg': 'value is not a valid integer', - 'type': 'type_error.integer' + "loc": ["query", "limit"], + "msg": "value is not a valid integer", + "type": "type_error.integer", }, { - 'loc': ['query', 'token_type'], - 'msg': "value is not a valid enumeration member; permitted: 'IbetStraightBond', 'IbetShare'", - 'type': 'type_error.enum', - 'ctx': {'enum_values': ['IbetStraightBond', 'IbetShare']} + "loc": ["query", "token_type"], + "msg": "value is not a valid enumeration member; permitted: 'IbetStraightBond', 'IbetShare'", + "type": "type_error.enum", + "ctx": {"enum_values": ["IbetStraightBond", "IbetShare"]}, }, { - 'loc': ['query', 'category'], - 'msg': "value is not a valid enumeration member; permitted: 'Lock', 'Unlock'", - 'type': 'type_error.enum', - 'ctx': {'enum_values': ['Lock', 'Unlock']} + "loc": ["query", "category"], + "msg": "value is not a valid enumeration member; permitted: 'Lock', 'Unlock'", + "type": "type_error.enum", + "ctx": {"enum_values": ["Lock", "Unlock"]}, }, { - 'loc': ['query', 'sort_item'], - 'msg': "value is not a valid enumeration member; permitted: 'token_address', 'lock_address', 'recipient_address', 'value', 'block_timestamp'", - 'type': 'type_error.enum', - 'ctx': {'enum_values': ['token_address', 'lock_address', 'recipient_address', 'value', 'block_timestamp']} - } - ] + "loc": ["query", "sort_item"], + "msg": "value is not a valid enumeration member; permitted: 'token_address', 'lock_address', 'recipient_address', 'value', 'block_timestamp'", + "type": "type_error.enum", + "ctx": { + "enum_values": [ + "token_address", + "lock_address", + "recipient_address", + "value", + "block_timestamp", + ] + }, + }, + ], } diff --git a/tests/test_app_routers_positions_{account_address}_{token_address}_GET.py b/tests/test_app_routers_positions_{account_address}_{token_address}_GET.py index 3bbe513e..43f857f4 100644 --- a/tests/test_app_routers_positions_{account_address}_{token_address}_GET.py +++ b/tests/test_app_routers_positions_{account_address}_{token_address}_GET.py @@ -18,16 +18,8 @@ """ from unittest import mock -from app.model.db import ( - IDXPosition, - IDXLockedPosition, - Token, - TokenType -) -from app.model.blockchain import ( - IbetStraightBondContract, - IbetShareContract -) +from app.model.blockchain import IbetShareContract, IbetStraightBondContract +from app.model.db import IDXLockedPosition, IDXPosition, Token, TokenType class TestAppRoutersPositionsAccountAddressTokenAddressGET: @@ -70,14 +62,18 @@ def test_normal_1_1(self, mock_IbetStraightBondContract_get, client, db): # prepare data: Locked Position _locked_position = IDXLockedPosition() _locked_position.token_address = token_address - _locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + _locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) _locked_position.account_address = account_address _locked_position.value = 5 db.add(_locked_position) _locked_position = IDXLockedPosition() _locked_position.token_address = token_address - _locked_position.lock_address = "0x1234567890123456789012345678900000000002" # lock address 2 + _locked_position.lock_address = ( + "0x1234567890123456789012345678900000000002" # lock address 2 + ) _locked_position.account_address = account_address _locked_position.value = 5 db.add(_locked_position) @@ -96,8 +92,10 @@ def test_normal_1_1(self, mock_IbetStraightBondContract_get, client, db): # request target api resp = client.get( - self.base_url.format(account_address=account_address, token_address=token_address), - headers={"issuer-address": issuer_address} + self.base_url.format( + account_address=account_address, token_address=token_address + ), + headers={"issuer-address": issuer_address}, ) # assertion @@ -111,7 +109,7 @@ def test_normal_1_1(self, mock_IbetStraightBondContract_get, client, db): "exchange_balance": 11, "exchange_commitment": 12, "pending_transfer": 13, - "locked": 10 + "locked": 10, } # @@ -146,14 +144,18 @@ def test_normal_1_2(self, mock_IbetShareContract_get, client, db): # prepare data: Locked Position _locked_position = IDXLockedPosition() _locked_position.token_address = token_address - _locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + _locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) _locked_position.account_address = account_address _locked_position.value = 5 db.add(_locked_position) _locked_position = IDXLockedPosition() _locked_position.token_address = token_address - _locked_position.lock_address = "0x1234567890123456789012345678900000000002" # lock address 2 + _locked_position.lock_address = ( + "0x1234567890123456789012345678900000000002" # lock address 2 + ) _locked_position.account_address = account_address _locked_position.value = 5 db.add(_locked_position) @@ -172,8 +174,10 @@ def test_normal_1_2(self, mock_IbetShareContract_get, client, db): # request target api resp = client.get( - self.base_url.format(account_address=account_address, token_address=token_address), - headers={"issuer-address": issuer_address} + self.base_url.format( + account_address=account_address, token_address=token_address + ), + headers={"issuer-address": issuer_address}, ) # assertion @@ -187,7 +191,7 @@ def test_normal_1_2(self, mock_IbetShareContract_get, client, db): "exchange_balance": 11, "exchange_commitment": 12, "pending_transfer": 13, - "locked": 10 + "locked": 10, } # @@ -224,7 +228,9 @@ def test_normal_2(self, mock_IbetStraightBondContract_get, client, db): # request target api resp = client.get( - self.base_url.format(account_address=account_address, token_address=token_address), + self.base_url.format( + account_address=account_address, token_address=token_address + ), ) # assertion @@ -238,7 +244,7 @@ def test_normal_2(self, mock_IbetStraightBondContract_get, client, db): "exchange_balance": 0, "exchange_commitment": 12, "pending_transfer": 13, - "locked": 0 + "locked": 0, } # @@ -262,7 +268,9 @@ def test_normal_3_1(self, mock_IbetStraightBondContract_get, client, db): # prepare data: Locked Position _locked_position = IDXLockedPosition() _locked_position.token_address = token_address - _locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + _locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) _locked_position.account_address = account_address _locked_position.value = 5 # not zero db.add(_locked_position) @@ -274,8 +282,10 @@ def test_normal_3_1(self, mock_IbetStraightBondContract_get, client, db): # request target api resp = client.get( - self.base_url.format(account_address=account_address, token_address=token_address), - headers={"issuer-address": issuer_address} + self.base_url.format( + account_address=account_address, token_address=token_address + ), + headers={"issuer-address": issuer_address}, ) # assertion @@ -289,7 +299,7 @@ def test_normal_3_1(self, mock_IbetStraightBondContract_get, client, db): "exchange_balance": 0, "exchange_commitment": 0, "pending_transfer": 0, - "locked": 0 + "locked": 0, } # @@ -322,7 +332,9 @@ def test_normal_3_2(self, mock_IbetStraightBondContract_get, client, db): # prepare data: Locked Position _locked_position = IDXLockedPosition() _locked_position.token_address = token_address - _locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + _locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) _locked_position.account_address = account_address _locked_position.value = 5 db.add(_locked_position) @@ -334,8 +346,10 @@ def test_normal_3_2(self, mock_IbetStraightBondContract_get, client, db): # request target api resp = client.get( - self.base_url.format(account_address=account_address, token_address=token_address), - headers={"issuer-address": issuer_address} + self.base_url.format( + account_address=account_address, token_address=token_address + ), + headers={"issuer-address": issuer_address}, ) # assertion @@ -349,7 +363,7 @@ def test_normal_3_2(self, mock_IbetStraightBondContract_get, client, db): "exchange_balance": 0, "exchange_commitment": 0, "pending_transfer": 0, - "locked": 5 + "locked": 5, } # @@ -387,8 +401,10 @@ def test_normal_3_3(self, mock_IbetStraightBondContract_get, client, db): # request target api resp = client.get( - self.base_url.format(account_address=account_address, token_address=token_address), - headers={"issuer-address": issuer_address} + self.base_url.format( + account_address=account_address, token_address=token_address + ), + headers={"issuer-address": issuer_address}, ) # assertion @@ -402,7 +418,7 @@ def test_normal_3_3(self, mock_IbetStraightBondContract_get, client, db): "exchange_balance": 10, "exchange_commitment": 15, "pending_transfer": 20, - "locked": 0 + "locked": 0, } # @@ -435,7 +451,9 @@ def test_normal_3_4(self, mock_IbetStraightBondContract_get, client, db): # prepare data: Locked Position _locked_position = IDXLockedPosition() _locked_position.token_address = token_address - _locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + _locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) _locked_position.account_address = account_address _locked_position.value = 0 db.add(_locked_position) @@ -447,8 +465,10 @@ def test_normal_3_4(self, mock_IbetStraightBondContract_get, client, db): # request target api resp = client.get( - self.base_url.format(account_address=account_address, token_address=token_address), - headers={"issuer-address": issuer_address} + self.base_url.format( + account_address=account_address, token_address=token_address + ), + headers={"issuer-address": issuer_address}, ) # assertion @@ -462,7 +482,7 @@ def test_normal_3_4(self, mock_IbetStraightBondContract_get, client, db): "exchange_balance": 10, "exchange_commitment": 15, "pending_transfer": 20, - "locked": 0 + "locked": 0, } ########################################################################### @@ -478,24 +498,23 @@ def test_error_1(self, client, db): # request target api resp = client.get( - self.base_url.format(account_address=account_address, token_address=token_address), - headers={"issuer-address": "test"} + self.base_url.format( + account_address=account_address, token_address=token_address + ), + headers={"issuer-address": "test"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -507,17 +526,16 @@ def test_error_2_1(self, client, db): # request target api resp = client.get( - self.base_url.format(account_address=account_address, token_address=token_address), + self.base_url.format( + account_address=account_address, token_address=token_address + ), ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # @@ -531,7 +549,9 @@ def test_error_2_2(self, client, db): # prepare data: Token _token = Token() _token.token_address = token_address - _token.issuer_address = "0x1234567890123456789012345678900000000101" # not target + _token.issuer_address = ( + "0x1234567890123456789012345678900000000101" # not target + ) _token.type = TokenType.IBET_STRAIGHT_BOND.value _token.tx_hash = "" _token.abi = "" @@ -549,18 +569,17 @@ def test_error_2_2(self, client, db): # request target api resp = client.get( - self.base_url.format(account_address=account_address, token_address=token_address), - headers={"issuer-address": issuer_address} + self.base_url.format( + account_address=account_address, token_address=token_address + ), + headers={"issuer-address": issuer_address}, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # @@ -592,16 +611,15 @@ def test_error_3(self, client, db): # request target api resp = client.get( - self.base_url.format(account_address=account_address, token_address=token_address), - headers={"issuer-address": issuer_address} + self.base_url.format( + account_address=account_address, token_address=token_address + ), + headers={"issuer-address": issuer_address}, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } diff --git a/tests/test_app_routers_share_bulk_transfer_GET.py b/tests/test_app_routers_share_bulk_transfer_GET.py index 774ad85a..0faae492 100644 --- a/tests/test_app_routers_share_bulk_transfer_GET.py +++ b/tests/test_app_routers_share_bulk_transfer_GET.py @@ -17,15 +17,11 @@ SPDX-License-Identifier: Apache-2.0 """ from datetime import datetime -import pytest +import pytest import pytz -from app.model.db import ( - Account, - TokenType, - BulkTransferUpload -) +from app.model.db import Account, BulkTransferUpload, TokenType from config import TZ from tests.account_config import config_eth_account @@ -39,20 +35,22 @@ class TestAppRoutersShareBulkTransferGET: upload_issuer_list = [ { "address": config_eth_account("user1")["address"], - "keyfile": config_eth_account("user1")["keyfile_json"] - }, { + "keyfile": config_eth_account("user1")["keyfile_json"], + }, + { "address": config_eth_account("user2")["address"], - "keyfile": config_eth_account("user2")["keyfile_json"] - }, { + "keyfile": config_eth_account("user2")["keyfile_json"], + }, + { "address": config_eth_account("user3")["address"], - "keyfile": config_eth_account("user3")["keyfile_json"] - } + "keyfile": config_eth_account("user3")["keyfile_json"], + }, ] upload_id_list = [ "0c961f7d-e1ad-40e5-988b-cca3d6009643", # 0: under progress "de778f46-864e-4ec0-b566-21bd31cf63ff", # 1: succeeded - "cf33d48f-9e6e-4a36-a55e-5bbcbda69c80" # 2: failed + "cf33d48f-9e6e-4a36-a55e-5bbcbda69c80", # 2: failed ] ########################################################################### @@ -84,7 +82,7 @@ def test_normal_1(self, client, db): # request target API resp = client.get( self.test_url, - headers={"issuer-address": self.upload_issuer_list[1]["address"]} + headers={"issuer-address": self.upload_issuer_list[1]["address"]}, ) # assertion @@ -95,7 +93,10 @@ def test_normal_1(self, client, db): "token_type": TokenType.IBET_SHARE.value, "upload_id": self.upload_id_list[1], "status": 1, - "created": pytz.timezone("UTC").localize(utc_now).astimezone(local_tz).isoformat() + "created": pytz.timezone("UTC") + .localize(utc_now) + .astimezone(local_tz) + .isoformat(), } ] assert resp.json() == assumed_response @@ -116,24 +117,28 @@ def test_normal_2(self, client, db): db.add(bulk_transfer_upload) # request target API - resp = client.get( - self.test_url - ) + resp = client.get(self.test_url) # assertion assert resp.status_code == 200 assumed_response = [] for i in range(0, 3): - assumed_response.append({ - "issuer_address": self.upload_issuer_list[i]["address"], - "token_type": TokenType.IBET_SHARE.value, - "upload_id": self.upload_id_list[i], - "status": i, - "created": pytz.timezone("UTC").localize(utc_now).astimezone(local_tz).isoformat() - }) + assumed_response.append( + { + "issuer_address": self.upload_issuer_list[i]["address"], + "token_type": TokenType.IBET_SHARE.value, + "upload_id": self.upload_id_list[i], + "status": i, + "created": pytz.timezone("UTC") + .localize(utc_now) + .astimezone(local_tz) + .isoformat(), + } + ) - assert sorted(resp.json(), key=lambda x: x['upload_id']) == sorted(assumed_response, - key=lambda x: x['upload_id']) + assert sorted(resp.json(), key=lambda x: x["upload_id"]) == sorted( + assumed_response, key=lambda x: x["upload_id"] + ) ########################################################################### # Error Case @@ -144,23 +149,17 @@ def test_normal_2(self, client, db): # invalid type : issuer-address def test_error_1(self, client, db): # request target API - resp = client.get( - self.test_url, - headers={"issuer-address": "DUMMY ADDRESS"} - ) + resp = client.get(self.test_url, headers={"issuer-address": "DUMMY ADDRESS"}) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } diff --git a/tests/test_app_routers_share_bulk_transfer_POST.py b/tests/test_app_routers_share_bulk_transfer_POST.py index 77fba575..6b213092 100644 --- a/tests/test_app_routers_share_bulk_transfer_POST.py +++ b/tests/test_app_routers_share_bulk_transfer_POST.py @@ -21,10 +21,10 @@ from app.model.db import ( Account, AuthToken, + BulkTransfer, + BulkTransferUpload, Token, TokenType, - BulkTransfer, - BulkTransferUpload ) from app.utils.e2ee_utils import E2EEUtils from tests.account_config import config_eth_account @@ -53,13 +53,13 @@ class TestAppRoutersShareBulkTransferPOST: "0x55e20Fa9F4Fa854Ef06081734872b734c105916b", "0x1d2E98AD049e978B08113fD282BD42948F265DDa", "0x2413a63D91eb10e1472a18aD4b9628fBE4aac8B8", - "0x6f9486251F4034C251ecb8Fa0f087CDDb3cDe6d7" + "0x6f9486251F4034C251ecb8Fa0f087CDDb3cDe6d7", ] upload_id_list = [ "0c961f7d-e1ad-40e5-988b-cca3d6009643", # 0: under progress "de778f46-864e-4ec0-b566-21bd31cf63ff", # 1: succeeded - "cf33d48f-9e6e-4a36-a55e-5bbcbda69c80" # 2: failed + "cf33d48f-9e6e-4a36-a55e-5bbcbda69c80", # 2: failed ] # @@ -88,37 +88,42 @@ def test_normal_1(self, client, db): "token_address": self.req_tokens[0], "from_address": self.from_address, "to_address": self.to_address, - "amount": 5 - }, { + "amount": 5, + }, + { "token_address": self.req_tokens[1], "from_address": self.from_address, "to_address": self.to_address, - "amount": 10 - } + "amount": 10, + }, ] resp = client.post( self.test_url, json=req_param, headers={ "issuer-address": self.admin_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 200 - bulk_transfer_upload = db.query(BulkTransferUpload). \ - filter(BulkTransferUpload.upload_id == resp.json()["upload_id"]). \ - all() + bulk_transfer_upload = ( + db.query(BulkTransferUpload) + .filter(BulkTransferUpload.upload_id == resp.json()["upload_id"]) + .all() + ) assert len(bulk_transfer_upload) == 1 assert bulk_transfer_upload[0].issuer_address == self.admin_address assert bulk_transfer_upload[0].status == 0 - bulk_transfer = db.query(BulkTransfer). \ - filter(BulkTransfer.upload_id == resp.json()["upload_id"]). \ - order_by(BulkTransfer.id). \ - all() + bulk_transfer = ( + db.query(BulkTransfer) + .filter(BulkTransfer.upload_id == resp.json()["upload_id"]) + .order_by(BulkTransfer.id) + .all() + ) assert len(bulk_transfer) == 2 assert bulk_transfer[0].issuer_address == self.admin_address assert bulk_transfer[0].token_address == self.req_tokens[0] @@ -168,37 +173,42 @@ def test_normal_2(self, client, db): "token_address": self.req_tokens[0], "from_address": self.from_address, "to_address": self.to_address, - "amount": 5 - }, { + "amount": 5, + }, + { "token_address": self.req_tokens[1], "from_address": self.from_address, "to_address": self.to_address, - "amount": 10 - } + "amount": 10, + }, ] resp = client.post( self.test_url, json=req_param, headers={ "issuer-address": self.admin_address, - "auth-token": "test_auth_token" - } + "auth-token": "test_auth_token", + }, ) # assertion assert resp.status_code == 200 - bulk_transfer_upload = db.query(BulkTransferUpload). \ - filter(BulkTransferUpload.upload_id == resp.json()["upload_id"]). \ - all() + bulk_transfer_upload = ( + db.query(BulkTransferUpload) + .filter(BulkTransferUpload.upload_id == resp.json()["upload_id"]) + .all() + ) assert len(bulk_transfer_upload) == 1 assert bulk_transfer_upload[0].issuer_address == self.admin_address assert bulk_transfer_upload[0].status == 0 - bulk_transfer = db.query(BulkTransfer). \ - filter(BulkTransfer.upload_id == resp.json()["upload_id"]). \ - order_by(BulkTransfer.id). \ - all() + bulk_transfer = ( + db.query(BulkTransfer) + .filter(BulkTransfer.upload_id == resp.json()["upload_id"]) + .order_by(BulkTransfer.id) + .all() + ) assert len(bulk_transfer) == 2 assert bulk_transfer[0].issuer_address == self.admin_address assert bulk_transfer[0].token_address == self.req_tokens[0] @@ -224,14 +234,16 @@ def test_normal_2(self, client, db): # invalid type def test_error_1(self, client, db): _token_address_int = 10 # integer - _from_address_long = "0xd9F55747DE740297ff1eEe537aBE0f8d73B7D7811" # long address + _from_address_long = ( + "0xd9F55747DE740297ff1eEe537aBE0f8d73B7D7811" # long address + ) _to_address_short = "0xd9F55747DE740297ff1eEe537aBE0f8d73B7D78" # short address req_param = [ { "token_address": _token_address_int, "from_address": _from_address_long, "to_address": _to_address_short, - "amount": 0 + "amount": 0, }, ] @@ -239,42 +251,36 @@ def test_error_1(self, client, db): resp = client.post( self.test_url, json=req_param, - headers={"issuer-address": self.admin_address} + headers={"issuer-address": self.admin_address}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", 0, "token_address"], "msg": "token_address is not a valid address", - "type": "value_error" - }, { + "type": "value_error", + }, + { "loc": ["body", 0, "from_address"], "msg": "from_address is not a valid address", - "type": "value_error" - }, { + "type": "value_error", + }, + { "loc": ["body", 0, "to_address"], "msg": "to_address is not a valid address", - "type": "value_error" - }, { - "ctx": { - "limit_value": 1 - }, - "loc": [ - "body", - 0, - "amount" - ], + "type": "value_error", + }, + { + "ctx": {"limit_value": 1}, + "loc": ["body", 0, "amount"], "msg": "ensure this value is greater than or equal to 1", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, - ] + ], } # @@ -287,7 +293,7 @@ def test_error_2(self, client, db): "token_address": self.req_tokens[0], "from_address": self.from_address, "to_address": self.to_address, - "amount": 1_000_000_000_001 + "amount": 1_000_000_000_001, } ] resp = client.post( @@ -295,31 +301,22 @@ def test_error_2(self, client, db): json=req_param, headers={ "issuer-address": self.admin_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "ctx": { - "limit_value": 1_000_000_000_000 - }, - "loc": [ - "body", - 0, - "amount" - ], + "ctx": {"limit_value": 1_000_000_000_000}, + "loc": ["body", 0, "amount"], "msg": "ensure this value is less than or equal to 1000000000000", - "type": "value_error.number.not_le" + "type": "value_error.number.not_le", }, - ] + ], } # @@ -327,29 +324,24 @@ def test_error_2(self, client, db): # headers and body required def test_error_3(self, client, db): # request target API - resp = client.post( - self.test_url - ) + resp = client.post(self.test_url) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, { "loc": ["body"], "msg": "field required", - "type": "value_error.missing" - } - ] + "type": "value_error.missing", + }, + ], } # @@ -359,27 +351,20 @@ def test_error_4(self, client, db): # request target API req_param = [] resp = client.post( - self.test_url, - json=req_param, - headers={ - "issuer-address": "admin_address" - } + self.test_url, json=req_param, headers={"issuer-address": "admin_address"} ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -391,24 +376,20 @@ def test_error_5(self, client, db): resp = client.post( self.test_url, json=req_param, - headers={ - "issuer-address": self.admin_address, - "eoa-password": "password" - } + headers={"issuer-address": self.admin_address, "eoa-password": "password"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, - "detail": [{ - "loc": ["header", "eoa-password"], - "msg": "eoa-password is not a Base64-encoded encrypted data", - "type": "value_error" - }] + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ + { + "loc": ["header", "eoa-password"], + "msg": "eoa-password is not a Base64-encoded encrypted data", + "type": "value_error", + } + ], } # @@ -429,18 +410,15 @@ def test_error_6(self, client, db): json=req_param, headers={ "issuer-address": self.admin_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "list length must be at least one" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "list length must be at least one", } # @@ -453,31 +431,29 @@ def test_error_7(self, client, db): "token_address": self.req_tokens[0], "from_address": self.from_address, "to_address": self.to_address, - "amount": 5 - }, { + "amount": 5, + }, + { "token_address": self.req_tokens[1], "from_address": self.from_address, "to_address": self.to_address, - "amount": 10 - } + "amount": 10, + }, ] resp = client.post( self.test_url, json=req_param, headers={ "issuer-address": self.admin_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -497,7 +473,7 @@ def test_error_8(self, client, db): "token_address": self.req_tokens[0], "from_address": self.from_address, "to_address": self.to_address, - "amount": 10 + "amount": 10, } ] resp = client.post( @@ -505,17 +481,14 @@ def test_error_8(self, client, db): json=req_param, headers={ "issuer-address": self.admin_address, - "eoa-password": E2EEUtils.encrypt("password_test") - } + "eoa-password": E2EEUtils.encrypt("password_test"), + }, ) assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -535,7 +508,7 @@ def test_error_9(self, client, db): "token_address": self.req_tokens[0], "from_address": self.from_address, "to_address": self.to_address, - "amount": 10 + "amount": 10, } ] resp = client.post( @@ -543,17 +516,14 @@ def test_error_9(self, client, db): json=req_param, headers={ "issuer-address": self.admin_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": f"token not found: {self.req_tokens[0]}" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": f"token not found: {self.req_tokens[0]}", } # @@ -583,7 +553,7 @@ def test_error_10(self, client, db): "token_address": self.req_tokens[0], "from_address": self.from_address, "to_address": self.to_address, - "amount": 10 + "amount": 10, } ] resp = client.post( @@ -591,15 +561,12 @@ def test_error_10(self, client, db): json=req_param, headers={ "issuer-address": self.admin_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": f"this token is temporarily unavailable: {self.req_tokens[0]}" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": f"this token is temporarily unavailable: {self.req_tokens[0]}", } diff --git a/tests/test_app_routers_share_bulk_transfer_{upload_id}_GET.py b/tests/test_app_routers_share_bulk_transfer_{upload_id}_GET.py index 3dac37fc..60299fcd 100644 --- a/tests/test_app_routers_share_bulk_transfer_{upload_id}_GET.py +++ b/tests/test_app_routers_share_bulk_transfer_{upload_id}_GET.py @@ -16,7 +16,7 @@ SPDX-License-Identifier: Apache-2.0 """ -from app.model.db import Account, TokenType, BulkTransfer, BulkTransferUpload +from app.model.db import Account, BulkTransfer, BulkTransferUpload, TokenType from tests.account_config import config_eth_account @@ -27,20 +27,22 @@ class TestAppRoutersShareBulkTransferGET: upload_issuer_list = [ { "address": config_eth_account("user1")["address"], - "keyfile": config_eth_account("user1")["keyfile_json"] - }, { + "keyfile": config_eth_account("user1")["keyfile_json"], + }, + { "address": config_eth_account("user2")["address"], - "keyfile": config_eth_account("user2")["keyfile_json"] - }, { + "keyfile": config_eth_account("user2")["keyfile_json"], + }, + { "address": config_eth_account("user3")["address"], - "keyfile": config_eth_account("user3")["keyfile_json"] - } + "keyfile": config_eth_account("user3")["keyfile_json"], + }, ] upload_id_list = [ "0c961f7d-e1ad-40e5-988b-cca3d6009643", # 0: under progress "de778f46-864e-4ec0-b566-21bd31cf63ff", # 1: succeeded - "cf33d48f-9e6e-4a36-a55e-5bbcbda69c80" # 2: failed + "cf33d48f-9e6e-4a36-a55e-5bbcbda69c80", # 2: failed ] bulk_transfer_token = "0xbB4138520af85fAfdDAACc7F0AabfE188334D0ca" @@ -82,7 +84,7 @@ def test_normal_1(self, client, db): # request target API resp = client.get( self.test_url.format(self.upload_id_list[1]), - headers={"issuer-address": self.upload_issuer_list[1]["address"]} + headers={"issuer-address": self.upload_issuer_list[1]["address"]}, ) # assertion @@ -96,14 +98,13 @@ def test_normal_1(self, client, db): "from_address": self.upload_issuer_list[1]["address"], "to_address": self.upload_issuer_list[2]["address"], "amount": 11, - "status": 1 + "status": 1, } ] assert resp.json() == assumed_response # def test_normal_2(self, client, db): - for i in range(0, 3): # prepare data : BulkTransferUpload bulk_transfer_upload = BulkTransferUpload() @@ -141,7 +142,7 @@ def test_normal_2(self, client, db): "from_address": self.upload_issuer_list[1]["address"], "to_address": self.upload_issuer_list[2]["address"], "amount": 10, - "status": 0 + "status": 0, } ] assert resp.json() == assumed_response @@ -157,40 +158,32 @@ def test_error_1(self, client, db): # request target API resp = client.get( self.test_url.format(self.upload_id_list[0]), - headers={"issuer-address": "DUMMY ADDRESS"} + headers={"issuer-address": "DUMMY ADDRESS"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # # Upload id Not Found def test_error_2(self, client, db): # request target API - resp = client.get( - self.test_url.format("DUMMY UPLOAD ID") - ) + resp = client.get(self.test_url.format("DUMMY UPLOAD ID")) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, + "meta": {"code": 1, "title": "NotFound"}, "detail": "bulk transfer not found", } @@ -228,15 +221,12 @@ def test_error_3(self, client, db): # request target API resp = client.get( self.test_url.format(self.upload_id_list[2]), - headers={"issuer-address": self.upload_issuer_list[0]["address"]} + headers={"issuer-address": self.upload_issuer_list[0]["address"]}, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "bulk transfer not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "bulk transfer not found", } diff --git a/tests/test_app_routers_share_lock_events_GET.py b/tests/test_app_routers_share_lock_events_GET.py index 4c107755..7389a78b 100644 --- a/tests/test_app_routers_share_lock_events_GET.py +++ b/tests/test_app_routers_share_lock_events_GET.py @@ -19,22 +19,15 @@ from datetime import datetime from unittest import mock from unittest.mock import ANY, MagicMock + import pytest from sqlalchemy.orm import Session -from app.model.db import ( - IDXLock, - IDXUnlock, - Token, - TokenType -) -from app.model.blockchain import ( - IbetShareContract -) +from app.model.blockchain import IbetShareContract +from app.model.db import IDXLock, IDXUnlock, Token, TokenType class TestAppRoutersShareLockEvents: - # target API endpoint base_url = "/share/tokens/{token_address}/lock_events" @@ -144,7 +137,7 @@ def get_contract_mock_data(token_name_list: list[str]): "recipient_address": None, "value": 1, "data": {"message": "locked_1"}, - "block_timestamp": ANY + "block_timestamp": ANY, } expected_lock_2 = { "category": "Lock", @@ -158,7 +151,7 @@ def get_contract_mock_data(token_name_list: list[str]): "recipient_address": None, "value": 1, "data": {"message": "locked_2"}, - "block_timestamp": ANY + "block_timestamp": ANY, } expected_unlock_1 = { "category": "Unlock", @@ -172,7 +165,7 @@ def get_contract_mock_data(token_name_list: list[str]): "recipient_address": other_account_address_1, "value": 1, "data": {"message": "unlocked_1"}, - "block_timestamp": ANY + "block_timestamp": ANY, } expected_unlock_2 = { "category": "Unlock", @@ -186,7 +179,7 @@ def get_contract_mock_data(token_name_list: list[str]): "recipient_address": other_account_address_2, "value": 1, "data": {"message": "unlocked_2"}, - "block_timestamp": ANY + "block_timestamp": ANY, } ########################################################################### @@ -219,7 +212,7 @@ def test_normal_1(self, client, db): "limit": None, "total": 0, }, - "events": [] + "events": [], } # Normal_2 @@ -242,18 +235,13 @@ def test_normal_2(self, mock_IbetShareContract_get, client, db): # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 4, - "offset": None, - "limit": None, - "total": 4 - }, + "result_set": {"count": 4, "offset": None, "limit": None, "total": 4}, "events": [ self.expected_unlock_2, self.expected_unlock_1, self.expected_lock_2, - self.expected_lock_1 - ] + self.expected_lock_1, + ], } # Normal_3 @@ -272,13 +260,8 @@ def test_normal_3(self, mock_IbetShareContract_get, client, db): # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 0, - 'offset': None, - 'limit': None, - 'total': 0 - }, - 'events': [] + "result_set": {"count": 0, "offset": None, "limit": None, "total": 0}, + "events": [], } # Normal_4 @@ -296,24 +279,19 @@ def test_normal_4(self, mock_IbetShareContract_get, client, db): # request target api resp = client.get( self.base_url.format(token_address=self.token_address_1), - headers={"issuer-address": self.issuer_address} + headers={"issuer-address": self.issuer_address}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 4, - "offset": None, - "limit": None, - "total": 4 - }, + "result_set": {"count": 4, "offset": None, "limit": None, "total": 4}, "events": [ self.expected_unlock_2, self.expected_unlock_1, self.expected_lock_2, - self.expected_lock_1 - ] + self.expected_lock_1, + ], } # Normal_5_1 @@ -331,22 +309,14 @@ def test_normal_5_1(self, mock_IbetShareContract_get, client, db): # request target api resp = client.get( self.base_url.format(token_address=self.token_address_1), - params={"category": "Lock"} + params={"category": "Lock"}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 2, - "offset": None, - "limit": None, - "total": 4 - }, - "events": [ - self.expected_lock_2, - self.expected_lock_1 - ] + "result_set": {"count": 2, "offset": None, "limit": None, "total": 4}, + "events": [self.expected_lock_2, self.expected_lock_1], } # Normal_5_2 @@ -364,22 +334,14 @@ def test_normal_5_2(self, mock_IbetShareContract_get, client, db): # request target api resp = client.get( self.base_url.format(token_address=self.token_address_1), - params={"account_address": self.account_address_1} + params={"account_address": self.account_address_1}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 2, - "offset": None, - "limit": None, - "total": 4 - }, - "events": [ - self.expected_unlock_1, - self.expected_lock_1 - ] + "result_set": {"count": 2, "offset": None, "limit": None, "total": 4}, + "events": [self.expected_unlock_1, self.expected_lock_1], } # Normal_5_3 @@ -397,22 +359,14 @@ def test_normal_5_3(self, mock_IbetShareContract_get, client, db): # request target api resp = client.get( self.base_url.format(token_address=self.token_address_1), - params={"lock_address": self.lock_address_1} + params={"lock_address": self.lock_address_1}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 2, - 'offset': None, - 'limit': None, - 'total': 4 - }, - 'events': [ - self.expected_unlock_1, - self.expected_lock_1 - ] + "result_set": {"count": 2, "offset": None, "limit": None, "total": 4}, + "events": [self.expected_unlock_1, self.expected_lock_1], } # Normal_5_4 @@ -430,81 +384,112 @@ def test_normal_5_4(self, mock_IbetShareContract_get, client, db): # request target api resp = client.get( self.base_url.format(token_address=self.token_address_1), - params={"recipient_address": self.other_account_address_2} + params={"recipient_address": self.other_account_address_2}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 1, - 'offset': None, - 'limit': None, - 'total': 4 - }, - 'events': [ - self.expected_unlock_2 - ] + "result_set": {"count": 1, "offset": None, "limit": None, "total": 4}, + "events": [self.expected_unlock_2], } # Normal_6 # Sort - @pytest.mark.parametrize("sort_item, sort_order, data, expect", [ - # ( - # "{sort_item}", {sort_order}, - # {data used to contract mock}, - # {expected result} - # ), - ( - "account_address", 0, - get_contract_mock_data([token_name_1, token_name_1, token_name_1, token_name_1]), - [expected_unlock_1, expected_lock_1, expected_unlock_2, expected_lock_2] - ), - ( - "lock_address", 0, - get_contract_mock_data([token_name_1, token_name_1, token_name_1, token_name_1]), - [expected_unlock_1, expected_lock_1, expected_unlock_2, expected_lock_2] - ), - ( - "recipient_address", 0, - get_contract_mock_data([token_name_1, token_name_1, token_name_1, token_name_1]), - [expected_unlock_1, expected_unlock_2, expected_lock_2, expected_lock_1] - ), - ( - "recipient_address", 1, - get_contract_mock_data([token_name_1, token_name_1, token_name_1, token_name_1]), - [expected_lock_2, expected_lock_1, expected_unlock_2, expected_unlock_1] - ), - ( - "value", 0, - get_contract_mock_data([token_name_1, token_name_1, token_name_1, token_name_1]), - [expected_unlock_2, expected_unlock_1, expected_lock_2, expected_lock_1] - ), - ]) + @pytest.mark.parametrize( + "sort_item, sort_order, data, expect", + [ + # ( + # "{sort_item}", {sort_order}, + # {data used to contract mock}, + # {expected result} + # ), + ( + "account_address", + 0, + get_contract_mock_data( + [token_name_1, token_name_1, token_name_1, token_name_1] + ), + [ + expected_unlock_1, + expected_lock_1, + expected_unlock_2, + expected_lock_2, + ], + ), + ( + "lock_address", + 0, + get_contract_mock_data( + [token_name_1, token_name_1, token_name_1, token_name_1] + ), + [ + expected_unlock_1, + expected_lock_1, + expected_unlock_2, + expected_lock_2, + ], + ), + ( + "recipient_address", + 0, + get_contract_mock_data( + [token_name_1, token_name_1, token_name_1, token_name_1] + ), + [ + expected_unlock_1, + expected_unlock_2, + expected_lock_2, + expected_lock_1, + ], + ), + ( + "recipient_address", + 1, + get_contract_mock_data( + [token_name_1, token_name_1, token_name_1, token_name_1] + ), + [ + expected_lock_2, + expected_lock_1, + expected_unlock_2, + expected_unlock_1, + ], + ), + ( + "value", + 0, + get_contract_mock_data( + [token_name_1, token_name_1, token_name_1, token_name_1] + ), + [ + expected_unlock_2, + expected_unlock_1, + expected_lock_2, + expected_lock_1, + ], + ), + ], + ) def test_normal_6(self, sort_item, sort_order, data, expect, client, db): # prepare data self.setup_data(db=db) # request target api - with mock.patch("app.model.blockchain.token.IbetShareContract.get", MagicMock(side_effect=data)): + with mock.patch( + "app.model.blockchain.token.IbetShareContract.get", + MagicMock(side_effect=data), + ): resp = client.get( self.base_url.format(token_address=self.token_address_1), - params={ - "sort_item": sort_item, - "sort_order": sort_order - } + params={"sort_item": sort_item, "sort_order": sort_order}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 4, - 'offset': None, - 'limit': None, - 'total': 4 - }, - 'events': expect + "result_set": {"count": 4, "offset": None, "limit": None, "total": 4}, + "events": expect, } # Normal_7 @@ -522,24 +507,14 @@ def test_normal_7(self, mock_IbetShareContract_get, client, db): # request target api resp = client.get( self.base_url.format(token_address=self.token_address_1), - params={ - "offset": 1, - "limit": 1 - } + params={"offset": 1, "limit": 1}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 4, - 'offset': 1, - 'limit': 1, - 'total': 4 - }, - 'events': [ - self.expected_unlock_1 - ] + "result_set": {"count": 4, "offset": 1, "limit": 1, "total": 4}, + "events": [self.expected_unlock_1], } # ########################################################################### @@ -555,23 +530,20 @@ def test_error_1_1(self, client, db): self.base_url.format(token_address=self.token_address_1), headers={ "issuer-address": "test", - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # Error_1_2 @@ -586,38 +558,43 @@ def test_error_1_2(self, client, db): "sort_item": "test", "offset": "test", "limit": "test", - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['query', 'offset'], - 'msg': 'value is not a valid integer', - 'type': 'type_error.integer' + "loc": ["query", "offset"], + "msg": "value is not a valid integer", + "type": "type_error.integer", }, { - 'loc': ['query', 'limit'], - 'msg': 'value is not a valid integer', - 'type': 'type_error.integer' + "loc": ["query", "limit"], + "msg": "value is not a valid integer", + "type": "type_error.integer", }, { - 'loc': ['query', 'category'], - 'msg': "value is not a valid enumeration member; permitted: 'Lock', 'Unlock'", - 'type': 'type_error.enum', - 'ctx': {'enum_values': ['Lock', 'Unlock']} + "loc": ["query", "category"], + "msg": "value is not a valid enumeration member; permitted: 'Lock', 'Unlock'", + "type": "type_error.enum", + "ctx": {"enum_values": ["Lock", "Unlock"]}, }, { - 'loc': ['query', 'sort_item'], - 'msg': "value is not a valid enumeration member; permitted: 'account_address', 'lock_address', 'recipient_address', 'value', 'block_timestamp'", - 'type': 'type_error.enum', - 'ctx': {'enum_values': ['account_address', 'lock_address', 'recipient_address', 'value', 'block_timestamp']} - } - ] + "loc": ["query", "sort_item"], + "msg": "value is not a valid enumeration member; permitted: 'account_address', 'lock_address', 'recipient_address', 'value', 'block_timestamp'", + "type": "type_error.enum", + "ctx": { + "enum_values": [ + "account_address", + "lock_address", + "recipient_address", + "value", + "block_timestamp", + ] + }, + }, + ], } diff --git a/tests/test_app_routers_share_tokens_GET.py b/tests/test_app_routers_share_tokens_GET.py index e739ac2a..935a6f87 100644 --- a/tests/test_app_routers_share_tokens_GET.py +++ b/tests/test_app_routers_share_tokens_GET.py @@ -18,14 +18,12 @@ """ from unittest import mock from unittest.mock import call + from pytz import timezone -from config import TZ from app.model.blockchain import IbetShareContract -from app.model.db import ( - Token, - TokenType -) +from app.model.db import Token, TokenType +from config import TZ from tests.account_config import config_eth_account @@ -61,7 +59,12 @@ def test_normal_2(self, mock_get, client, db): token.abi = "abi_test1" db.add(token) db.commit() - _issue_datetime = timezone("UTC").localize(token.created).astimezone(self.local_tz).isoformat() + _issue_datetime = ( + timezone("UTC") + .localize(token.created) + .astimezone(self.local_tz) + .isoformat() + ) # request target API mock_token = IbetShareContract() @@ -72,7 +75,9 @@ def test_normal_2(self, mock_get, client, db): mock_token.total_supply = 10000 mock_token.contact_information = "contactInformation_test1" mock_token.privacy_policy = "privacyPolicy_test1" - mock_token.tradable_exchange_contract_address = "0x1234567890abCdFe1234567890ABCdFE12345678" + mock_token.tradable_exchange_contract_address = ( + "0x1234567890abCdFe1234567890ABCdFE12345678" + ) mock_token.status = True mock_token.issue_price = 1000 mock_token.dividends = 123.45 @@ -81,7 +86,9 @@ def test_normal_2(self, mock_get, client, db): mock_token.cancellation_date = "20221231" mock_token.transferable = True mock_token.is_offering = True - mock_token.personal_info_contract_address = "0x1234567890aBcDFE1234567890abcDFE12345679" + mock_token.personal_info_contract_address = ( + "0x1234567890aBcDFE1234567890abcDFE12345679" + ) mock_token.principal_value = 1000 mock_token.transfer_approval_required = False mock_token.is_canceled = False @@ -138,7 +145,12 @@ def test_normal_3(self, mock_get, client, db): token_1.abi = "abi_test1" db.add(token_1) db.commit() - _issue_datetime_1 = timezone("UTC").localize(token_1.created).astimezone(self.local_tz).isoformat() + _issue_datetime_1 = ( + timezone("UTC") + .localize(token_1.created) + .astimezone(self.local_tz) + .isoformat() + ) mock_token_1 = IbetShareContract() mock_token_1.issuer_address = issuer_address_1 @@ -148,7 +160,9 @@ def test_normal_3(self, mock_get, client, db): mock_token_1.total_supply = 10000 mock_token_1.contact_information = "contactInformation_test1" mock_token_1.privacy_policy = "privacyPolicy_test1" - mock_token_1.tradable_exchange_contract_address = "0x1234567890abCdFe1234567890ABCdFE12345678" + mock_token_1.tradable_exchange_contract_address = ( + "0x1234567890abCdFe1234567890ABCdFE12345678" + ) mock_token_1.status = True mock_token_1.issue_price = 1000 mock_token_1.dividends = 123.45 @@ -157,7 +171,9 @@ def test_normal_3(self, mock_get, client, db): mock_token_1.cancellation_date = "20221231" mock_token_1.transferable = True mock_token_1.is_offering = True - mock_token_1.personal_info_contract_address = "0x1234567890aBcDFE1234567890abcDFE12345679" + mock_token_1.personal_info_contract_address = ( + "0x1234567890aBcDFE1234567890abcDFE12345679" + ) mock_token_1.principal_value = 1000 mock_token_1.transfer_approval_required = False mock_token_1.is_canceled = False @@ -173,7 +189,12 @@ def test_normal_3(self, mock_get, client, db): token_2.token_status = 0 db.add(token_2) db.commit() - _issue_datetime_2 = timezone("UTC").localize(token_2.created).astimezone(self.local_tz).isoformat() + _issue_datetime_2 = ( + timezone("UTC") + .localize(token_2.created) + .astimezone(self.local_tz) + .isoformat() + ) mock_token_2 = IbetShareContract() mock_token_2.issuer_address = issuer_address_2 @@ -183,7 +204,9 @@ def test_normal_3(self, mock_get, client, db): mock_token_2.total_supply = 10000 mock_token_2.contact_information = "contactInformation_test2" mock_token_2.privacy_policy = "privacyPolicy_test2" - mock_token_2.tradable_exchange_contract_address = "0x1234567890abCdFe1234567890ABCdFE12345678" + mock_token_2.tradable_exchange_contract_address = ( + "0x1234567890abCdFe1234567890ABCdFE12345678" + ) mock_token_2.status = True mock_token_2.issue_price = 1000 mock_token_2.dividends = 123.45 @@ -192,15 +215,15 @@ def test_normal_3(self, mock_get, client, db): mock_token_2.cancellation_date = "20221231" mock_token_2.transferable = True mock_token_2.is_offering = True - mock_token_2.personal_info_contract_address = "0x1234567890aBcDFE1234567890abcDFE12345679" + mock_token_2.personal_info_contract_address = ( + "0x1234567890aBcDFE1234567890abcDFE12345679" + ) mock_token_2.principal_value = 1000 mock_token_2.transfer_approval_required = False mock_token_2.is_canceled = False mock_token_2.memo = "memo_test2" - mock_get.side_effect = [ - mock_token_1, mock_token_2 - ] + mock_get.side_effect = [mock_token_1, mock_token_2] resp = client.get(self.apiurl) @@ -254,7 +277,7 @@ def test_normal_3(self, mock_get, client, db): "issue_datetime": _issue_datetime_2, "token_status": 0, "memo": "memo_test2", - } + }, ] assert resp.status_code == 200 @@ -296,7 +319,12 @@ def test_normal_5(self, mock_get, client, db): token_1.abi = "abi_test1" db.add(token_1) db.commit() - _issue_datetime = timezone("UTC").localize(token_1.created).astimezone(self.local_tz).isoformat() + _issue_datetime = ( + timezone("UTC") + .localize(token_1.created) + .astimezone(self.local_tz) + .isoformat() + ) mock_token = IbetShareContract() mock_token.issuer_address = issuer_address_1 @@ -306,7 +334,9 @@ def test_normal_5(self, mock_get, client, db): mock_token.total_supply = 10000 mock_token.contact_information = "contactInformation_test1" mock_token.privacy_policy = "privacyPolicy_test1" - mock_token.tradable_exchange_contract_address = "0x1234567890abCdFe1234567890ABCdFE12345678" + mock_token.tradable_exchange_contract_address = ( + "0x1234567890abCdFe1234567890ABCdFE12345678" + ) mock_token.status = True mock_token.issue_price = 1000 mock_token.dividends = 123.45 @@ -315,7 +345,9 @@ def test_normal_5(self, mock_get, client, db): mock_token.cancellation_date = "20221231" mock_token.transferable = True mock_token.is_offering = True - mock_token.personal_info_contract_address = "0x1234567890aBcDFE1234567890abcDFE12345679" + mock_token.personal_info_contract_address = ( + "0x1234567890aBcDFE1234567890abcDFE12345679" + ) mock_token.principal_value = 1000 mock_token.transfer_approval_required = False mock_token.is_canceled = False @@ -381,7 +413,12 @@ def test_normal_6(self, mock_get, client, db): token_1.abi = "abi_test1" db.add(token_1) db.commit() - _issue_datetime_1 = timezone("UTC").localize(token_1.created).astimezone(self.local_tz).isoformat() + _issue_datetime_1 = ( + timezone("UTC") + .localize(token_1.created) + .astimezone(self.local_tz) + .isoformat() + ) mock_token_1 = IbetShareContract() mock_token_1.issuer_address = issuer_address_1 @@ -391,7 +428,9 @@ def test_normal_6(self, mock_get, client, db): mock_token_1.total_supply = 10000 mock_token_1.contact_information = "contactInformation_test1" mock_token_1.privacy_policy = "privacyPolicy_test1" - mock_token_1.tradable_exchange_contract_address = "0x1234567890abCdFe1234567890ABCdFE12345678" + mock_token_1.tradable_exchange_contract_address = ( + "0x1234567890abCdFe1234567890ABCdFE12345678" + ) mock_token_1.status = True mock_token_1.issue_price = 1000 mock_token_1.dividends = 123.45 @@ -400,7 +439,9 @@ def test_normal_6(self, mock_get, client, db): mock_token_1.cancellation_date = "20221231" mock_token_1.transferable = True mock_token_1.is_offering = True - mock_token_1.personal_info_contract_address = "0x1234567890aBcDFE1234567890abcDFE12345679" + mock_token_1.personal_info_contract_address = ( + "0x1234567890aBcDFE1234567890abcDFE12345679" + ) mock_token_1.principal_value = 1000 mock_token_1.transfer_approval_required = False mock_token_1.is_canceled = False @@ -416,7 +457,12 @@ def test_normal_6(self, mock_get, client, db): token_2.token_status = 0 db.add(token_2) db.commit() - _issue_datetime_2 = timezone("UTC").localize(token_2.created).astimezone(self.local_tz).isoformat() + _issue_datetime_2 = ( + timezone("UTC") + .localize(token_2.created) + .astimezone(self.local_tz) + .isoformat() + ) mock_token_2 = IbetShareContract() mock_token_2.issuer_address = issuer_address_1 @@ -426,7 +472,9 @@ def test_normal_6(self, mock_get, client, db): mock_token_2.total_supply = 10000 mock_token_2.contact_information = "contactInformation_test2" mock_token_2.privacy_policy = "privacyPolicy_test2" - mock_token_2.tradable_exchange_contract_address = "0x1234567890abCdFe1234567890ABCdFE12345678" + mock_token_2.tradable_exchange_contract_address = ( + "0x1234567890abCdFe1234567890ABCdFE12345678" + ) mock_token_2.status = True mock_token_2.issue_price = 1000 mock_token_2.dividends = 123.45 @@ -435,15 +483,15 @@ def test_normal_6(self, mock_get, client, db): mock_token_2.cancellation_date = "20221231" mock_token_2.transferable = True mock_token_2.is_offering = True - mock_token_2.personal_info_contract_address = "0x1234567890aBcDFE1234567890abcDFE12345679" + mock_token_2.personal_info_contract_address = ( + "0x1234567890aBcDFE1234567890abcDFE12345679" + ) mock_token_2.principal_value = 1000 mock_token_2.transfer_approval_required = False mock_token_2.is_canceled = False mock_token_2.memo = "memo_test2" - mock_get.side_effect = [ - mock_token_1, mock_token_2 - ] + mock_get.side_effect = [mock_token_1, mock_token_2] # No Target Data token_3 = Token() @@ -506,7 +554,7 @@ def test_normal_6(self, mock_get, client, db): "issue_datetime": _issue_datetime_2, "token_status": 0, "memo": "memo_test2", - } + }, ] assert resp.status_code == 200 @@ -523,13 +571,12 @@ def test_error_1(self, client, db): assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, - "detail": [{ - "loc": ["header", "issuer-address"], - "msg": "issuer-address is not a valid address", - "type": "value_error" - }] + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ + { + "loc": ["header", "issuer-address"], + "msg": "issuer-address is not a valid address", + "type": "value_error", + } + ], } diff --git a/tests/test_app_routers_share_tokens_POST.py b/tests/test_app_routers_share_tokens_POST.py index 0e37c42c..c3a89e9e 100644 --- a/tests/test_app_routers_share_tokens_POST.py +++ b/tests/test_app_routers_share_tokens_POST.py @@ -17,35 +17,29 @@ SPDX-License-Identifier: Apache-2.0 """ import hashlib -from unittest.mock import ( - ANY, - patch -) -from datetime import ( - datetime, - timezone -) +import random +import string +from datetime import datetime, timezone +from unittest.mock import ANY, patch from web3 import Web3 from web3.middleware import geth_poa_middleware import config -import random -import string from app.exceptions import SendTransactionError +from app.model.blockchain.token import IbetShareContract +from app.model.blockchain.token_list import TokenListContract from app.model.db import ( + UTXO, Account, AuthToken, + IDXPosition, Token, TokenType, UpdateToken, - IDXPosition, - UTXO ) from app.utils.contract_utils import ContractUtils from app.utils.e2ee_utils import E2EEUtils -from app.model.blockchain.token import IbetShareContract -from app.model.blockchain.token_list import TokenListContract from tests.account_config import config_eth_account web3 = Web3(Web3.HTTPProvider(config.WEB3_HTTP_PROVIDER)) @@ -77,23 +71,25 @@ def test_normal_1_1(self, client, db): # mock IbetShareContract_create = patch( target="app.model.blockchain.token.IbetShareContract.create", - return_value=("contract_address_test1", "abi_test1", "tx_hash_test1") + return_value=("contract_address_test1", "abi_test1", "tx_hash_test1"), ) TokenListContract_register = patch( target="app.model.blockchain.token_list.TokenListContract.register", - return_value=None + return_value=None, ) ContractUtils_get_block_by_transaction_hash = patch( target="app.utils.contract_utils.ContractUtils.get_block_by_transaction_hash", return_value={ "number": 12345, - "timestamp": datetime(2021, 4, 27, 12, 34, 56, tzinfo=timezone.utc).timestamp() - } + "timestamp": datetime( + 2021, 4, 27, 12, 34, 56, tzinfo=timezone.utc + ).timestamp(), + }, ) - with IbetShareContract_create, \ - TokenListContract_register, \ - ContractUtils_get_block_by_transaction_hash: + with ( + IbetShareContract_create + ), TokenListContract_register, ContractUtils_get_block_by_transaction_hash: # request target api req_param = { "name": "name_test1", @@ -104,35 +100,40 @@ def test_normal_1_1(self, client, db): "dividend_record_date": "20211231", "dividend_payment_date": "20211231", "cancellation_date": "20221231", - "principal_value": 1000 + "principal_value": 1000, } resp = client.post( self.apiurl, json=req_param, headers={ "issuer-address": test_account["address"], - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion IbetShareContract.create.assert_called_with( args=[ - "name_test1", "symbol_test1", 1000, 10000, 1234500000000000, - "20211231", "20211231", "20221231", 1000 + "name_test1", + "symbol_test1", + 1000, + 10000, + 1234500000000000, + "20211231", + "20211231", + "20221231", + 1000, ], tx_from=test_account["address"], - private_key=ANY + private_key=ANY, ) TokenListContract.register.assert_called_with( token_address="contract_address_test1", token_template=TokenType.IBET_SHARE.value, tx_from=test_account["address"], - private_key=ANY - ) - ContractUtils.get_block_by_transaction_hash( - tx_hash="tx_hash_test1" + private_key=ANY, ) + ContractUtils.get_block_by_transaction_hash(tx_hash="tx_hash_test1") assert resp.status_code == 200 assert resp.json()["token_address"] == "contract_address_test1" @@ -187,57 +188,54 @@ def test_normal_1_2(self, client, db): # mock IbetShareContract_create = patch( target="app.model.blockchain.token.IbetShareContract.create", - return_value=("contract_address_test1", "abi_test1", "tx_hash_test1") + return_value=("contract_address_test1", "abi_test1", "tx_hash_test1"), ) TokenListContract_register = patch( target="app.model.blockchain.token_list.TokenListContract.register", - return_value=None + return_value=None, ) ContractUtils_get_block_by_transaction_hash = patch( target="app.utils.contract_utils.ContractUtils.get_block_by_transaction_hash", return_value={ "number": 12345, - "timestamp": datetime(2021, 4, 27, 12, 34, 56, tzinfo=timezone.utc).timestamp() - } + "timestamp": datetime( + 2021, 4, 27, 12, 34, 56, tzinfo=timezone.utc + ).timestamp(), + }, ) - with IbetShareContract_create, \ - TokenListContract_register, \ - ContractUtils_get_block_by_transaction_hash: + with ( + IbetShareContract_create + ), TokenListContract_register, ContractUtils_get_block_by_transaction_hash: # request target api req_param = { "name": "name_test1", "issue_price": 1000, "total_supply": 10000, - "principal_value": 1000 + "principal_value": 1000, } resp = client.post( self.apiurl, json=req_param, headers={ "issuer-address": test_account["address"], - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion IbetShareContract.create.assert_called_with( - args=[ - "name_test1", "", 1000, 10000, 0, - "", "", "", 1000 - ], + args=["name_test1", "", 1000, 10000, 0, "", "", "", 1000], tx_from=test_account["address"], - private_key=ANY + private_key=ANY, ) TokenListContract.register.assert_called_with( token_address="contract_address_test1", token_template=TokenType.IBET_SHARE.value, tx_from=test_account["address"], - private_key=ANY - ) - ContractUtils.get_block_by_transaction_hash( - tx_hash="tx_hash_test1" + private_key=ANY, ) + ContractUtils.get_block_by_transaction_hash(tx_hash="tx_hash_test1") assert resp.status_code == 200 assert resp.json()["token_address"] == "contract_address_test1" @@ -291,23 +289,25 @@ def test_normal_2(self, client, db): # mock IbetShareContract_create = patch( target="app.model.blockchain.token.IbetShareContract.create", - return_value=("contract_address_test1", "abi_test1", "tx_hash_test1") + return_value=("contract_address_test1", "abi_test1", "tx_hash_test1"), ) TokenListContract_register = patch( target="app.model.blockchain.token_list.TokenListContract.register", - return_value=None + return_value=None, ) ContractUtils_get_block_by_transaction_hash = patch( target="app.utils.contract_utils.ContractUtils.get_block_by_transaction_hash", return_value={ "number": 12345, - "timestamp": datetime(2021, 4, 27, 12, 34, 56, tzinfo=timezone.utc).timestamp() - } + "timestamp": datetime( + 2021, 4, 27, 12, 34, 56, tzinfo=timezone.utc + ).timestamp(), + }, ) - with IbetShareContract_create, \ - TokenListContract_register, \ - ContractUtils_get_block_by_transaction_hash: + with ( + IbetShareContract_create + ), TokenListContract_register, ContractUtils_get_block_by_transaction_hash: # request target api req_param = { "name": "name_test1", @@ -327,25 +327,32 @@ def test_normal_2(self, client, db): "privacy_policy": "privacy policy test", # update "transfer_approval_required": True, # update "principal_value": 1000, - "is_canceled": True + "is_canceled": True, } resp = client.post( self.apiurl, json=req_param, headers={ "issuer-address": test_account["address"], - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion IbetShareContract.create.assert_called_with( args=[ - "name_test1", "symbol_test1", 1000, 10000, 1234500000000000, - "20211231", "20211231", "20221231", 1000 + "name_test1", + "symbol_test1", + 1000, + 10000, + 1234500000000000, + "20211231", + "20211231", + "20221231", + 1000, ], tx_from=test_account["address"], - private_key=ANY + private_key=ANY, ) TokenListContract.register.assert_not_called() ContractUtils.get_block_by_transaction_hash.assert_not_called() @@ -404,23 +411,25 @@ def test_normal_3(self, client, db): # mock IbetShareContract_create = patch( target="app.model.blockchain.token.IbetShareContract.create", - return_value=("contract_address_test1", "abi_test1", "tx_hash_test1") + return_value=("contract_address_test1", "abi_test1", "tx_hash_test1"), ) TokenListContract_register = patch( target="app.model.blockchain.token_list.TokenListContract.register", - return_value=None + return_value=None, ) ContractUtils_get_block_by_transaction_hash = patch( target="app.utils.contract_utils.ContractUtils.get_block_by_transaction_hash", return_value={ "number": 12345, - "timestamp": datetime(2021, 4, 27, 12, 34, 56, tzinfo=timezone.utc).timestamp() - } + "timestamp": datetime( + 2021, 4, 27, 12, 34, 56, tzinfo=timezone.utc + ).timestamp(), + }, ) - with IbetShareContract_create, \ - TokenListContract_register, \ - ContractUtils_get_block_by_transaction_hash: + with ( + IbetShareContract_create + ), TokenListContract_register, ContractUtils_get_block_by_transaction_hash: # request target api req_param = { "name": "name_test1", @@ -431,35 +440,40 @@ def test_normal_3(self, client, db): "dividend_record_date": "20211231", "dividend_payment_date": "20211231", "cancellation_date": "20221231", - "principal_value": 1000 + "principal_value": 1000, } resp = client.post( self.apiurl, json=req_param, headers={ "issuer-address": test_account["address"], - "auth-token": "test_auth_token" - } + "auth-token": "test_auth_token", + }, ) # assertion IbetShareContract.create.assert_called_with( args=[ - "name_test1", "symbol_test1", 1000, 10000, 1234500000000000, - "20211231", "20211231", "20221231", 1000 + "name_test1", + "symbol_test1", + 1000, + 10000, + 1234500000000000, + "20211231", + "20211231", + "20221231", + 1000, ], tx_from=test_account["address"], - private_key=ANY + private_key=ANY, ) TokenListContract.register.assert_called_with( token_address="contract_address_test1", token_template=TokenType.IBET_SHARE.value, tx_from=test_account["address"], - private_key=ANY - ) - ContractUtils.get_block_by_transaction_hash( - tx_hash="tx_hash_test1" + private_key=ANY, ) + ContractUtils.get_block_by_transaction_hash(tx_hash="tx_hash_test1") assert resp.status_code == 200 assert resp.json()["token_address"] == "contract_address_test1" @@ -511,23 +525,25 @@ def test_normal_4_1(self, client, db): # mock IbetShareContract_create = patch( target="app.model.blockchain.token.IbetShareContract.create", - return_value=("contract_address_test1", "abi_test1", "tx_hash_test1") + return_value=("contract_address_test1", "abi_test1", "tx_hash_test1"), ) TokenListContract_register = patch( target="app.model.blockchain.token_list.TokenListContract.register", - return_value=None + return_value=None, ) ContractUtils_get_block_by_transaction_hash = patch( target="app.utils.contract_utils.ContractUtils.get_block_by_transaction_hash", return_value={ "number": 12345, - "timestamp": datetime(2021, 4, 27, 12, 34, 56, tzinfo=timezone.utc).timestamp() - } + "timestamp": datetime( + 2021, 4, 27, 12, 34, 56, tzinfo=timezone.utc + ).timestamp(), + }, ) - with IbetShareContract_create, \ - TokenListContract_register, \ - ContractUtils_get_block_by_transaction_hash: + with ( + IbetShareContract_create + ), TokenListContract_register, ContractUtils_get_block_by_transaction_hash: # request target api req_param = { "name": "name_test1", @@ -538,15 +554,15 @@ def test_normal_4_1(self, client, db): "dividend_record_date": "20211231", "dividend_payment_date": "20211231", "cancellation_date": "20221231", - "principal_value": 1000 + "principal_value": 1000, } resp = client.post( self.apiurl, json=req_param, headers={ "issuer-address": test_account["address"], - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion @@ -560,10 +576,10 @@ def test_normal_4_1(self, client, db): "20211231", "20211231", "20221231", - 1000 + 1000, ], tx_from=test_account["address"], - private_key=ANY + private_key=ANY, ) assert resp.status_code == 200 @@ -585,23 +601,25 @@ def test_normal_4_2(self, client, db): # mock IbetShareContract_create = patch( target="app.model.blockchain.token.IbetShareContract.create", - return_value=("contract_address_test1", "abi_test1", "tx_hash_test1") + return_value=("contract_address_test1", "abi_test1", "tx_hash_test1"), ) TokenListContract_register = patch( target="app.model.blockchain.token_list.TokenListContract.register", - return_value=None + return_value=None, ) ContractUtils_get_block_by_transaction_hash = patch( target="app.utils.contract_utils.ContractUtils.get_block_by_transaction_hash", return_value={ "number": 12345, - "timestamp": datetime(2021, 4, 27, 12, 34, 56, tzinfo=timezone.utc).timestamp() - } + "timestamp": datetime( + 2021, 4, 27, 12, 34, 56, tzinfo=timezone.utc + ).timestamp(), + }, ) - with IbetShareContract_create, \ - TokenListContract_register, \ - ContractUtils_get_block_by_transaction_hash: + with ( + IbetShareContract_create + ), TokenListContract_register, ContractUtils_get_block_by_transaction_hash: # request target api req_param = { "name": "name_test1", @@ -612,15 +630,15 @@ def test_normal_4_2(self, client, db): "dividend_record_date": "", "dividend_payment_date": "", "cancellation_date": "", - "principal_value": 1000 + "principal_value": 1000, } resp = client.post( self.apiurl, json=req_param, headers={ "issuer-address": test_account["address"], - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion @@ -634,10 +652,10 @@ def test_normal_4_2(self, client, db): "", "", "", - 1000 + 1000, ], tx_from=test_account["address"], - private_key=ANY + private_key=ANY, ) assert resp.status_code == 200 @@ -653,29 +671,24 @@ def test_normal_4_2(self, client, db): # missing fields def test_error_1(self, client, db): # request target api - resp = client.post( - self.apiurl - ) + resp = client.post(self.apiurl) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, { "loc": ["body"], "msg": "field required", - "type": "value_error.missing" - } - ] + "type": "value_error.missing", + }, + ], } # @@ -696,49 +709,35 @@ def test_error_2_1(self, client, db): "cancellation_date": "20221231", "tradable_exchange_contract_address": "0x0", "personal_info_contract_address": "0x0", - "principal_value": 1000 + "principal_value": 1000, } resp = client.post( self.apiurl, json=req_param, - headers={ - "issuer-address": test_account["address"] - } + headers={"issuer-address": test_account["address"]}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "loc": [ - "body", - "dividends" - ], + "loc": ["body", "dividends"], "msg": "dividends must be rounded to 13 decimal places", - "type": "value_error" + "type": "value_error", }, { - "loc": [ - "body", - "tradable_exchange_contract_address" - ], + "loc": ["body", "tradable_exchange_contract_address"], "msg": "tradable_exchange_contract_address is not a valid address", - "type": "value_error" + "type": "value_error", }, { - "loc": [ - "body", - "personal_info_contract_address" - ], + "loc": ["body", "personal_info_contract_address"], "msg": "personal_info_contract_address is not a valid address", - "type": "value_error" - } - ] + "type": "value_error", + }, + ], } # @@ -757,30 +756,23 @@ def test_error_2_2(self, client, db): "dividend_record_date": "20211231", "dividend_payment_date": "20211231", "cancellation_date": "20221231", - "principal_value": 1000 + "principal_value": 1000, } resp = client.post( - self.apiurl, - json=req_param, - headers={ - "issuer-address": "issuer-address" - } + self.apiurl, json=req_param, headers={"issuer-address": "issuer-address"} ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -806,29 +798,28 @@ def test_error_2_3(self, client, db): "dividend_record_date": "20211231", "dividend_payment_date": "20211231", "cancellation_date": "20221231", - "principal_value": 1000 + "principal_value": 1000, } resp = client.post( self.apiurl, json=req_param, headers={ "issuer-address": test_account_1["address"], - "eoa-password": "password" - } + "eoa-password": "password", + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, - "detail": [{ - "loc": ["header", "eoa-password"], - "msg": "eoa-password is not a Base64-encoded encrypted data", - "type": "value_error" - }] + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ + { + "loc": ["header", "eoa-password"], + "msg": "eoa-password is not a Base64-encoded encrypted data", + "type": "value_error", + } + ], } # @@ -856,69 +847,44 @@ def test_error_2_4(self, client, db): "privacy_policy": "privacy policy test", # update "transfer_approval_required": True, # update "principal_value": -1, - "is_canceled": True + "is_canceled": True, } resp = client.post( self.apiurl, json=req_param, - headers={ - "issuer-address": test_account["address"] - } + headers={"issuer-address": test_account["address"]}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "ctx": { - "limit_value": 0 - }, - "loc": [ - "body", - "issue_price" - ], + "ctx": {"limit_value": 0}, + "loc": ["body", "issue_price"], "msg": "ensure this value is greater than or equal to 0", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, { - "ctx": { - "limit_value": 0 - }, - "loc": [ - "body", - "principal_value" - ], + "ctx": {"limit_value": 0}, + "loc": ["body", "principal_value"], "msg": "ensure this value is greater than or equal to 0", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, { - "ctx": { - "limit_value": 0 - }, - "loc": [ - "body", - "total_supply" - ], + "ctx": {"limit_value": 0}, + "loc": ["body", "total_supply"], "msg": "ensure this value is greater than or equal to 0", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, { - "ctx": { - "limit_value": 0.0 - }, - "loc": [ - "body", - "dividends" - ], + "ctx": {"limit_value": 0.0}, + "loc": ["body", "dividends"], "msg": "ensure this value is greater than or equal to 0.0", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, - ] + ], } # @@ -946,73 +912,68 @@ def test_error_2_5(self, client, db): "privacy_policy": GetRandomStr(5001), # update "transfer_approval_required": True, # update "principal_value": 5_000_000_001, - "is_canceled": True + "is_canceled": True, } resp = client.post( self.apiurl, json=req_param, - headers={ - "issuer-address": test_account["address"] - } + headers={"issuer-address": test_account["address"]}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "name"], "msg": "ensure this value has at most 100 characters", "type": "value_error.any_str.max_length", - "ctx": {"limit_value": 100} + "ctx": {"limit_value": 100}, }, { "loc": ["body", "issue_price"], "msg": "ensure this value is less than or equal to 5000000000", "type": "value_error.number.not_le", - "ctx": {"limit_value": 5000000000} + "ctx": {"limit_value": 5000000000}, }, { "loc": ["body", "principal_value"], "msg": "ensure this value is less than or equal to 5000000000", "type": "value_error.number.not_le", - "ctx": {"limit_value": 5000000000} + "ctx": {"limit_value": 5000000000}, }, { "loc": ["body", "total_supply"], "msg": "ensure this value is less than or equal to 1000000000000", "type": "value_error.number.not_le", - "ctx": {"limit_value": 1000000000000} + "ctx": {"limit_value": 1000000000000}, }, { "loc": ["body", "symbol"], "msg": "ensure this value has at most 100 characters", "type": "value_error.any_str.max_length", - "ctx": {"limit_value": 100} + "ctx": {"limit_value": 100}, }, { "loc": ["body", "dividends"], "msg": "ensure this value is less than or equal to 5000000000.0", "type": "value_error.number.not_le", - "ctx": {"limit_value": 5000000000.0} + "ctx": {"limit_value": 5000000000.0}, }, { "loc": ["body", "contact_information"], "msg": "ensure this value has at most 2000 characters", "type": "value_error.any_str.max_length", - "ctx": {"limit_value": 2000} + "ctx": {"limit_value": 2000}, }, { "loc": ["body", "privacy_policy"], "msg": "ensure this value has at most 5000 characters", "type": "value_error.any_str.max_length", - "ctx": {"limit_value": 5000} - } - ] + "ctx": {"limit_value": 5000}, + }, + ], } # @@ -1031,61 +992,62 @@ def test_error_2_6(self, client, db): "dividend_record_date": "202101010", "dividend_payment_date": "202101010", "cancellation_date": "202201010", - "principal_value": 1000 + "principal_value": 1000, } resp = client.post( self.apiurl, json=req_param, - headers={ - "issuer-address": test_account["address"] - } + headers={"issuer-address": test_account["address"]}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - 'loc': ['body', 'dividend_record_date'], - 'msg': 'string does not match regex "^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$"', - 'type': 'value_error.str.regex', - 'ctx': {'pattern': '^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$'} + "loc": ["body", "dividend_record_date"], + "msg": 'string does not match regex "^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$"', + "type": "value_error.str.regex", + "ctx": { + "pattern": "^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$" + }, }, { - 'loc': ['body', 'dividend_record_date'], - 'msg': "unexpected value; permitted: ''", - 'type': 'value_error.const', - 'ctx': {'given': '202101010', 'permitted': ['']} + "loc": ["body", "dividend_record_date"], + "msg": "unexpected value; permitted: ''", + "type": "value_error.const", + "ctx": {"given": "202101010", "permitted": [""]}, }, { - 'loc': ['body', 'dividend_payment_date'], - 'msg': 'string does not match regex "^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$"', - 'type': 'value_error.str.regex', - 'ctx': {'pattern': '^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$'} + "loc": ["body", "dividend_payment_date"], + "msg": 'string does not match regex "^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$"', + "type": "value_error.str.regex", + "ctx": { + "pattern": "^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$" + }, }, { - 'loc': ['body', 'dividend_payment_date'], - 'msg': "unexpected value; permitted: ''", - 'type': 'value_error.const', - 'ctx': {'given': '202101010', 'permitted': ['']} + "loc": ["body", "dividend_payment_date"], + "msg": "unexpected value; permitted: ''", + "type": "value_error.const", + "ctx": {"given": "202101010", "permitted": [""]}, }, { - 'loc': ['body', 'cancellation_date'], - 'msg': 'string does not match regex "^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$"', - 'type': 'value_error.str.regex', - 'ctx': {'pattern': '^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$'} + "loc": ["body", "cancellation_date"], + "msg": 'string does not match regex "^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$"', + "type": "value_error.str.regex", + "ctx": { + "pattern": "^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$" + }, }, { - 'loc': ['body', 'cancellation_date'], - 'msg': "unexpected value; permitted: ''", - 'type': 'value_error.const', - 'ctx': {'given': '202201010', 'permitted': ['']} - } - ] + "loc": ["body", "cancellation_date"], + "msg": "unexpected value; permitted: ''", + "type": "value_error.const", + "ctx": {"given": "202201010", "permitted": [""]}, + }, + ], } # @@ -1111,25 +1073,22 @@ def test_error_3_1(self, client, db): "dividend_record_date": "20211231", "dividend_payment_date": "20211231", "cancellation_date": "20221231", - "principal_value": 1000 + "principal_value": 1000, } resp = client.post( self.apiurl, json=req_param, headers={ "issuer-address": test_account_2["address"], - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -1155,25 +1114,22 @@ def test_error_3_2(self, client, db): "dividend_record_date": "20211231", "dividend_payment_date": "20211231", "cancellation_date": "20221231", - "principal_value": 1000 + "principal_value": 1000, } resp = client.post( self.apiurl, json=req_param, headers={ "issuer-address": test_account_1["address"], - "eoa-password": E2EEUtils.encrypt("password_test") - } + "eoa-password": E2EEUtils.encrypt("password_test"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -1193,7 +1149,7 @@ def test_error_4_1(self, client, db): # mock IbetShareContract_create = patch( target="app.model.blockchain.token.IbetShareContract.create", - side_effect=SendTransactionError() + side_effect=SendTransactionError(), ) with IbetShareContract_create: @@ -1207,25 +1163,22 @@ def test_error_4_1(self, client, db): "dividend_record_date": "20211231", "dividend_payment_date": "20211231", "cancellation_date": "20221231", - "principal_value": 1000 + "principal_value": 1000, } resp = client.post( self.apiurl, json=req_param, headers={ "issuer-address": test_account_1["address"], - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 2, - "title": "SendTransactionError" - }, - "detail": "failed to send transaction" + "meta": {"code": 2, "title": "SendTransactionError"}, + "detail": "failed to send transaction", } # @@ -1245,15 +1198,14 @@ def test_error_5(self, client, db): # mock IbetShareContract_create = patch( target="app.model.blockchain.token.IbetShareContract.create", - return_value=("contract_address_test1", "abi_test1", "tx_hash_test1") + return_value=("contract_address_test1", "abi_test1", "tx_hash_test1"), ) TokenListContract_register = patch( target="app.model.blockchain.token_list.TokenListContract.register", - side_effect=SendTransactionError() + side_effect=SendTransactionError(), ) - with IbetShareContract_create, \ - TokenListContract_register: + with IbetShareContract_create, TokenListContract_register: # request target api req_param = { "name": "name_test1", @@ -1271,21 +1223,18 @@ def test_error_5(self, client, db): json=req_param, headers={ "issuer-address": test_account_1["address"], - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 2, - "title": "SendTransactionError" - }, - "detail": "failed to register token address token list" + "meta": {"code": 2, "title": "SendTransactionError"}, + "detail": "failed to register token address token list", } def GetRandomStr(num): dat = string.digits + string.ascii_lowercase + string.ascii_uppercase - return ''.join([random.choice(dat) for i in range(num)]) + return "".join([random.choice(dat) for i in range(num)]) diff --git a/tests/test_app_routers_share_tokens_{token_address}_GET.py b/tests/test_app_routers_share_tokens_{token_address}_GET.py index add693c0..904f741a 100644 --- a/tests/test_app_routers_share_tokens_{token_address}_GET.py +++ b/tests/test_app_routers_share_tokens_{token_address}_GET.py @@ -17,14 +17,12 @@ SPDX-License-Identifier: Apache-2.0 """ from unittest import mock + from pytz import timezone -from config import TZ from app.model.blockchain import IbetShareContract -from app.model.db import ( - Token, - TokenType -) +from app.model.db import Token, TokenType +from config import TZ class TestAppRoutersShareTokensTokenAddressGET: @@ -49,7 +47,12 @@ def test_normal_1(self, mock_get, client, db): token.abi = "abi_test1" db.add(token) db.commit() - _issue_time = timezone("UTC").localize(token.created).astimezone(self.local_tz).isoformat() + _issue_time = ( + timezone("UTC") + .localize(token.created) + .astimezone(self.local_tz) + .isoformat() + ) # request target API mock_token = IbetShareContract() @@ -60,7 +63,9 @@ def test_normal_1(self, mock_get, client, db): mock_token.total_supply = 10000 mock_token.contact_information = "contactInformation_test1" mock_token.privacy_policy = "privacyPolicy_test1" - mock_token.tradable_exchange_contract_address = "0x1234567890abCdFe1234567890ABCdFE12345678" + mock_token.tradable_exchange_contract_address = ( + "0x1234567890abCdFe1234567890ABCdFE12345678" + ) mock_token.status = True mock_token.issue_price = 1000 mock_token.dividends = 123.45 @@ -69,7 +74,9 @@ def test_normal_1(self, mock_get, client, db): mock_token.cancellation_date = "20221231" mock_token.transferable = True mock_token.is_offering = True - mock_token.personal_info_contract_address = "0x1234567890aBcDFE1234567890abcDFE12345679" + mock_token.personal_info_contract_address = ( + "0x1234567890aBcDFE1234567890abcDFE12345679" + ) mock_token.principal_value = 1000 mock_token.transfer_approval_required = False mock_token.is_canceled = False @@ -121,7 +128,12 @@ def test_normal_2(self, mock_get, client, db): token.abi = "abi_test1" db.add(token) db.commit() - _issue_time = timezone("UTC").localize(token.created).astimezone(self.local_tz).isoformat() + _issue_time = ( + timezone("UTC") + .localize(token.created) + .astimezone(self.local_tz) + .isoformat() + ) # request target API mock_token = IbetShareContract() @@ -132,7 +144,9 @@ def test_normal_2(self, mock_get, client, db): mock_token.total_supply = 10000 mock_token.contact_information = "contactInformation_test1" mock_token.privacy_policy = "privacyPolicy_test1" - mock_token.tradable_exchange_contract_address = "0x1234567890abCdFe1234567890ABCdFE12345678" + mock_token.tradable_exchange_contract_address = ( + "0x1234567890abCdFe1234567890ABCdFE12345678" + ) mock_token.status = True mock_token.issue_price = 1000 mock_token.dividends = 123.45 @@ -141,7 +155,9 @@ def test_normal_2(self, mock_get, client, db): mock_token.cancellation_date = "20221231" mock_token.transferable = True mock_token.is_offering = True - mock_token.personal_info_contract_address = "0x1234567890aBcDFE1234567890abcDFE12345679" + mock_token.personal_info_contract_address = ( + "0x1234567890aBcDFE1234567890abcDFE12345679" + ) mock_token.principal_value = 1000 mock_token.transfer_approval_required = False mock_token.is_canceled = False @@ -191,11 +207,8 @@ def test_error_1(self, client, db): assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # @@ -215,9 +228,6 @@ def test_error_2(self, client, db): assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } diff --git a/tests/test_app_routers_share_tokens_{token_address}_POST.py b/tests/test_app_routers_share_tokens_{token_address}_POST.py index 0ba1aea7..4ca0cad6 100644 --- a/tests/test_app_routers_share_tokens_{token_address}_POST.py +++ b/tests/test_app_routers_share_tokens_{token_address}_POST.py @@ -18,22 +18,14 @@ """ import hashlib from unittest import mock -from unittest.mock import ( - MagicMock, - ANY -) +from unittest.mock import ANY, MagicMock from web3 import Web3 from web3.middleware import geth_poa_middleware import config from app.exceptions import SendTransactionError -from app.model.db import ( - Account, - AuthToken, - Token, - TokenType -) +from app.model.db import Account, AuthToken, Token, TokenType from app.utils.e2ee_utils import E2EEUtils from tests.account_config import config_eth_account @@ -91,22 +83,20 @@ def test_normal_1(self, IbetShareContract_mock, client, db): "transfer_approval_required": False, "principal_value": 1000, "is_canceled": True, - "memo": "m" * 10000 + "memo": "m" * 10000, } resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion IbetShareContract_mock.assert_any_call( - data=req_param, - tx_from=_issuer_address, - private_key=ANY + data=req_param, tx_from=_issuer_address, private_key=ANY ) assert resp.status_code == 200 assert resp.json() is None @@ -145,8 +135,8 @@ def test_normal_2(self, IbetShareContract_mock, client, db): json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion @@ -202,22 +192,20 @@ def test_normal_3(self, IbetShareContract_mock, client, db): "transfer_approval_required": False, "principal_value": 1000, "is_canceled": True, - "memo": "memo_test1" + "memo": "memo_test1", } resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "auth-token": "test_auth_token" - } + "auth-token": "test_auth_token", + }, ) # assertion IbetShareContract_mock.assert_any_call( - data=req_param, - tx_from=_issuer_address, - private_key=ANY + data=req_param, tx_from=_issuer_address, private_key=ANY ) assert resp.status_code == 200 assert resp.json() is None @@ -254,15 +242,15 @@ def test_normal_4_1(self, IbetShareContract_mock, client, db): "cancellation_date": "20221231", "dividends": 345.67, "dividend_record_date": "20211231", - "dividend_payment_date": "20211231" + "dividend_payment_date": "20211231", } resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion @@ -282,10 +270,10 @@ def test_normal_4_1(self, IbetShareContract_mock, client, db): "transfer_approval_required": None, "principal_value": None, "is_canceled": None, - "memo": None + "memo": None, }, tx_from=_issuer_address, - private_key=ANY + private_key=ANY, ) assert resp.status_code == 200 assert resp.json() is None @@ -322,15 +310,15 @@ def test_normal_4_2(self, IbetShareContract_mock, client, db): "cancellation_date": "", "dividends": 345.67, "dividend_record_date": "", - "dividend_payment_date": "" + "dividend_payment_date": "", } resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion @@ -350,10 +338,10 @@ def test_normal_4_2(self, IbetShareContract_mock, client, db): "transfer_approval_required": None, "principal_value": None, "is_canceled": None, - "memo": None + "memo": None, }, tx_from=_issuer_address, - private_key=ANY + private_key=ANY, ) assert resp.status_code == 200 assert resp.json() is None @@ -376,27 +364,19 @@ def test_error_1(self, client, db): resp = client.post( self.base_url.format(_token_address), json=req_param, - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "loc": [ - "body", - "dividends" - ], + "loc": ["body", "dividends"], "msg": "dividends must be rounded to 13 decimal places", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -413,27 +393,19 @@ def test_error_2(self, client, db): resp = client.post( self.base_url.format(_token_address), json=req_param, - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "loc": [ - "body", - "dividends" - ], + "loc": ["body", "dividends"], "msg": "all items are required to update the dividend information", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -444,33 +416,23 @@ def test_error_3(self, client, db): _token_address = "0x82b1c9374aB625380bd498a3d9dF4033B8A0E3Bb" # request target API - req_param = { - "tradable_exchange_contract_address": "invalid_address" - } + req_param = {"tradable_exchange_contract_address": "invalid_address"} resp = client.post( self.base_url.format(_token_address), json=req_param, - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "loc": [ - "body", - "tradable_exchange_contract_address" - ], + "loc": ["body", "tradable_exchange_contract_address"], "msg": "tradable_exchange_contract_address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -481,33 +443,23 @@ def test_error_4(self, client, db): _token_address = "0x82b1c9374aB625380bd498a3d9dF4033B8A0E3Bb" # request target API - req_param = { - "personal_info_contract_address": "invalid_address" - } + req_param = {"personal_info_contract_address": "invalid_address"} resp = client.post( self.base_url.format(_token_address), json=req_param, - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "loc": [ - "body", - "personal_info_contract_address" - ], + "loc": ["body", "personal_info_contract_address"], "msg": "personal_info_contract_address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -516,28 +468,23 @@ def test_error_6(self, client, db): _token_address = "0x82b1c9374aB625380bd498a3d9dF4033B8A0E3Bb" # request target API - resp = client.post( - self.base_url.format(_token_address) - ) + resp = client.post(self.base_url.format(_token_address)) assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, { "loc": ["body"], "msg": "field required", - "type": "value_error.missing" - } - ] + "type": "value_error.missing", + }, + ], } # @@ -552,25 +499,20 @@ def test_error_7(self, client, db): resp = client.post( self.base_url.format(_token_address), json=req_param, - headers={ - "issuer-address": "issuer_address" - } + headers={"issuer-address": "issuer_address"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -585,24 +527,20 @@ def test_error_8(self, client, db): resp = client.post( self.base_url.format(_token_address), json=req_param, - headers={ - "issuer-address": _issuer_address, - "eoa-password": "password" - } + headers={"issuer-address": _issuer_address, "eoa-password": "password"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, - "detail": [{ - "loc": ["header", "eoa-password"], - "msg": "eoa-password is not a Base64-encoded encrypted data", - "type": "value_error" - }] + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ + { + "loc": ["header", "eoa-password"], + "msg": "eoa-password is not a Base64-encoded encrypted data", + "type": "value_error", + } + ], } # @@ -628,48 +566,32 @@ def test_error_9(self, client, db): "transfer_approval_required": False, "principal_value": -1, "is_canceled": True, - "memo": "memo_test1" + "memo": "memo_test1", } resp = client.post( self.base_url.format(_token_address), json=req_param, - headers={ - "issuer-address": _issuer_address, - "eoa-password": "password" - } + headers={"issuer-address": _issuer_address, "eoa-password": "password"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "ctx": { - "limit_value": 0.0 - }, - "loc": [ - "body", - "dividends" - ], + "ctx": {"limit_value": 0.0}, + "loc": ["body", "dividends"], "msg": "ensure this value is greater than or equal to 0.0", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, { - "ctx": { - "limit_value": 0 - }, - "loc": [ - "body", - "principal_value" - ], + "ctx": {"limit_value": 0}, + "loc": ["body", "principal_value"], "msg": "ensure this value is greater than or equal to 0", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, - ] + ], } # @@ -695,48 +617,32 @@ def test_error_10(self, client, db): "transfer_approval_required": False, "principal_value": 5_000_000_001, "is_canceled": True, - "memo": "memo_test1" + "memo": "memo_test1", } resp = client.post( self.base_url.format(_token_address), json=req_param, - headers={ - "issuer-address": _issuer_address, - "eoa-password": "password" - } + headers={"issuer-address": _issuer_address, "eoa-password": "password"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "ctx": { - "limit_value": 5_000_000_000.00 - }, - "loc": [ - "body", - "dividends" - ], + "ctx": {"limit_value": 5_000_000_000.00}, + "loc": ["body", "dividends"], "msg": "ensure this value is less than or equal to 5000000000.0", - "type": "value_error.number.not_le" + "type": "value_error.number.not_le", }, { - "ctx": { - "limit_value": 5_000_000_000 - }, - "loc": [ - "body", - "principal_value" - ], + "ctx": {"limit_value": 5_000_000_000}, + "loc": ["body", "principal_value"], "msg": "ensure this value is less than or equal to 5000000000", - "type": "value_error.number.not_le" + "type": "value_error.number.not_le", }, - ] + ], } # @@ -751,60 +657,61 @@ def test_error_11(self, client, db): req_param = { "cancellation_date": "202112310", "dividend_record_date": "202112310", - "dividend_payment_date": "202112310" + "dividend_payment_date": "202112310", } resp = client.post( self.base_url.format(_token_address), json=req_param, - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - 'loc': ['body', 'cancellation_date'], - 'msg': 'string does not match regex "^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$"', - 'type': 'value_error.str.regex', - 'ctx': {'pattern': '^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$'} + "loc": ["body", "cancellation_date"], + "msg": 'string does not match regex "^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$"', + "type": "value_error.str.regex", + "ctx": { + "pattern": "^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$" + }, }, { - 'loc': ['body', 'cancellation_date'], - 'msg': "unexpected value; permitted: ''", - 'type': 'value_error.const', - 'ctx': {'given': '202112310', 'permitted': ['']} + "loc": ["body", "cancellation_date"], + "msg": "unexpected value; permitted: ''", + "type": "value_error.const", + "ctx": {"given": "202112310", "permitted": [""]}, }, { - 'loc': ['body', 'dividend_record_date'], - 'msg': 'string does not match regex "^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$"', - 'type': 'value_error.str.regex', - 'ctx': {'pattern': '^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$'} + "loc": ["body", "dividend_record_date"], + "msg": 'string does not match regex "^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$"', + "type": "value_error.str.regex", + "ctx": { + "pattern": "^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$" + }, }, { - 'loc': ['body', 'dividend_record_date'], - 'msg': "unexpected value; permitted: ''", - 'type': 'value_error.const', - 'ctx': {'given': '202112310', 'permitted': ['']} + "loc": ["body", "dividend_record_date"], + "msg": "unexpected value; permitted: ''", + "type": "value_error.const", + "ctx": {"given": "202112310", "permitted": [""]}, }, { - 'loc': ['body', 'dividend_payment_date'], - 'msg': 'string does not match regex "^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$"', - 'type': 'value_error.str.regex', - 'ctx': {'pattern': '^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$'} + "loc": ["body", "dividend_payment_date"], + "msg": 'string does not match regex "^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$"', + "type": "value_error.str.regex", + "ctx": { + "pattern": "^(19[0-9]{2}|20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$" + }, }, { - 'loc': ['body', 'dividend_payment_date'], - 'msg': "unexpected value; permitted: ''", - 'type': 'value_error.const', - 'ctx': {'given': '202112310', 'permitted': ['']} - } - ] + "loc": ["body", "dividend_payment_date"], + "msg": "unexpected value; permitted: ''", + "type": "value_error.const", + "ctx": {"given": "202112310", "permitted": [""]}, + }, + ], } # @@ -834,18 +741,15 @@ def test_error_12(self, IbetShareContract_mock, client, db): json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -874,18 +778,15 @@ def test_error_13(self, IbetShareContract_mock, client, db): json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password_test") - } + "eoa-password": E2EEUtils.encrypt("password_test"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -914,18 +815,15 @@ def test_error_14(self, IbetShareContract_mock, client, db): json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # @@ -959,24 +857,23 @@ def test_error_15(self, client, db): json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } # # Send Transaction Error - @mock.patch("app.model.blockchain.token.IbetShareContract.update", - MagicMock(side_effect=SendTransactionError())) + @mock.patch( + "app.model.blockchain.token.IbetShareContract.update", + MagicMock(side_effect=SendTransactionError()), + ) def test_error_16(self, client, db): test_account = config_eth_account("user1") _issuer_address = test_account["address"] @@ -1005,16 +902,13 @@ def test_error_16(self, client, db): json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 2, - "title": "SendTransactionError" - }, - "detail": "failed to send transaction" + "meta": {"code": 2, "title": "SendTransactionError"}, + "detail": "failed to send transaction", } diff --git a/tests/test_app_routers_share_tokens_{token_address}_additional_issue_GET.py b/tests/test_app_routers_share_tokens_{token_address}_additional_issue_GET.py index ed41d989..a673020c 100644 --- a/tests/test_app_routers_share_tokens_{token_address}_additional_issue_GET.py +++ b/tests/test_app_routers_share_tokens_{token_address}_additional_issue_GET.py @@ -22,17 +22,17 @@ import config from app.model.db import ( + IDXIssueRedeem, + IDXIssueRedeemEventType, + IDXIssueRedeemSortItem, Token, TokenType, - IDXIssueRedeem, - IDXIssueRedeemEventType, IDXIssueRedeemSortItem ) local_tz = timezone(config.TZ) class TestAppRoutersShareTokensTokenAddressAdditionalIssueGET: - # target API endpoint base_url = "/share/tokens/{}/additional_issue" @@ -48,9 +48,9 @@ class TestAppRoutersShareTokensTokenAddressAdditionalIssueGET: test_amount = [10, 20, 30] test_block_timestamp = [ - datetime.strptime("2022/01/02 15:20:30", '%Y/%m/%d %H:%M:%S'), # JST 2022/01/03 - datetime.strptime("2022/01/01 15:20:30", '%Y/%m/%d %H:%M:%S'), # JST 2022/01/02 - datetime.strptime("2022/01/02 00:20:30", '%Y/%m/%d %H:%M:%S'), # JST 2022/01/02 + datetime.strptime("2022/01/02 15:20:30", "%Y/%m/%d %H:%M:%S"), # JST 2022/01/03 + datetime.strptime("2022/01/01 15:20:30", "%Y/%m/%d %H:%M:%S"), # JST 2022/01/02 + datetime.strptime("2022/01/02 00:20:30", "%Y/%m/%d %H:%M:%S"), # JST 2022/01/02 ] test_block_timestamp_str = [ "2022-01-03T00:20:30+09:00", @@ -86,20 +86,13 @@ def test_normal_1(self, client, db): db.add(_record) # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 0, - 'offset': None, - 'limit': None, - 'total': 0 - }, - 'history': [] + "result_set": {"count": 0, "offset": None, "limit": None, "total": 0}, + "history": [], } # Normal_2 @@ -146,45 +139,38 @@ def test_normal_2(self, client, db): db.add(_record) # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 3, - 'offset': None, - 'limit': None, - 'total': 3 - }, - 'history': [ + "result_set": {"count": 3, "offset": None, "limit": None, "total": 3}, + "history": [ { - 'transaction_hash': self.test_transaction_hash, - 'token_address': self.test_token_address, - 'locked_address': self.test_locked_address, - 'target_address': self.test_target_address, - 'amount': self.test_amount[0], - 'block_timestamp': self.test_block_timestamp_str[0] + "transaction_hash": self.test_transaction_hash, + "token_address": self.test_token_address, + "locked_address": self.test_locked_address, + "target_address": self.test_target_address, + "amount": self.test_amount[0], + "block_timestamp": self.test_block_timestamp_str[0], }, { - 'transaction_hash': self.test_transaction_hash, - 'token_address': self.test_token_address, - 'locked_address': self.test_locked_address, - 'target_address': self.test_target_address, - 'amount': self.test_amount[2], - 'block_timestamp': self.test_block_timestamp_str[2] + "transaction_hash": self.test_transaction_hash, + "token_address": self.test_token_address, + "locked_address": self.test_locked_address, + "target_address": self.test_target_address, + "amount": self.test_amount[2], + "block_timestamp": self.test_block_timestamp_str[2], }, { - 'transaction_hash': self.test_transaction_hash, - 'token_address': self.test_token_address, - 'locked_address': self.test_locked_address, - 'target_address': self.test_target_address, - 'amount': self.test_amount[1], - 'block_timestamp': self.test_block_timestamp_str[1] - } - ] + "transaction_hash": self.test_transaction_hash, + "token_address": self.test_token_address, + "locked_address": self.test_locked_address, + "target_address": self.test_target_address, + "amount": self.test_amount[1], + "block_timestamp": self.test_block_timestamp_str[1], + }, + ], } # Normal_3 @@ -235,45 +221,40 @@ def test_normal_3(self, client, db): self.base_url.format(self.test_token_address), params={ "sort_item": IDXIssueRedeemSortItem.BLOCK_TIMESTAMP.value, - "sort_order": 0 - } + "sort_order": 0, + }, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 3, - 'offset': None, - 'limit': None, - 'total': 3 - }, - 'history': [ + "result_set": {"count": 3, "offset": None, "limit": None, "total": 3}, + "history": [ { - 'transaction_hash': self.test_transaction_hash, - 'token_address': self.test_token_address, - 'locked_address': self.test_locked_address, - 'target_address': self.test_target_address, - 'amount': self.test_amount[1], - 'block_timestamp': self.test_block_timestamp_str[1] + "transaction_hash": self.test_transaction_hash, + "token_address": self.test_token_address, + "locked_address": self.test_locked_address, + "target_address": self.test_target_address, + "amount": self.test_amount[1], + "block_timestamp": self.test_block_timestamp_str[1], }, { - 'transaction_hash': self.test_transaction_hash, - 'token_address': self.test_token_address, - 'locked_address': self.test_locked_address, - 'target_address': self.test_target_address, - 'amount': self.test_amount[2], - 'block_timestamp': self.test_block_timestamp_str[2] + "transaction_hash": self.test_transaction_hash, + "token_address": self.test_token_address, + "locked_address": self.test_locked_address, + "target_address": self.test_target_address, + "amount": self.test_amount[2], + "block_timestamp": self.test_block_timestamp_str[2], }, { - 'transaction_hash': self.test_transaction_hash, - 'token_address': self.test_token_address, - 'locked_address': self.test_locked_address, - 'target_address': self.test_target_address, - 'amount': self.test_amount[0], - 'block_timestamp': self.test_block_timestamp_str[0] - } - ] + "transaction_hash": self.test_transaction_hash, + "token_address": self.test_token_address, + "locked_address": self.test_locked_address, + "target_address": self.test_target_address, + "amount": self.test_amount[0], + "block_timestamp": self.test_block_timestamp_str[0], + }, + ], } # Normal_4 @@ -322,31 +303,23 @@ def test_normal_4(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "offset": 1, - "limit": 1 - } + params={"offset": 1, "limit": 1}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 3, - 'offset': 1, - 'limit': 1, - 'total': 3 - }, - 'history': [ + "result_set": {"count": 3, "offset": 1, "limit": 1, "total": 3}, + "history": [ { - 'transaction_hash': self.test_transaction_hash, - 'token_address': self.test_token_address, - 'locked_address': self.test_locked_address, - 'target_address': self.test_target_address, - 'amount': self.test_amount[2], - 'block_timestamp': self.test_block_timestamp_str[2] + "transaction_hash": self.test_transaction_hash, + "token_address": self.test_token_address, + "locked_address": self.test_locked_address, + "target_address": self.test_target_address, + "amount": self.test_amount[2], + "block_timestamp": self.test_block_timestamp_str[2], } - ] + ], } ########################################################################### @@ -357,18 +330,13 @@ def test_normal_4(self, client, db): # NotFound def test_error_1(self, client, db): # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # Error_2 @@ -386,18 +354,13 @@ def test_error_2(self, client, db): db.add(_token) # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } # Error_3 @@ -407,33 +370,28 @@ def test_error_3(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "sort_item": "block_timestamp12345" - } + params={"sort_item": "block_timestamp12345"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['query', 'sort_item'], - 'msg': "value is not a valid enumeration member; permitted: 'block_timestamp', 'locked_address', 'target_address', 'amount'", - 'type': 'type_error.enum', - 'ctx': { - 'enum_values': [ - 'block_timestamp', - 'locked_address', - 'target_address', - 'amount' + "loc": ["query", "sort_item"], + "msg": "value is not a valid enumeration member; permitted: 'block_timestamp', 'locked_address', 'target_address', 'amount'", + "type": "type_error.enum", + "ctx": { + "enum_values": [ + "block_timestamp", + "locked_address", + "target_address", + "amount", ] - } + }, } - ] + ], } # Error_4_1 @@ -442,27 +400,21 @@ def test_error_3(self, client, db): def test_error_4_1(self, client, db): # request target API resp = client.get( - self.base_url.format(self.test_token_address), - params={ - "sort_order": -1 - } + self.base_url.format(self.test_token_address), params={"sort_order": -1} ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "ctx": {"limit_value": 0}, "loc": ["query", "sort_order"], "msg": "ensure this value is greater than or equal to 0", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", } - ] + ], } # Error_4_2 @@ -471,25 +423,19 @@ def test_error_4_1(self, client, db): def test_error_4_2(self, client, db): # request target API resp = client.get( - self.base_url.format(self.test_token_address), - params={ - "sort_order": 2 - } + self.base_url.format(self.test_token_address), params={"sort_order": 2} ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "ctx": {"limit_value": 1}, "loc": ["query", "sort_order"], "msg": "ensure this value is less than or equal to 1", - "type": "value_error.number.not_le" + "type": "value_error.number.not_le", } - ] + ], } diff --git a/tests/test_app_routers_share_tokens_{token_address}_additional_issue_POST.py b/tests/test_app_routers_share_tokens_{token_address}_additional_issue_POST.py index 18f8c793..b5ff35db 100644 --- a/tests/test_app_routers_share_tokens_{token_address}_additional_issue_POST.py +++ b/tests/test_app_routers_share_tokens_{token_address}_additional_issue_POST.py @@ -20,14 +20,9 @@ from unittest import mock from unittest.mock import ANY, MagicMock -from app.model.db import ( - Account, - AuthToken, - Token, - TokenType -) -from app.utils.e2ee_utils import E2EEUtils from app.exceptions import SendTransactionError +from app.model.db import Account, AuthToken, Token, TokenType +from app.utils.e2ee_utils import E2EEUtils from tests.account_config import config_eth_account @@ -67,24 +62,19 @@ def test_normal_1(self, IbetShareContract_mock, client, db): IbetShareContract_mock.side_effect = [None] # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion IbetShareContract_mock.assert_any_call( - data=req_param, - tx_from=_issuer_address, - private_key=ANY + data=req_param, tx_from=_issuer_address, private_key=ANY ) assert resp.status_code == 200 @@ -124,24 +114,19 @@ def test_normal_2(self, IbetShareContract_mock, client, db): IbetShareContract_mock.side_effect = [None] # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "auth-token": "test_auth_token" - } + "auth-token": "test_auth_token", + }, ) # assertion IbetShareContract_mock.assert_any_call( - data=req_param, - tx_from=_issuer_address, - private_key=ANY + data=req_param, tx_from=_issuer_address, private_key=ANY ) assert resp.status_code == 200 @@ -157,29 +142,24 @@ def test_error_1(self, client, db): _token_address = "token_address_test" # request target API - resp = client.post( - self.base_url.format(_token_address) - ) + resp = client.post(self.base_url.format(_token_address)) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, { "loc": ["body"], "msg": "field required", - "type": "value_error.missing" - } - ] + "type": "value_error.missing", + }, + ], } # @@ -190,43 +170,30 @@ def test_error_2(self, client, db): _token_address = "token_address_test" # request target API - req_param = { - "account_address": "0x0", - "amount": 0 - } + req_param = {"account_address": "0x0", "amount": 0} resp = client.post( self.base_url.format(_token_address), json=req_param, - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "account_address"], "msg": "account_address is not a valid address", - "type": "value_error" + "type": "value_error", }, { - "ctx": { - "limit_value": 1 - }, - "loc": [ - "body", - "amount" - ], + "ctx": {"limit_value": 1}, + "loc": ["body", "amount"], "msg": "ensure this value is greater than or equal to 1", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, - ] + ], } # @@ -237,38 +204,25 @@ def test_error_3(self, client, db): _token_address = "token_address_test" # request target API - req_param = { - "account_address": _issuer_address, - "amount": 1_000_000_000_001 - } + req_param = {"account_address": _issuer_address, "amount": 1_000_000_000_001} resp = client.post( self.base_url.format(_token_address), json=req_param, - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "ctx": { - "limit_value": 1_000_000_000_000 - }, - "loc": [ - "body", - "amount" - ], + "ctx": {"limit_value": 1_000_000_000_000}, + "loc": ["body", "amount"], "msg": "ensure this value is less than or equal to 1000000000000", - "type": "value_error.number.not_le" + "type": "value_error.number.not_le", }, - ] + ], } # @@ -279,32 +233,24 @@ def test_error_4(self, client, db): _token_address = "token_address_test" # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, - headers={ - "issuer-address": "issuer-address" - } + headers={"issuer-address": "issuer-address"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -325,32 +271,25 @@ def test_error_5(self, client, db): db.add(token) # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, - headers={ - "issuer-address": _issuer_address, - "eoa-password": "password" - } + headers={"issuer-address": _issuer_address, "eoa-password": "password"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, - "detail": [{ - "loc": ["header", "eoa-password"], - "msg": "eoa-password is not a Base64-encoded encrypted data", - "type": "value_error" - }] + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ + { + "loc": ["header", "eoa-password"], + "msg": "eoa-password is not a Base64-encoded encrypted data", + "type": "value_error", + } + ], } # @@ -371,28 +310,22 @@ def test_error_6(self, client, db): db.add(token) # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -411,26 +344,20 @@ def test_error_7(self, client, db): db.add(account) # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password_test") - } + "eoa-password": E2EEUtils.encrypt("password_test"), + }, ) assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -449,26 +376,20 @@ def test_error_8(self, client, db): db.add(account) # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # @@ -496,33 +417,29 @@ def test_error_9(self, client, db): db.add(token) # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } # # Send Transaction Error - @mock.patch("app.model.blockchain.token.IbetShareContract.additional_issue", - MagicMock(side_effect=SendTransactionError())) + @mock.patch( + "app.model.blockchain.token.IbetShareContract.additional_issue", + MagicMock(side_effect=SendTransactionError()), + ) def test_error_10(self, client, db): test_account = config_eth_account("user1") _issuer_address = test_account["address"] @@ -545,25 +462,19 @@ def test_error_10(self, client, db): db.add(token) # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 2, - "title": "SendTransactionError" - }, - "detail": "failed to send transaction" + "meta": {"code": 2, "title": "SendTransactionError"}, + "detail": "failed to send transaction", } diff --git a/tests/test_app_routers_share_tokens_{token_address}_additional_issue_batch_GET.py b/tests/test_app_routers_share_tokens_{token_address}_additional_issue_batch_GET.py index 1501d2d8..b3b62e2d 100644 --- a/tests/test_app_routers_share_tokens_{token_address}_additional_issue_batch_GET.py +++ b/tests/test_app_routers_share_tokens_{token_address}_additional_issue_batch_GET.py @@ -20,10 +20,10 @@ from unittest import mock from app.model.db import ( + BatchIssueRedeemProcessingCategory, + BatchIssueRedeemUpload, Token, TokenType, - BatchIssueRedeemUpload, - BatchIssueRedeemProcessingCategory ) from tests.account_config import config_eth_account @@ -53,21 +53,13 @@ def test_normal_1(self, client, db): db.add(token) # request target API - resp = client.get( - self.base_url.format(token_address), - headers={} - ) + resp = client.get(self.base_url.format(token_address), headers={}) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 0, - "limit": None, - "offset": None, - "total": 0 - }, - "uploads": [] - } + "result_set": {"count": 0, "limit": None, "offset": None, "total": 0}, + "uploads": [], + } # # 1 record @@ -90,35 +82,28 @@ def test_normal_2(self, client, db): additional_issue_upload1.token_address = token_address additional_issue_upload1.issuer_address = issuer_address additional_issue_upload1.token_type = TokenType.IBET_SHARE.value - additional_issue_upload1.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload1.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload1.processed = False db.add(additional_issue_upload1) # request target API - resp = client.get( - self.base_url.format(token_address), - headers={} - ) + resp = client.get(self.base_url.format(token_address), headers={}) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 1, - "limit": None, - "offset": None, - "total": 1 - }, - "uploads": - [ + "result_set": {"count": 1, "limit": None, "offset": None, "total": 1}, + "uploads": [ { "issuer_address": issuer_address, "processed": False, "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, } - ] + ], } # @@ -143,7 +128,9 @@ def test_normal_3_1(self, client, db): additional_issue_upload1.token_address = token_address additional_issue_upload1.issuer_address = issuer_address additional_issue_upload1.token_type = TokenType.IBET_SHARE.value - additional_issue_upload1.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload1.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload1.processed = True db.add(additional_issue_upload1) @@ -152,7 +139,9 @@ def test_normal_3_1(self, client, db): additional_issue_upload2.token_address = token_address additional_issue_upload2.issuer_address = issuer_address additional_issue_upload2.token_type = TokenType.IBET_SHARE.value - additional_issue_upload2.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload2.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload2.processed = False db.add(additional_issue_upload2) @@ -161,7 +150,9 @@ def test_normal_3_1(self, client, db): additional_issue_upload3.token_address = token_address additional_issue_upload3.issuer_address = issuer_address additional_issue_upload3.token_type = TokenType.IBET_SHARE.value - additional_issue_upload3.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload3.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload3.processed = False db.add(additional_issue_upload3) @@ -170,7 +161,9 @@ def test_normal_3_1(self, client, db): additional_issue_upload4.token_address = token_address additional_issue_upload4.issuer_address = issuer_address additional_issue_upload4.token_type = TokenType.IBET_SHARE.value - additional_issue_upload4.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload4.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload4.processed = False db.add(additional_issue_upload4) @@ -179,24 +172,18 @@ def test_normal_3_1(self, client, db): additional_issue_upload5.token_address = "other_token" additional_issue_upload5.issuer_address = issuer_address additional_issue_upload5.token_type = TokenType.IBET_SHARE.value - additional_issue_upload5.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload5.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload5.processed = False db.add(additional_issue_upload5) # request target API - resp = client.get( - self.base_url.format(token_address), - headers={} - ) + resp = client.get(self.base_url.format(token_address), headers={}) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 4, - "limit": None, - "offset": None, - "total": 4 - }, + "result_set": {"count": 4, "limit": None, "offset": None, "total": 4}, "uploads": [ { "issuer_address": issuer_address, @@ -204,7 +191,7 @@ def test_normal_3_1(self, client, db): "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -212,7 +199,7 @@ def test_normal_3_1(self, client, db): "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -220,7 +207,7 @@ def test_normal_3_1(self, client, db): "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -228,9 +215,9 @@ def test_normal_3_1(self, client, db): "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY - } - ] + "created": mock.ANY, + }, + ], } # @@ -255,7 +242,9 @@ def test_normal_3_2(self, client, db): additional_issue_upload1.token_address = token_address additional_issue_upload1.issuer_address = issuer_address additional_issue_upload1.token_type = TokenType.IBET_SHARE.value - additional_issue_upload1.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload1.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload1.processed = True db.add(additional_issue_upload1) @@ -264,7 +253,9 @@ def test_normal_3_2(self, client, db): additional_issue_upload2.token_address = token_address additional_issue_upload2.issuer_address = issuer_address additional_issue_upload2.token_type = TokenType.IBET_SHARE.value - additional_issue_upload2.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload2.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload2.processed = False db.add(additional_issue_upload2) @@ -273,7 +264,9 @@ def test_normal_3_2(self, client, db): additional_issue_upload3.token_address = token_address additional_issue_upload3.issuer_address = "other_issuer" additional_issue_upload3.token_type = TokenType.IBET_SHARE.value - additional_issue_upload3.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload3.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload3.processed = False db.add(additional_issue_upload3) @@ -282,7 +275,9 @@ def test_normal_3_2(self, client, db): additional_issue_upload4.token_address = token_address additional_issue_upload4.issuer_address = "other_issuer" additional_issue_upload4.token_type = TokenType.IBET_SHARE.value - additional_issue_upload4.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload4.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload4.processed = False db.add(additional_issue_upload4) @@ -291,26 +286,21 @@ def test_normal_3_2(self, client, db): additional_issue_upload5.token_address = "other_token" additional_issue_upload5.issuer_address = issuer_address additional_issue_upload5.token_type = TokenType.IBET_SHARE.value - additional_issue_upload5.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload5.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload5.processed = False db.add(additional_issue_upload5) # request target API resp = client.get( self.base_url.format(token_address), - headers={ - "issuer-address": issuer_address - } + headers={"issuer-address": issuer_address}, ) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 2, - "limit": None, - "offset": None, - "total": 2 - }, + "result_set": {"count": 2, "limit": None, "offset": None, "total": 2}, "uploads": [ { "issuer_address": issuer_address, @@ -318,7 +308,7 @@ def test_normal_3_2(self, client, db): "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -326,10 +316,10 @@ def test_normal_3_2(self, client, db): "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY - } - ] - } + "created": mock.ANY, + }, + ], + } # # Multi record (status) @@ -353,7 +343,9 @@ def test_normal_3_3(self, client, db): additional_issue_upload1.token_address = token_address additional_issue_upload1.issuer_address = issuer_address additional_issue_upload1.token_type = TokenType.IBET_SHARE.value - additional_issue_upload1.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload1.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload1.processed = True db.add(additional_issue_upload1) @@ -362,7 +354,9 @@ def test_normal_3_3(self, client, db): additional_issue_upload2.token_address = token_address additional_issue_upload2.issuer_address = issuer_address additional_issue_upload2.token_type = TokenType.IBET_SHARE.value - additional_issue_upload2.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload2.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload2.processed = False db.add(additional_issue_upload2) @@ -371,7 +365,9 @@ def test_normal_3_3(self, client, db): additional_issue_upload3.token_address = token_address additional_issue_upload3.issuer_address = issuer_address additional_issue_upload3.token_type = TokenType.IBET_SHARE.value - additional_issue_upload3.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload3.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload3.processed = False db.add(additional_issue_upload3) @@ -380,7 +376,9 @@ def test_normal_3_3(self, client, db): additional_issue_upload4.token_address = token_address additional_issue_upload4.issuer_address = issuer_address additional_issue_upload4.token_type = TokenType.IBET_SHARE.value - additional_issue_upload4.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload4.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload4.processed = False db.add(additional_issue_upload4) @@ -389,36 +387,27 @@ def test_normal_3_3(self, client, db): additional_issue_upload5.token_address = "other_token" additional_issue_upload5.issuer_address = issuer_address additional_issue_upload5.token_type = TokenType.IBET_SHARE.value - additional_issue_upload5.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload5.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload5.processed = False db.add(additional_issue_upload5) # request target API - req_param = { - "processed": False - } - resp = client.get( - self.base_url.format(token_address), - params=req_param - ) + req_param = {"processed": False} + resp = client.get(self.base_url.format(token_address), params=req_param) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 3, - "limit": None, - "offset": None, - "total": 4 - }, - "uploads": - [ + "result_set": {"count": 3, "limit": None, "offset": None, "total": 4}, + "uploads": [ { "issuer_address": issuer_address, "processed": False, "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -426,7 +415,7 @@ def test_normal_3_3(self, client, db): "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -434,9 +423,9 @@ def test_normal_3_3(self, client, db): "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY - } - ] + "created": mock.ANY, + }, + ], } # @@ -461,7 +450,9 @@ def test_normal_4(self, client, db): additional_issue_upload1.token_address = token_address additional_issue_upload1.issuer_address = issuer_address additional_issue_upload1.token_type = TokenType.IBET_SHARE.value - additional_issue_upload1.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload1.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload1.processed = True db.add(additional_issue_upload1) @@ -470,7 +461,9 @@ def test_normal_4(self, client, db): additional_issue_upload2.token_address = token_address additional_issue_upload2.issuer_address = issuer_address additional_issue_upload2.token_type = TokenType.IBET_SHARE.value - additional_issue_upload2.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload2.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload2.processed = False db.add(additional_issue_upload2) @@ -479,7 +472,9 @@ def test_normal_4(self, client, db): additional_issue_upload3.token_address = token_address additional_issue_upload3.issuer_address = issuer_address additional_issue_upload3.token_type = TokenType.IBET_SHARE.value - additional_issue_upload3.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload3.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload3.processed = False db.add(additional_issue_upload3) @@ -488,7 +483,9 @@ def test_normal_4(self, client, db): additional_issue_upload4.token_address = token_address additional_issue_upload4.issuer_address = issuer_address additional_issue_upload4.token_type = TokenType.IBET_SHARE.value - additional_issue_upload4.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload4.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload4.processed = False db.add(additional_issue_upload4) @@ -497,28 +494,19 @@ def test_normal_4(self, client, db): additional_issue_upload5.token_address = "other_token" additional_issue_upload5.issuer_address = issuer_address additional_issue_upload5.token_type = TokenType.IBET_SHARE.value - additional_issue_upload5.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload5.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload5.processed = False db.add(additional_issue_upload5) # request target API - req_param = { - "limit": 2, - "offset": 2 - } - resp = client.get( - self.base_url.format(token_address), - params=req_param - ) + req_param = {"limit": 2, "offset": 2} + resp = client.get(self.base_url.format(token_address), params=req_param) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 4, - "limit": 2, - "offset": 2, - "total": 4 - }, + "result_set": {"count": 4, "limit": 2, "offset": 2, "total": 4}, "uploads": [ { "issuer_address": issuer_address, @@ -526,7 +514,7 @@ def test_normal_4(self, client, db): "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -534,9 +522,9 @@ def test_normal_4(self, client, db): "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY - } - ] + "created": mock.ANY, + }, + ], } # @@ -561,7 +549,9 @@ def test_normal_5(self, client, db): additional_issue_upload1.token_address = token_address additional_issue_upload1.issuer_address = issuer_address additional_issue_upload1.token_type = TokenType.IBET_SHARE.value - additional_issue_upload1.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload1.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload1.processed = True db.add(additional_issue_upload1) @@ -570,7 +560,9 @@ def test_normal_5(self, client, db): additional_issue_upload2.token_address = token_address additional_issue_upload2.issuer_address = issuer_address additional_issue_upload2.token_type = TokenType.IBET_SHARE.value - additional_issue_upload2.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload2.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload2.processed = False db.add(additional_issue_upload2) @@ -579,7 +571,9 @@ def test_normal_5(self, client, db): additional_issue_upload3.token_address = token_address additional_issue_upload3.issuer_address = issuer_address additional_issue_upload3.token_type = TokenType.IBET_SHARE.value - additional_issue_upload3.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload3.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload3.processed = True db.add(additional_issue_upload3) @@ -588,7 +582,9 @@ def test_normal_5(self, client, db): additional_issue_upload4.token_address = token_address additional_issue_upload4.issuer_address = issuer_address additional_issue_upload4.token_type = TokenType.IBET_SHARE.value - additional_issue_upload4.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload4.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload4.processed = False db.add(additional_issue_upload4) @@ -597,27 +593,19 @@ def test_normal_5(self, client, db): additional_issue_upload5.token_address = "other_token" additional_issue_upload5.issuer_address = issuer_address additional_issue_upload5.token_type = TokenType.IBET_SHARE.value - additional_issue_upload5.category = BatchIssueRedeemProcessingCategory.ISSUE.value + additional_issue_upload5.category = ( + BatchIssueRedeemProcessingCategory.ISSUE.value + ) additional_issue_upload5.processed = False db.add(additional_issue_upload5) # request target API - req_param = { - "sort_order": 0 - } - resp = client.get( - self.base_url.format(token_address), - params=req_param - ) + req_param = {"sort_order": 0} + resp = client.get(self.base_url.format(token_address), params=req_param) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 4, - "limit": None, - "offset": None, - "total": 4 - }, + "result_set": {"count": 4, "limit": None, "offset": None, "total": 4}, "uploads": [ { "issuer_address": issuer_address, @@ -625,7 +613,7 @@ def test_normal_5(self, client, db): "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -633,7 +621,7 @@ def test_normal_5(self, client, db): "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -641,7 +629,7 @@ def test_normal_5(self, client, db): "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -649,9 +637,9 @@ def test_normal_5(self, client, db): "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY - } - ] + "created": mock.ANY, + }, + ], } ########################################################################### @@ -677,13 +665,8 @@ def test_error_1(self, client, db): db.add(token) # request target API - req_param = { - "processed": "invalid_value" - } - resp = client.get( - self.base_url.format(token_address), - params=req_param - ) + req_param = {"processed": "invalid_value"} + resp = client.get(self.base_url.format(token_address), params=req_param) assert resp.status_code == 422 assert resp.json() == { @@ -691,10 +674,8 @@ def test_error_1(self, client, db): { "loc": ["query", "processed"], "msg": "value could not be parsed to a boolean", - "type": "type_error.bool" + "type": "type_error.bool", } ], - "meta": { - "code": 1, "title": "RequestValidationError" - } + "meta": {"code": 1, "title": "RequestValidationError"}, } diff --git a/tests/test_app_routers_share_tokens_{token_address}_additional_issue_batch_POST.py b/tests/test_app_routers_share_tokens_{token_address}_additional_issue_batch_POST.py index 089ad817..6ae63a95 100644 --- a/tests/test_app_routers_share_tokens_{token_address}_additional_issue_batch_POST.py +++ b/tests/test_app_routers_share_tokens_{token_address}_additional_issue_batch_POST.py @@ -20,10 +20,11 @@ from app.model.db import ( Account, + BatchIssueRedeem, + BatchIssueRedeemProcessingCategory, + BatchIssueRedeemUpload, Token, TokenType, - BatchIssueRedeemUpload, - BatchIssueRedeem, BatchIssueRedeemProcessingCategory ) from app.utils.e2ee_utils import E2EEUtils from tests.account_config import config_eth_account @@ -64,23 +65,20 @@ def test_normal_1(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 10 - } - ] + req_param = [{"account_address": test_account_1, "amount": 10}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion - upload: Optional[BatchIssueRedeemUpload] = db.query(BatchIssueRedeemUpload).first() + upload: Optional[BatchIssueRedeemUpload] = db.query( + BatchIssueRedeemUpload + ).first() assert upload.issuer_address == issuer_address assert upload.token_type == TokenType.IBET_SHARE.value assert upload.token_address == token_address @@ -128,26 +126,22 @@ def test_normal_2(self, client, db): # request target API req_param = [ - { - "account_address": test_account_1, - "amount": 10 - }, - { - "account_address": test_account_2, - "amount": 20 - } + {"account_address": test_account_1, "amount": 10}, + {"account_address": test_account_2, "amount": 20}, ] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion - upload: Optional[BatchIssueRedeemUpload] = db.query(BatchIssueRedeemUpload).first() + upload: Optional[BatchIssueRedeemUpload] = db.query( + BatchIssueRedeemUpload + ).first() assert upload.issuer_address == issuer_address assert upload.token_type == TokenType.IBET_SHARE.value assert upload.token_address == token_address @@ -207,24 +201,21 @@ def test_error_1_1(self, client, db): json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['body'], - 'msg': 'value is not a valid list', - 'type': 'type_error.list' + "loc": ["body"], + "msg": "value is not a valid list", + "type": "type_error.list", } - ] + ], } # Error_1_2 @@ -252,35 +243,27 @@ def test_error_1_2(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": "0x0", - "amount": 10 - } - ] + req_param = [{"account_address": "0x0", "amount": 10}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['body', 0, 'account_address'], - 'msg': 'account_address is not a valid address', - 'type': 'value_error' + "loc": ["body", 0, "account_address"], + "msg": "account_address is not a valid address", + "type": "value_error", } - ] + ], } # Error_1_3_1 @@ -310,36 +293,28 @@ def test_error_1_3_1(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 0 - } - ] + req_param = [{"account_address": test_account_1, "amount": 0}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['body', 0, 'amount'], - 'msg': 'ensure this value is greater than or equal to 1', - 'type': 'value_error.number.not_ge', - 'ctx': {'limit_value': 1} + "loc": ["body", 0, "amount"], + "msg": "ensure this value is greater than or equal to 1", + "type": "value_error.number.not_ge", + "ctx": {"limit_value": 1}, } - ] + ], } # Error_1_3_2 @@ -369,36 +344,28 @@ def test_error_1_3_2(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 1_000_000_000_001 - } - ] + req_param = [{"account_address": test_account_1, "amount": 1_000_000_000_001}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['body', 0, 'amount'], - 'msg': 'ensure this value is less than or equal to 1000000000000', - 'type': 'value_error.number.not_le', - 'ctx': {'limit_value': 1000000000000} + "loc": ["body", 0, "amount"], + "msg": "ensure this value is less than or equal to 1000000000000", + "type": "value_error.number.not_le", + "ctx": {"limit_value": 1000000000000}, } - ] + ], } # Error_1_4 @@ -428,32 +395,22 @@ def test_error_1_4(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 10 - } - ] + req_param = [{"account_address": test_account_1, "amount": 10}] resp = client.post( - self.base_url.format(token_address), - json=req_param, - headers=None + self.base_url.format(token_address), json=req_param, headers=None ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['header', 'issuer-address'], - 'msg': 'field required', - 'type': 'value_error.missing' + "loc": ["header", "issuer-address"], + "msg": "field required", + "type": "value_error.missing", } - ] + ], } # Error_1_5 @@ -483,35 +440,24 @@ def test_error_1_5(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 10 - } - ] + req_param = [{"account_address": test_account_1, "amount": 10}] resp = client.post( self.base_url.format(token_address), json=req_param, - headers={ - "issuer-address": issuer_address, - "eoa-password": "password" - } + headers={"issuer-address": issuer_address, "eoa-password": "password"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['header', 'eoa-password'], - 'msg': 'eoa-password is not a Base64-encoded encrypted data', - 'type': 'value_error' + "loc": ["header", "eoa-password"], + "msg": "eoa-password is not a Base64-encoded encrypted data", + "type": "value_error", } - ] + ], } # Error_1_6 @@ -545,18 +491,15 @@ def test_error_1_6(self, client, db): json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'InvalidParameterError' - }, - 'detail': 'list length must be at least one' + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "list length must be at least one", } # Error_1_7_1 @@ -586,29 +529,21 @@ def test_error_1_7_1(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 10 - } - ] + req_param = [{"account_address": test_account_1, "amount": 10}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'AuthorizationError' - }, - 'detail': 'issuer does not exist, or password mismatch' + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # Error_1_7_2 @@ -638,29 +573,21 @@ def test_error_1_7_2(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 10 - } - ] + req_param = [{"account_address": test_account_1, "amount": 10}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'AuthorizationError' - }, - 'detail': 'issuer does not exist, or password mismatch' + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # Error_1_8_1 @@ -683,29 +610,21 @@ def test_error_1_8_1(self, client, db): db.add(account) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 10 - } - ] + req_param = [{"account_address": test_account_1, "amount": 10}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'NotFound' - }, - 'detail': 'token not found' + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # Error_1_8_2 @@ -737,27 +656,19 @@ def test_error_1_8_2(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 10 - } - ] + req_param = [{"account_address": test_account_1, "amount": 10}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'InvalidParameterError' - }, - 'detail': 'this token is temporarily unavailable' + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } diff --git a/tests/test_app_routers_share_tokens_{token_address}_additional_issue_batch_{batch_id}_GET.py b/tests/test_app_routers_share_tokens_{token_address}_additional_issue_batch_{batch_id}_GET.py index 00472f5f..501a2d0d 100644 --- a/tests/test_app_routers_share_tokens_{token_address}_additional_issue_batch_{batch_id}_GET.py +++ b/tests/test_app_routers_share_tokens_{token_address}_additional_issue_batch_{batch_id}_GET.py @@ -16,16 +16,15 @@ SPDX-License-Identifier: Apache-2.0 """ -from app.utils.e2ee_utils import E2EEUtils - from app.model.db import ( - TokenType, Account, - Token, - BatchIssueRedeemUpload, + BatchIssueRedeem, BatchIssueRedeemProcessingCategory, - BatchIssueRedeem + BatchIssueRedeemUpload, + Token, + TokenType, ) +from app.utils.e2ee_utils import E2EEUtils from tests.account_config import config_eth_account @@ -39,13 +38,8 @@ class TestAppRoutersShareTokensTokenAddressAdditionalIssueBatchBatchIdGET: ] account_list = [ - { - "address": config_eth_account("user1")["address"], - "amount": 1 - }, { - "address": config_eth_account("user2")["address"], - "amount": 2 - } + {"address": config_eth_account("user1")["address"], "amount": 1}, + {"address": config_eth_account("user2")["address"], "amount": 2}, ] ########################################################################### @@ -95,22 +89,20 @@ def test_normal_1(self, client, db): # request target API resp = client.get( self.base_url.format(test_token_address, self.upload_id_list[0]), - headers={ - "issuer-address": issuer_address - } + headers={"issuer-address": issuer_address}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'processed': True, - 'results': [ + "processed": True, + "results": [ { - 'account_address': self.account_list[0]["address"], - 'amount': self.account_list[0]["amount"], - 'status': 1 + "account_address": self.account_list[0]["address"], + "amount": self.account_list[0]["amount"], + "status": 1, } - ] + ], } # Normal_2 @@ -163,27 +155,25 @@ def test_normal_2(self, client, db): # request target API resp = client.get( self.base_url.format(test_token_address, self.upload_id_list[0]), - headers={ - "issuer-address": issuer_address - } + headers={"issuer-address": issuer_address}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'processed': True, - 'results': [ + "processed": True, + "results": [ { - 'account_address': self.account_list[0]["address"], - 'amount': self.account_list[0]["amount"], - 'status': 1 + "account_address": self.account_list[0]["address"], + "amount": self.account_list[0]["amount"], + "status": 1, }, { - 'account_address': self.account_list[1]["address"], - 'amount': self.account_list[1]["amount"], - 'status': 1 - } - ] + "account_address": self.account_list[1]["address"], + "amount": self.account_list[1]["amount"], + "status": 1, + }, + ], } ######################################################################### @@ -226,17 +216,12 @@ def test_error_1(self, client, db): # request target API resp = client.get( self.base_url.format(test_token_address, self.upload_id_list[0]), - headers={ - "issuer-address": issuer_address - } + headers={"issuer-address": issuer_address}, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "batch not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "batch not found", } diff --git a/tests/test_app_routers_share_tokens_{token_address}_holders_GET.py b/tests/test_app_routers_share_tokens_{token_address}_holders_GET.py index 4af17fde..049ea883 100644 --- a/tests/test_app_routers_share_tokens_{token_address}_holders_GET.py +++ b/tests/test_app_routers_share_tokens_{token_address}_holders_GET.py @@ -18,11 +18,11 @@ """ from app.model.db import ( Account, + IDXLockedPosition, + IDXPersonalInfo, + IDXPosition, Token, TokenType, - IDXPosition, - IDXLockedPosition, - IDXPersonalInfo ) from tests.account_config import config_eth_account @@ -58,9 +58,7 @@ def test_normal_1(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion @@ -102,18 +100,22 @@ def test_normal_2(self, client, db): # prepare data: Locked Position idx_locked_position = IDXLockedPosition() idx_locked_position.token_address = _token_address - idx_locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + idx_locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) idx_locked_position.account_address = _account_address_1 idx_locked_position.value = 5 db.add(idx_locked_position) idx_locked_position = IDXLockedPosition() idx_locked_position.token_address = _token_address - idx_locked_position.lock_address = "0x1234567890123456789012345678900000000002" # lock address 2 + idx_locked_position.lock_address = ( + "0x1234567890123456789012345678900000000002" # lock address 2 + ) idx_locked_position.account_address = _account_address_1 idx_locked_position.value = 5 db.add(idx_locked_position) - + # prepare data: Personal Info idx_personal_info_1 = IDXPersonalInfo() idx_personal_info_1.account_address = _account_address_1 @@ -126,16 +128,14 @@ def test_normal_2(self, client, db): "email": "email_test1", "birth": "birth_test1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } db.add(idx_personal_info_1) # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion @@ -151,13 +151,13 @@ def test_normal_2(self, client, db): "email": "email_test1", "birth": "birth_test1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, }, "balance": 10, "exchange_balance": 11, "exchange_commitment": 12, "pending_transfer": 5, - "locked": 10 + "locked": 10, } ] @@ -195,14 +195,18 @@ def test_normal_3_1(self, client, db): idx_locked_position = IDXLockedPosition() idx_locked_position.token_address = _token_address - idx_locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + idx_locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) idx_locked_position.account_address = _account_address_1 idx_locked_position.value = 5 db.add(idx_locked_position) idx_locked_position = IDXLockedPosition() idx_locked_position.token_address = _token_address - idx_locked_position.lock_address = "0x1234567890123456789012345678900000000002" # lock address 2 + idx_locked_position.lock_address = ( + "0x1234567890123456789012345678900000000002" # lock address 2 + ) idx_locked_position.account_address = _account_address_1 idx_locked_position.value = 5 db.add(idx_locked_position) @@ -218,7 +222,7 @@ def test_normal_3_1(self, client, db): "email": "email_test1", "birth": "birth_test1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } db.add(idx_personal_info_1) @@ -231,17 +235,21 @@ def test_normal_3_1(self, client, db): idx_position_2.exchange_commitment = 22 idx_position_2.pending_transfer = 10 db.add(idx_position_2) - + idx_locked_position = IDXLockedPosition() idx_locked_position.token_address = _token_address - idx_locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + idx_locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) idx_locked_position.account_address = _account_address_2 idx_locked_position.value = 10 db.add(idx_locked_position) idx_locked_position = IDXLockedPosition() idx_locked_position.token_address = _token_address - idx_locked_position.lock_address = "0x1234567890123456789012345678900000000002" # lock address 2 + idx_locked_position.lock_address = ( + "0x1234567890123456789012345678900000000002" # lock address 2 + ) idx_locked_position.account_address = _account_address_2 idx_locked_position.value = 10 db.add(idx_locked_position) @@ -258,14 +266,18 @@ def test_normal_3_1(self, client, db): idx_locked_position = IDXLockedPosition() idx_locked_position.token_address = _token_address - idx_locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + idx_locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) idx_locked_position.account_address = _account_address_3 idx_locked_position.value = 15 db.add(idx_locked_position) idx_locked_position = IDXLockedPosition() idx_locked_position.token_address = _token_address - idx_locked_position.lock_address = "0x1234567890123456789012345678900000000002" # lock address 2 + idx_locked_position.lock_address = ( + "0x1234567890123456789012345678900000000002" # lock address 2 + ) idx_locked_position.account_address = _account_address_3 idx_locked_position.value = 15 db.add(idx_locked_position) @@ -287,9 +299,7 @@ def test_normal_3_1(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion @@ -305,13 +315,13 @@ def test_normal_3_1(self, client, db): "email": "email_test1", "birth": "birth_test1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, }, "balance": 10, "exchange_balance": 11, "exchange_commitment": 12, "pending_transfer": 5, - "locked": 10 + "locked": 10, }, { "account_address": _account_address_2, @@ -323,13 +333,13 @@ def test_normal_3_1(self, client, db): "email": None, "birth": None, "is_corporate": None, - "tax_category": None + "tax_category": None, }, "balance": 20, "exchange_balance": 21, "exchange_commitment": 22, "pending_transfer": 10, - "locked": 20 + "locked": 20, }, { "account_address": _account_address_3, @@ -341,14 +351,14 @@ def test_normal_3_1(self, client, db): "email": "email_test3", "birth": "birth_test3", "is_corporate": None, - "tax_category": None + "tax_category": None, }, "balance": 99, "exchange_balance": 99, "exchange_commitment": 99, "pending_transfer": 99, - "locked": 30 - } + "locked": 30, + }, ] # @@ -398,7 +408,9 @@ def test_normal_3_2(self, client, db): idx_locked_position = IDXLockedPosition() idx_locked_position.token_address = _token_address - idx_locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + idx_locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) idx_locked_position.account_address = _account_address_2 idx_locked_position.value = 0 db.add(idx_locked_position) @@ -416,7 +428,9 @@ def test_normal_3_2(self, client, db): idx_locked_position = IDXLockedPosition() idx_locked_position.token_address = _token_address - idx_locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + idx_locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) idx_locked_position.account_address = _account_address_3 idx_locked_position.value = 0 db.add(idx_locked_position) @@ -438,9 +452,7 @@ def test_normal_3_2(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion @@ -457,13 +469,13 @@ def test_normal_3_2(self, client, db): "email": None, "birth": None, "is_corporate": None, - "tax_category": None + "tax_category": None, }, "balance": 0, "exchange_balance": 0, "exchange_commitment": 12, "pending_transfer": 5, - "locked": 0 + "locked": 0, }, { "account_address": _account_address_2, @@ -475,14 +487,14 @@ def test_normal_3_2(self, client, db): "email": None, "birth": None, "is_corporate": None, - "tax_category": None + "tax_category": None, }, "balance": 20, "exchange_balance": 21, "exchange_commitment": 0, "pending_transfer": 0, - "locked": 0 - } + "locked": 0, + }, ] # @@ -529,7 +541,7 @@ def test_normal_3_3(self, client, db): "email": "email_test1", "birth": "birth_test1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } db.add(idx_personal_info_1) @@ -568,12 +580,8 @@ def test_normal_3_3(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - }, - params={ - "include_former_holder": "true" - } + headers={"issuer-address": _issuer_address}, + params={"include_former_holder": "true"}, ) # assertion @@ -590,13 +598,13 @@ def test_normal_3_3(self, client, db): "email": "email_test1", "birth": "birth_test1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, }, "balance": 0, "exchange_balance": 0, "exchange_commitment": 12, "pending_transfer": 5, - "locked": 0 + "locked": 0, }, { "account_address": _account_address_2, @@ -608,13 +616,13 @@ def test_normal_3_3(self, client, db): "email": None, "birth": None, "is_corporate": None, - "tax_category": None + "tax_category": None, }, "balance": 20, "exchange_balance": 21, "exchange_commitment": 0, "pending_transfer": 0, - "locked": 0 + "locked": 0, }, { "account_address": _account_address_3, @@ -626,14 +634,14 @@ def test_normal_3_3(self, client, db): "email": "email_test3", "birth": "birth_test3", "is_corporate": None, - "tax_category": None + "tax_category": None, }, "balance": 0, "exchange_balance": 0, "exchange_commitment": 0, "pending_transfer": 0, - "locked": 0 - } + "locked": 0, + }, ] ########################################################################### @@ -647,24 +655,20 @@ def test_error_1(self, client, db): # request target API resp = client.get( - self.base_url.format(_token_address), - headers={ - "issuer-address": "0x0" - } + self.base_url.format(_token_address), headers={"issuer-address": "0x0"} ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, - "detail": [{ - "loc": ["header", "issuer-address"], - "msg": "issuer-address is not a valid address", - "type": "value_error" - }] + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ + { + "loc": ["header", "issuer-address"], + "msg": "issuer-address is not a valid address", + "type": "value_error", + } + ], } # @@ -677,19 +681,14 @@ def test_error_2(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "issuer does not exist" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "issuer does not exist", } # @@ -707,19 +706,14 @@ def test_error_3(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # @@ -746,17 +740,12 @@ def test_error_4(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } diff --git a/tests/test_app_routers_share_tokens_{token_address}_holders_count_GET.py b/tests/test_app_routers_share_tokens_{token_address}_holders_count_GET.py index a73d387e..9c616725 100644 --- a/tests/test_app_routers_share_tokens_{token_address}_holders_count_GET.py +++ b/tests/test_app_routers_share_tokens_{token_address}_holders_count_GET.py @@ -16,13 +16,7 @@ SPDX-License-Identifier: Apache-2.0 """ -from app.model.db import ( - Account, - Token, - TokenType, - IDXPosition, - IDXLockedPosition -) +from app.model.db import Account, IDXLockedPosition, IDXPosition, Token, TokenType from tests.account_config import config_eth_account @@ -58,14 +52,12 @@ def test_normal_1_1(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 200 - assert resp.json() == {'count': 0} + assert resp.json() == {"count": 0} # # position is not None @@ -101,14 +93,12 @@ def test_normal_1_2(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 200 - assert resp.json() == {'count': 1} + assert resp.json() == {"count": 1} # # position is not None @@ -143,14 +133,18 @@ def test_normal_1_3(self, client, db): idx_locked_position = IDXLockedPosition() idx_locked_position.token_address = _token_address - idx_locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + idx_locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) idx_locked_position.account_address = _account_address_1 idx_locked_position.value = 5 db.add(idx_locked_position) idx_locked_position = IDXLockedPosition() idx_locked_position.token_address = _token_address - idx_locked_position.lock_address = "0x1234567890123456789012345678900000000002" # lock address 2 + idx_locked_position.lock_address = ( + "0x1234567890123456789012345678900000000002" # lock address 2 + ) idx_locked_position.account_address = _account_address_1 idx_locked_position.value = 5 db.add(idx_locked_position) @@ -158,14 +152,12 @@ def test_normal_1_3(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 200 - assert resp.json() == {'count': 1} + assert resp.json() == {"count": 1} # # position is not None (but zero) @@ -200,7 +192,9 @@ def test_normal_1_4(self, client, db): idx_locked_position = IDXLockedPosition() idx_locked_position.token_address = _token_address - idx_locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + idx_locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) idx_locked_position.account_address = _account_address_1 idx_locked_position.value = 0 db.add(idx_locked_position) @@ -208,14 +202,12 @@ def test_normal_1_4(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 200 - assert resp.json() == {'count': 0} + assert resp.json() == {"count": 0} # # Multiple records @@ -251,7 +243,9 @@ def test_normal_2(self, client, db): idx_locked_position = IDXLockedPosition() idx_locked_position.token_address = _token_address - idx_locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + idx_locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) idx_locked_position.account_address = _account_address_1 idx_locked_position.value = 5 db.add(idx_locked_position) @@ -267,7 +261,9 @@ def test_normal_2(self, client, db): idx_locked_position = IDXLockedPosition() idx_locked_position.token_address = _token_address - idx_locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + idx_locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) idx_locked_position.account_address = _account_address_2 idx_locked_position.value = 5 db.add(idx_locked_position) @@ -283,7 +279,9 @@ def test_normal_2(self, client, db): idx_locked_position = IDXLockedPosition() idx_locked_position.token_address = _token_address - idx_locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + idx_locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) idx_locked_position.account_address = _account_address_3 idx_locked_position.value = 5 db.add(idx_locked_position) @@ -291,14 +289,12 @@ def test_normal_2(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 200 - assert resp.json() == {'count': 3} + assert resp.json() == {"count": 3} ########################################################################### # Error Case @@ -312,24 +308,20 @@ def test_error_1(self, client, db): # request target API resp = client.get( - self.base_url.format(_token_address), - headers={ - "issuer-address": "0x0" - } + self.base_url.format(_token_address), headers={"issuer-address": "0x0"} ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, - "detail": [{ - "loc": ["header", "issuer-address"], - "msg": "issuer-address is not a valid address", - "type": "value_error" - }] + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ + { + "loc": ["header", "issuer-address"], + "msg": "issuer-address is not a valid address", + "type": "value_error", + } + ], } # @@ -343,19 +335,14 @@ def test_error_2(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "issuer does not exist" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "issuer does not exist", } # @@ -374,19 +361,14 @@ def test_error_3(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # @@ -414,17 +396,12 @@ def test_error_4(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } diff --git a/tests/test_app_routers_share_tokens_{token_address}_holders_{account_address}_GET.py b/tests/test_app_routers_share_tokens_{token_address}_holders_{account_address}_GET.py index d9d09ad9..1b25bc1d 100644 --- a/tests/test_app_routers_share_tokens_{token_address}_holders_{account_address}_GET.py +++ b/tests/test_app_routers_share_tokens_{token_address}_holders_{account_address}_GET.py @@ -18,11 +18,11 @@ """ from app.model.db import ( Account, + IDXLockedPosition, + IDXPersonalInfo, + IDXPosition, Token, TokenType, - IDXPosition, - IDXLockedPosition, - IDXPersonalInfo ) from tests.account_config import config_eth_account @@ -70,16 +70,14 @@ def test_normal_1_1(self, client, db): "email": "email_test1", "birth": "birth_test1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } db.add(idx_personal_info_1) # request target API resp = client.get( self.base_url.format(_token_address, _account_address_1), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion @@ -94,13 +92,13 @@ def test_normal_1_1(self, client, db): "email": "email_test1", "birth": "birth_test1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, }, "balance": 0, "exchange_balance": 0, "exchange_commitment": 0, "pending_transfer": 0, - "locked": 0 + "locked": 0, } # @@ -148,16 +146,14 @@ def test_normal_1_2(self, client, db): "email": "email_test1", "birth": "birth_test1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } db.add(idx_personal_info_1) # request target API resp = client.get( self.base_url.format(_token_address, _account_address_1), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion @@ -172,13 +168,13 @@ def test_normal_1_2(self, client, db): "email": "email_test1", "birth": "birth_test1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, }, "balance": 10, "exchange_balance": 11, "exchange_commitment": 12, "pending_transfer": 5, - "locked": 0 + "locked": 0, } # @@ -217,14 +213,18 @@ def test_normal_1_3(self, client, db): # prepare data: Locked Position _locked_position = IDXLockedPosition() _locked_position.token_address = _token_address - _locked_position.lock_address = "0x1234567890123456789012345678900000000001" # lock address 1 + _locked_position.lock_address = ( + "0x1234567890123456789012345678900000000001" # lock address 1 + ) _locked_position.account_address = _account_address_1 _locked_position.value = 5 db.add(_locked_position) _locked_position = IDXLockedPosition() _locked_position.token_address = _token_address - _locked_position.lock_address = "0x1234567890123456789012345678900000000002" # lock address 2 + _locked_position.lock_address = ( + "0x1234567890123456789012345678900000000002" # lock address 2 + ) _locked_position.account_address = _account_address_1 _locked_position.value = 5 db.add(_locked_position) @@ -241,16 +241,14 @@ def test_normal_1_3(self, client, db): "email": "email_test1", "birth": "birth_test1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } db.add(idx_personal_info_1) # request target API resp = client.get( self.base_url.format(_token_address, _account_address_1), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion @@ -265,13 +263,13 @@ def test_normal_1_3(self, client, db): "email": "email_test1", "birth": "birth_test1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, }, "balance": 10, "exchange_balance": 11, "exchange_commitment": 12, "pending_transfer": 5, - "locked": 10 + "locked": 10, } # @@ -307,9 +305,7 @@ def test_normal_2_1(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address, _account_address_1), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion @@ -324,13 +320,13 @@ def test_normal_2_1(self, client, db): "email": None, "birth": None, "is_corporate": None, - "tax_category": None + "tax_category": None, }, "balance": 10, "exchange_balance": 11, "exchange_commitment": 12, "pending_transfer": 5, - "locked": 0 + "locked": 0, } # @@ -380,9 +376,7 @@ def test_normal_2_2(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address, _account_address_1), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion @@ -397,13 +391,13 @@ def test_normal_2_2(self, client, db): "email": "email_test1", "birth": "birth_test1", "is_corporate": None, - "tax_category": None + "tax_category": None, }, "balance": 10, "exchange_balance": 11, "exchange_commitment": 12, "pending_transfer": 5, - "locked": 0 + "locked": 0, } ########################################################################### @@ -419,23 +413,20 @@ def test_error_1(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address, _account_address_1), - headers={ - "issuer-address": "0x0" - } + headers={"issuer-address": "0x0"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, - "detail": [{ - "loc": ["header", "issuer-address"], - "msg": "issuer-address is not a valid address", - "type": "value_error" - }] + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ + { + "loc": ["header", "issuer-address"], + "msg": "issuer-address is not a valid address", + "type": "value_error", + } + ], } # @@ -449,19 +440,14 @@ def test_error_2(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address, _account_address_1), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "issuer does not exist" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "issuer does not exist", } # @@ -480,19 +466,14 @@ def test_error_3(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address, _account_address_1), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # @@ -520,17 +501,12 @@ def test_error_4(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address, _account_address_1), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } diff --git a/tests/test_app_routers_share_tokens_{token_address}_personal_info_POST.py b/tests/test_app_routers_share_tokens_{token_address}_personal_info_POST.py index bed11827..ba6f67e2 100644 --- a/tests/test_app_routers_share_tokens_{token_address}_personal_info_POST.py +++ b/tests/test_app_routers_share_tokens_{token_address}_personal_info_POST.py @@ -19,18 +19,10 @@ import hashlib from unittest.mock import patch -from app.model.db import ( - Account, - AuthToken, - Token, - TokenType -) -from app.utils.e2ee_utils import E2EEUtils -from app.model.blockchain import ( - IbetShareContract, - PersonalInfoContract -) from app.exceptions import SendTransactionError +from app.model.blockchain import IbetShareContract, PersonalInfoContract +from app.model.db import Account, AuthToken, Token, TokenType +from app.utils.e2ee_utils import E2EEUtils from tests.account_config import config_eth_account @@ -70,21 +62,25 @@ def test_normal_1(self, client, db): # mock ibet_share_contract = IbetShareContract() - ibet_share_contract.personal_info_contract_address = "personal_info_contract_address" + ibet_share_contract.personal_info_contract_address = ( + "personal_info_contract_address" + ) IbetShareContract_get = patch( target="app.model.blockchain.token.IbetShareContract.get", - return_value=ibet_share_contract + return_value=ibet_share_contract, ) PersonalInfoContract_init = patch( target="app.model.blockchain.personal_info.PersonalInfoContract.__init__", - return_value=None + return_value=None, ) PersonalInfoContract_register_info = patch( target="app.model.blockchain.personal_info.PersonalInfoContract.register_info", - return_value=None + return_value=None, ) - with IbetShareContract_get, PersonalInfoContract_init, PersonalInfoContract_register_info: + with ( + IbetShareContract_get + ), PersonalInfoContract_init, PersonalInfoContract_register_info: # request target API req_param = { "account_address": _test_account_address, @@ -95,15 +91,15 @@ def test_normal_1(self, client, db): "email": "test_email", "birth": "test_birth", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } resp = client.post( self.test_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion @@ -112,12 +108,12 @@ def test_normal_1(self, client, db): PersonalInfoContract.__init__.assert_called_with( db=db, issuer_address=_issuer_address, - contract_address="personal_info_contract_address" + contract_address="personal_info_contract_address", ) PersonalInfoContract.register_info.assert_called_with( account_address=_test_account_address, data=req_param, - default_value=None + default_value=None, ) # @@ -149,21 +145,25 @@ def test_normal_2(self, client, db): # mock ibet_share_contract = IbetShareContract() - ibet_share_contract.personal_info_contract_address = "personal_info_contract_address" + ibet_share_contract.personal_info_contract_address = ( + "personal_info_contract_address" + ) IbetShareContract_get = patch( target="app.model.blockchain.token.IbetShareContract.get", - return_value=ibet_share_contract + return_value=ibet_share_contract, ) PersonalInfoContract_init = patch( target="app.model.blockchain.personal_info.PersonalInfoContract.__init__", - return_value=None + return_value=None, ) PersonalInfoContract_register_info = patch( target="app.model.blockchain.personal_info.PersonalInfoContract.register_info", - return_value=None + return_value=None, ) - with IbetShareContract_get, PersonalInfoContract_init, PersonalInfoContract_register_info: + with ( + IbetShareContract_get + ), PersonalInfoContract_init, PersonalInfoContract_register_info: # request target API req_param = { "account_address": _test_account_address, @@ -174,15 +174,15 @@ def test_normal_2(self, client, db): "email": None, "birth": None, "is_corporate": None, - "tax_category": None + "tax_category": None, } resp = client.post( self.test_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion @@ -191,12 +191,12 @@ def test_normal_2(self, client, db): PersonalInfoContract.__init__.assert_called_with( db=db, issuer_address=_issuer_address, - contract_address="personal_info_contract_address" + contract_address="personal_info_contract_address", ) PersonalInfoContract.register_info.assert_called_with( account_address=_test_account_address, data=req_param, - default_value=None + default_value=None, ) # @@ -234,21 +234,25 @@ def test_normal_3(self, client, db): # mock ibet_share_contract = IbetShareContract() - ibet_share_contract.personal_info_contract_address = "personal_info_contract_address" + ibet_share_contract.personal_info_contract_address = ( + "personal_info_contract_address" + ) IbetShareContract_get = patch( target="app.model.blockchain.token.IbetShareContract.get", - return_value=ibet_share_contract + return_value=ibet_share_contract, ) PersonalInfoContract_init = patch( target="app.model.blockchain.personal_info.PersonalInfoContract.__init__", - return_value=None + return_value=None, ) PersonalInfoContract_register_info = patch( target="app.model.blockchain.personal_info.PersonalInfoContract.register_info", - return_value=None + return_value=None, ) - with IbetShareContract_get, PersonalInfoContract_init, PersonalInfoContract_register_info: + with ( + IbetShareContract_get + ), PersonalInfoContract_init, PersonalInfoContract_register_info: # request target API req_param = { "account_address": _test_account_address, @@ -259,15 +263,15 @@ def test_normal_3(self, client, db): "email": "test_email", "birth": "test_birth", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } resp = client.post( self.test_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "auth-token": "test_auth_token" - } + "auth-token": "test_auth_token", + }, ) # assertion @@ -276,12 +280,12 @@ def test_normal_3(self, client, db): PersonalInfoContract.__init__.assert_called_with( db=db, issuer_address=_issuer_address, - contract_address="personal_info_contract_address" + contract_address="personal_info_contract_address", ) PersonalInfoContract.register_info.assert_called_with( account_address=_test_account_address, data=req_param, - default_value=None + default_value=None, ) ########################################################################### @@ -302,28 +306,24 @@ def test_error_1_1(self, client, db): _token_address = "0xd9F55747DE740297ff1eEe537aBE0f8d73B7D783" # request target API - resp = client.post( - self.test_url.format(_token_address) - ) + resp = client.post(self.test_url.format(_token_address)) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "field required", - "type": "value_error.missing" - }, { + "type": "value_error.missing", + }, + { "loc": ["body"], "msg": "field required", - "type": "value_error.missing" - } - ] + "type": "value_error.missing", + }, + ], } # @@ -349,35 +349,33 @@ def test_error_1_2(self, client, db): "email": None, "birth": None, "is_corporate": None, - "tax_category": None + "tax_category": None, } resp = client.post( self.test_url.format(_token_address, _test_account_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "account_address"], "msg": "none is not an allowed value", - "type": "type_error.none.not_allowed" - }, { + "type": "type_error.none.not_allowed", + }, + { "loc": ["body", "key_manager"], "msg": "none is not an allowed value", - "type": "type_error.none.not_allowed" - } - ] + "type": "type_error.none.not_allowed", + }, + ], } # @@ -403,34 +401,28 @@ def test_error_1_3(self, client, db): "email": "test_email", "birth": "test_birth", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } resp = client.post( self.test_url.format(_token_address, _test_account_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "loc": [ - "body", - "account_address" - ], + "loc": ["body", "account_address"], "msg": "account_address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -452,31 +444,28 @@ def test_error_1_4(self, client, db): "email": "test_email", "birth": "test_birth", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } resp = client.post( self.test_url.format(_token_address), json=req_param, headers={ "issuer-address": "test_issuer_address", - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -502,31 +491,28 @@ def test_error_1_5(self, client, db): "email": "test_email", "birth": "test_birth", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } resp = client.post( self.test_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": "not_encrypted_password" - } + "eoa-password": "not_encrypted_password", + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "eoa-password"], "msg": "eoa-password is not a Base64-encoded encrypted data", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -552,25 +538,22 @@ def test_error_2_1(self, client, db): "email": "test_email", "birth": "test_birth", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } resp = client.post( self.test_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -603,25 +586,22 @@ def test_error_2_2(self, client, db): "email": "test_email", "birth": "test_birth", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } resp = client.post( self.test_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("mismatch_password") - } + "eoa-password": E2EEUtils.encrypt("mismatch_password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -654,25 +634,22 @@ def test_error_3(self, client, db): "email": "test_email", "birth": "test_birth", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } resp = client.post( self.test_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # @@ -714,25 +691,22 @@ def test_error_4(self, client, db): "email": "test_email", "birth": "test_birth", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } resp = client.post( self.test_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } # @@ -764,21 +738,25 @@ def test_error_5(self, client, db): # mock ibet_share_contract = IbetShareContract() - ibet_share_contract.personal_info_contract_address = "personal_info_contract_address" + ibet_share_contract.personal_info_contract_address = ( + "personal_info_contract_address" + ) IbetShareContract_get = patch( target="app.model.blockchain.token.IbetShareContract.get", - return_value=ibet_share_contract + return_value=ibet_share_contract, ) PersonalInfoContract_init = patch( target="app.model.blockchain.personal_info.PersonalInfoContract.__init__", - return_value=None + return_value=None, ) PersonalInfoContract_register_info = patch( target="app.model.blockchain.personal_info.PersonalInfoContract.register_info", - side_effect=SendTransactionError() + side_effect=SendTransactionError(), ) - with IbetShareContract_get, PersonalInfoContract_init, PersonalInfoContract_register_info: + with ( + IbetShareContract_get + ), PersonalInfoContract_init, PersonalInfoContract_register_info: # request target API req_param = { "account_address": _test_account_address, @@ -789,23 +767,20 @@ def test_error_5(self, client, db): "email": "test_email", "birth": "test_birth", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } resp = client.post( self.test_url.format(_token_address, _test_account_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 2, - "title": "SendTransactionError" - }, - "detail": "failed to register personal information" + "meta": {"code": 2, "title": "SendTransactionError"}, + "detail": "failed to register personal information", } diff --git a/tests/test_app_routers_share_tokens_{token_address}_personal_info_batch_GET.py b/tests/test_app_routers_share_tokens_{token_address}_personal_info_batch_GET.py index 92cba2a8..399b0a82 100644 --- a/tests/test_app_routers_share_tokens_{token_address}_personal_info_batch_GET.py +++ b/tests/test_app_routers_share_tokens_{token_address}_personal_info_batch_GET.py @@ -19,10 +19,10 @@ from unittest import mock from app.model.db import ( - TokenType, - Token, BatchRegisterPersonalInfoUpload, - BatchRegisterPersonalInfoUploadStatus + BatchRegisterPersonalInfoUploadStatus, + Token, + TokenType, ) from tests.account_config import config_eth_account @@ -37,7 +37,7 @@ class TestAppRoutersShareTokensTokenAddressPersonalInfoBatchGET: "0f33d48f-9e6e-4a36-a55e-5bbcbda69c80", "1c961f7d-e1ad-40e5-988b-cca3d6009643", "1e778f46-864e-4ec0-b566-21bd31cf63ff", - "1f33d48f-9e6e-4a36-a55e-5bbcbda69c80" + "1f33d48f-9e6e-4a36-a55e-5bbcbda69c80", ] ########################################################################### @@ -64,21 +64,14 @@ def test_normal_1(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address, self.upload_id_list[0]), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 0, - 'offset': None, - 'limit': None, - 'total': 0 - }, - 'uploads': [] + "result_set": {"count": 0, "offset": None, "limit": None, "total": 0}, + "uploads": [], } # Normal_2 @@ -108,37 +101,33 @@ def test_normal_2(self, client, db): batch_register_upload = BatchRegisterPersonalInfoUpload() batch_register_upload.issuer_address = _issuer_address batch_register_upload.upload_id = self.upload_id_list[1] - batch_register_upload.status = BatchRegisterPersonalInfoUploadStatus.PENDING.value + batch_register_upload.status = ( + BatchRegisterPersonalInfoUploadStatus.PENDING.value + ) db.add(batch_register_upload) # request target API resp = client.get( self.base_url.format(_token_address, self.upload_id_list[0]), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 2, - 'offset': None, - 'limit': None, - 'total': 2 - }, - 'uploads': [ + "result_set": {"count": 2, "offset": None, "limit": None, "total": 2}, + "uploads": [ { - 'batch_id': self.upload_id_list[1], - 'status': BatchRegisterPersonalInfoUploadStatus.PENDING.value, - 'created': mock.ANY - }, { - 'batch_id': self.upload_id_list[0], - 'status': BatchRegisterPersonalInfoUploadStatus.DONE.value, - 'created': mock.ANY - } - ] + "batch_id": self.upload_id_list[1], + "status": BatchRegisterPersonalInfoUploadStatus.PENDING.value, + "created": mock.ANY, + }, + { + "batch_id": self.upload_id_list[0], + "status": BatchRegisterPersonalInfoUploadStatus.DONE.value, + "created": mock.ANY, + }, + ], } # Normal_3 @@ -168,36 +157,29 @@ def test_normal_3(self, client, db): batch_register_upload = BatchRegisterPersonalInfoUpload() batch_register_upload.issuer_address = _issuer_address batch_register_upload.upload_id = self.upload_id_list[1] - batch_register_upload.status = BatchRegisterPersonalInfoUploadStatus.PENDING.value + batch_register_upload.status = ( + BatchRegisterPersonalInfoUploadStatus.PENDING.value + ) db.add(batch_register_upload) # request target API resp = client.get( self.base_url.format(_token_address, self.upload_id_list[0]), - headers={ - "issuer-address": _issuer_address - }, - params={ - "status": BatchRegisterPersonalInfoUploadStatus.DONE.value - } + headers={"issuer-address": _issuer_address}, + params={"status": BatchRegisterPersonalInfoUploadStatus.DONE.value}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 1, - 'offset': None, - 'limit': None, - 'total': 2 - }, - 'uploads': [ + "result_set": {"count": 1, "offset": None, "limit": None, "total": 2}, + "uploads": [ { - 'batch_id': self.upload_id_list[0], - 'status': BatchRegisterPersonalInfoUploadStatus.DONE.value, - 'created': mock.ANY + "batch_id": self.upload_id_list[0], + "status": BatchRegisterPersonalInfoUploadStatus.DONE.value, + "created": mock.ANY, } - ] + ], } # Normal_4 @@ -227,37 +209,29 @@ def test_normal_4(self, client, db): batch_register_upload = BatchRegisterPersonalInfoUpload() batch_register_upload.issuer_address = _issuer_address batch_register_upload.upload_id = self.upload_id_list[1] - batch_register_upload.status = BatchRegisterPersonalInfoUploadStatus.PENDING.value + batch_register_upload.status = ( + BatchRegisterPersonalInfoUploadStatus.PENDING.value + ) db.add(batch_register_upload) # request target API resp = client.get( self.base_url.format(_token_address, self.upload_id_list[0]), - headers={ - "issuer-address": _issuer_address - }, - params={ - "offset": 0, - "limit": 1 - } + headers={"issuer-address": _issuer_address}, + params={"offset": 0, "limit": 1}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 2, - 'offset': 0, - 'limit': 1, - 'total': 2 - }, - 'uploads': [ + "result_set": {"count": 2, "offset": 0, "limit": 1, "total": 2}, + "uploads": [ { - 'batch_id': self.upload_id_list[1], - 'status': BatchRegisterPersonalInfoUploadStatus.PENDING.value, - 'created': mock.ANY + "batch_id": self.upload_id_list[1], + "status": BatchRegisterPersonalInfoUploadStatus.PENDING.value, + "created": mock.ANY, } - ] + ], } # Normal_5 @@ -287,41 +261,34 @@ def test_normal_5(self, client, db): batch_register_upload = BatchRegisterPersonalInfoUpload() batch_register_upload.issuer_address = _issuer_address batch_register_upload.upload_id = self.upload_id_list[1] - batch_register_upload.status = BatchRegisterPersonalInfoUploadStatus.PENDING.value + batch_register_upload.status = ( + BatchRegisterPersonalInfoUploadStatus.PENDING.value + ) db.add(batch_register_upload) # request target API resp = client.get( self.base_url.format(_token_address, self.upload_id_list[0]), - headers={ - "issuer-address": _issuer_address - }, - params={ - "sort_order": 0 - } + headers={"issuer-address": _issuer_address}, + params={"sort_order": 0}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 2, - 'offset': None, - 'limit': None, - 'total': 2 - }, - 'uploads': [ + "result_set": {"count": 2, "offset": None, "limit": None, "total": 2}, + "uploads": [ { - 'batch_id': self.upload_id_list[0], - 'status': BatchRegisterPersonalInfoUploadStatus.DONE.value, - 'created': mock.ANY + "batch_id": self.upload_id_list[0], + "status": BatchRegisterPersonalInfoUploadStatus.DONE.value, + "created": mock.ANY, }, { - 'batch_id': self.upload_id_list[1], - 'status': BatchRegisterPersonalInfoUploadStatus.PENDING.value, - 'created': mock.ANY - } - ] + "batch_id": self.upload_id_list[1], + "status": BatchRegisterPersonalInfoUploadStatus.PENDING.value, + "created": mock.ANY, + }, + ], } ######################################################################### @@ -347,24 +314,20 @@ def test_error_1(self, client, db): # request target API resp = client.get( - self.base_url.format(_token_address, self.upload_id_list[0]), - headers={} + self.base_url.format(_token_address, self.upload_id_list[0]), headers={} ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['header', 'issuer-address'], - 'msg': 'field required', - 'type': 'value_error.missing' + "loc": ["header", "issuer-address"], + "msg": "field required", + "type": "value_error.missing", } - ] + ], } # Error_2 @@ -398,17 +361,12 @@ def test_error_2(self, client, db): # request target API resp = client.get( self.base_url.format(_token_address, self.upload_id_list[0]), - headers={ - "issuer-address": _issuer_address_1 - } + headers={"issuer-address": _issuer_address_1}, ) # assertion assert resp.status_code == 404 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'NotFound' - }, - 'detail': 'token not found' + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } diff --git a/tests/test_app_routers_share_tokens_{token_address}_personal_info_batch_POST.py b/tests/test_app_routers_share_tokens_{token_address}_personal_info_batch_POST.py index 8b4c6dff..44b07c36 100644 --- a/tests/test_app_routers_share_tokens_{token_address}_personal_info_batch_POST.py +++ b/tests/test_app_routers_share_tokens_{token_address}_personal_info_batch_POST.py @@ -23,11 +23,11 @@ from app.model.db import ( Account, AuthToken, - Token, - TokenType, BatchRegisterPersonalInfo, BatchRegisterPersonalInfoUpload, - BatchRegisterPersonalInfoUploadStatus + BatchRegisterPersonalInfoUploadStatus, + Token, + TokenType, ) from app.utils.e2ee_utils import E2EEUtils from tests.account_config import config_eth_account @@ -77,7 +77,7 @@ def test_normal_1(self, client, db): "email": "test_email", "birth": "test_birth", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } # request target API req_param = [personal_info for _ in range(0, 10)] @@ -86,8 +86,8 @@ def test_normal_1(self, client, db): json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion @@ -95,14 +95,18 @@ def test_normal_1(self, client, db): assert resp.json() == { "batch_id": ANY, "status": BatchRegisterPersonalInfoUploadStatus.PENDING.value, - "created": ANY + "created": ANY, } - _upload: Optional[BatchRegisterPersonalInfoUpload] = db.query(BatchRegisterPersonalInfoUpload).first() + _upload: Optional[BatchRegisterPersonalInfoUpload] = db.query( + BatchRegisterPersonalInfoUpload + ).first() assert _upload.status == BatchRegisterPersonalInfoUploadStatus.PENDING.value assert _upload.issuer_address == _issuer_address - _register_list: list[BatchRegisterPersonalInfo] = db.query(BatchRegisterPersonalInfo).all() + _register_list: list[BatchRegisterPersonalInfo] = db.query( + BatchRegisterPersonalInfo + ).all() assert len(_register_list) == 10 # @@ -147,7 +151,7 @@ def test_normal_2(self, client, db): "email": "test_email", "birth": "test_birth", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } # request target API req_param = [personal_info for _ in range(0, 10)] @@ -156,8 +160,8 @@ def test_normal_2(self, client, db): json=req_param, headers={ "issuer-address": _issuer_address, - "auth-token": "test_auth_token" - } + "auth-token": "test_auth_token", + }, ) # assertion @@ -165,14 +169,18 @@ def test_normal_2(self, client, db): assert resp.json() == { "batch_id": ANY, "status": BatchRegisterPersonalInfoUploadStatus.PENDING.value, - "created": ANY + "created": ANY, } - _upload: Optional[BatchRegisterPersonalInfoUpload] = db.query(BatchRegisterPersonalInfoUpload).first() + _upload: Optional[BatchRegisterPersonalInfoUpload] = db.query( + BatchRegisterPersonalInfoUpload + ).first() assert _upload.status == BatchRegisterPersonalInfoUploadStatus.PENDING.value assert _upload.issuer_address == _issuer_address - _register_list: list[BatchRegisterPersonalInfo] = db.query(BatchRegisterPersonalInfo).all() + _register_list: list[BatchRegisterPersonalInfo] = db.query( + BatchRegisterPersonalInfo + ).all() assert len(_register_list) == 10 ########################################################################### @@ -193,28 +201,24 @@ def test_error_1_1(self, client, db): _token_address = "0xd9F55747DE740297ff1eEe537aBE0f8d73B7D783" # request target API - resp = client.post( - self.test_url.format(_token_address) - ) + resp = client.post(self.test_url.format(_token_address)) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "field required", - "type": "value_error.missing" - }, { + "type": "value_error.missing", + }, + { "loc": ["body"], "msg": "field required", - "type": "value_error.missing" - } - ] + "type": "value_error.missing", + }, + ], } # @@ -239,7 +243,7 @@ def test_error_1_2(self, client, db): "email": None, "birth": None, "is_corporate": None, - "tax_category": None + "tax_category": None, } # request target API req_param = [personal_info for _ in range(0, 10)] @@ -248,8 +252,8 @@ def test_error_1_2(self, client, db): json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) details = [] @@ -258,21 +262,21 @@ def test_error_1_2(self, client, db): { "loc": ["body", i, "account_address"], "msg": "none is not an allowed value", - "type": "type_error.none.not_allowed" - }) - details.append({ + "type": "type_error.none.not_allowed", + } + ) + details.append( + { "loc": ["body", i, "key_manager"], "msg": "none is not an allowed value", - "type": "type_error.none.not_allowed" - }) + "type": "type_error.none.not_allowed", + } + ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, - "detail": details + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": details, } # @@ -297,7 +301,7 @@ def test_error_1_3(self, client, db): "email": "test_email", "birth": "test_birth", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } # request target API req_param = [personal_info for _ in range(0, 10)] @@ -306,29 +310,22 @@ def test_error_1_3(self, client, db): json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "loc": [ - "body", - i, - "account_address" - ], + "loc": ["body", i, "account_address"], "msg": "account_address is not a valid address", - "type": "value_error" + "type": "value_error", } for i in range(0, 10) - ] + ], } # @@ -341,40 +338,39 @@ def test_error_1_4(self, client, db): _token_address = "0xd9F55747DE740297ff1eEe537aBE0f8d73B7D783" # request target API - req_param = [{ - "account_address": _test_account_address, - "key_manager": "test_key_manager", - "name": "test_name", - "postal_code": "test_postal_code", - "address": "test_address", - "email": "test_email", - "birth": "test_birth", - "is_corporate": False, - "tax_category": 10 - }] + req_param = [ + { + "account_address": _test_account_address, + "key_manager": "test_key_manager", + "name": "test_name", + "postal_code": "test_postal_code", + "address": "test_address", + "email": "test_email", + "birth": "test_birth", + "is_corporate": False, + "tax_category": 10, + } + ] resp = client.post( self.test_url.format(_token_address), json=req_param, headers={ "issuer-address": "test_issuer_address", - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -391,40 +387,39 @@ def test_error_1_5(self, client, db): _token_address = "0xd9F55747DE740297ff1eEe537aBE0f8d73B7D783" # request target API - req_param = [{ - "account_address": _test_account_address, - "key_manager": "test_key_manager", - "name": "test_name", - "postal_code": "test_postal_code", - "address": "test_address", - "email": "test_email", - "birth": "test_birth", - "is_corporate": False, - "tax_category": 10 - }] + req_param = [ + { + "account_address": _test_account_address, + "key_manager": "test_key_manager", + "name": "test_name", + "postal_code": "test_postal_code", + "address": "test_address", + "email": "test_email", + "birth": "test_birth", + "is_corporate": False, + "tax_category": 10, + } + ] resp = client.post( self.test_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": "not_encrypted_password" - } + "eoa-password": "not_encrypted_password", + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "eoa-password"], "msg": "eoa-password is not a Base64-encoded encrypted data", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -441,34 +436,33 @@ def test_error_2_1(self, client, db): _token_address = "0xd9F55747DE740297ff1eEe537aBE0f8d73B7D783" # request target API - req_param = [{ - "account_address": _test_account_address, - "key_manager": "test_key_manager", - "name": "test_name", - "postal_code": "test_postal_code", - "address": "test_address", - "email": "test_email", - "birth": "test_birth", - "is_corporate": False, - "tax_category": 10 - }] + req_param = [ + { + "account_address": _test_account_address, + "key_manager": "test_key_manager", + "name": "test_name", + "postal_code": "test_postal_code", + "address": "test_address", + "email": "test_email", + "birth": "test_birth", + "is_corporate": False, + "tax_category": 10, + } + ] resp = client.post( self.test_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -492,34 +486,33 @@ def test_error_2_2(self, client, db): db.add(account) # request target API - req_param = [{ - "account_address": _test_account_address, - "key_manager": "test_key_manager", - "name": "test_name", - "postal_code": "test_postal_code", - "address": "test_address", - "email": "test_email", - "birth": "test_birth", - "is_corporate": False, - "tax_category": 10 - }] + req_param = [ + { + "account_address": _test_account_address, + "key_manager": "test_key_manager", + "name": "test_name", + "postal_code": "test_postal_code", + "address": "test_address", + "email": "test_email", + "birth": "test_birth", + "is_corporate": False, + "tax_category": 10, + } + ] resp = client.post( self.test_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("mismatch_password") - } + "eoa-password": E2EEUtils.encrypt("mismatch_password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -543,34 +536,33 @@ def test_error_3(self, client, db): db.add(account) # request target API - req_param = [{ - "account_address": _test_account_address, - "key_manager": "test_key_manager", - "name": "test_name", - "postal_code": "test_postal_code", - "address": "test_address", - "email": "test_email", - "birth": "test_birth", - "is_corporate": False, - "tax_category": 10 - }] + req_param = [ + { + "account_address": _test_account_address, + "key_manager": "test_key_manager", + "name": "test_name", + "postal_code": "test_postal_code", + "address": "test_address", + "email": "test_email", + "birth": "test_birth", + "is_corporate": False, + "tax_category": 10, + } + ] resp = client.post( self.test_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # @@ -603,34 +595,33 @@ def test_error_4_1(self, client, db): db.add(token) # request target API - req_param = [{ - "account_address": _test_account_address, - "key_manager": "test_key_manager", - "name": "test_name", - "postal_code": "test_postal_code", - "address": "test_address", - "email": "test_email", - "birth": "test_birth", - "is_corporate": False, - "tax_category": 10 - }] + req_param = [ + { + "account_address": _test_account_address, + "key_manager": "test_key_manager", + "name": "test_name", + "postal_code": "test_postal_code", + "address": "test_address", + "email": "test_email", + "birth": "test_birth", + "is_corporate": False, + "tax_category": 10, + } + ] resp = client.post( self.test_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } # @@ -669,16 +660,13 @@ def test_error_4_2(self, client, db): json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "personal information list must not be empty" - } \ No newline at end of file + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "personal information list must not be empty", + } diff --git a/tests/test_app_routers_share_tokens_{token_address}_personal_info_batch_{batch_id}_GET.py b/tests/test_app_routers_share_tokens_{token_address}_personal_info_batch_{batch_id}_GET.py index e50c94c3..dfbb1a92 100644 --- a/tests/test_app_routers_share_tokens_{token_address}_personal_info_batch_{batch_id}_GET.py +++ b/tests/test_app_routers_share_tokens_{token_address}_personal_info_batch_{batch_id}_GET.py @@ -16,16 +16,15 @@ SPDX-License-Identifier: Apache-2.0 """ -from app.utils.e2ee_utils import E2EEUtils - from app.model.db import ( - TokenType, Account, - Token, + BatchRegisterPersonalInfo, BatchRegisterPersonalInfoUpload, BatchRegisterPersonalInfoUploadStatus, - BatchRegisterPersonalInfo + Token, + TokenType, ) +from app.utils.e2ee_utils import E2EEUtils from tests.account_config import config_eth_account @@ -39,26 +38,30 @@ class TestAppRoutersShareTokensTokenAddressPersonalInfoBatchBatchIdGET: "0f33d48f-9e6e-4a36-a55e-5bbcbda69c80", "1c961f7d-e1ad-40e5-988b-cca3d6009643", "1e778f46-864e-4ec0-b566-21bd31cf63ff", - "1f33d48f-9e6e-4a36-a55e-5bbcbda69c80" + "1f33d48f-9e6e-4a36-a55e-5bbcbda69c80", ] account_list = [ { "address": config_eth_account("user1")["address"], - "keyfile": config_eth_account("user1")["keyfile_json"] - }, { + "keyfile": config_eth_account("user1")["keyfile_json"], + }, + { "address": config_eth_account("user2")["address"], - "keyfile": config_eth_account("user2")["keyfile_json"] - }, { + "keyfile": config_eth_account("user2")["keyfile_json"], + }, + { "address": config_eth_account("user3")["address"], - "keyfile": config_eth_account("user3")["keyfile_json"] - }, { + "keyfile": config_eth_account("user3")["keyfile_json"], + }, + { "address": config_eth_account("user4")["address"], - "keyfile": config_eth_account("user4")["keyfile_json"] - }, { + "keyfile": config_eth_account("user4")["keyfile_json"], + }, + { "address": config_eth_account("user5")["address"], - "keyfile": config_eth_account("user5")["keyfile_json"] - } + "keyfile": config_eth_account("user5")["keyfile_json"], + }, ] ########################################################################### @@ -95,7 +98,9 @@ def test_normal_1(self, client, db): batch_register_upload = BatchRegisterPersonalInfoUpload() batch_register_upload.issuer_address = _issuer_address batch_register_upload.upload_id = self.upload_id_list[0] - batch_register_upload.status = BatchRegisterPersonalInfoUploadStatus.PENDING.value + batch_register_upload.status = ( + BatchRegisterPersonalInfoUploadStatus.PENDING.value + ) db.add(batch_register_upload) # Prepare data : BatchRegisterPersonalInfo @@ -113,56 +118,58 @@ def test_normal_1(self, client, db): "email": "test_value@a.test", "birth": "19900101", "is_corporate": True, - "tax_category": 3 + "tax_category": 3, } db.add(batch_register) # request target API resp = client.get( self.base_url.format(_token_address, self.upload_id_list[0]), - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 200 assert resp.json() == { "status": BatchRegisterPersonalInfoUploadStatus.PENDING.value, - "results": [{ - "status": 0, - "account_address": self.account_list[0]["address"], - "key_manager": "test_value", - "name": "test_value", - "postal_code": "1000001", - "address": "test_value", - "email": "test_value@a.test", - "birth": "19900101", - "is_corporate": True, - "tax_category": 3 - }, { - "status": 0, - "account_address": self.account_list[1]["address"], - "key_manager": "test_value", - "name": "test_value", - "postal_code": "1000001", - "address": "test_value", - "email": "test_value@a.test", - "birth": "19900101", - "is_corporate": True, - "tax_category": 3 - }, { - "status": 0, - "account_address": self.account_list[2]["address"], - "key_manager": "test_value", - "name": "test_value", - "postal_code": "1000001", - "address": "test_value", - "email": "test_value@a.test", - "birth": "19900101", - "is_corporate": True, - "tax_category": 3 - }] + "results": [ + { + "status": 0, + "account_address": self.account_list[0]["address"], + "key_manager": "test_value", + "name": "test_value", + "postal_code": "1000001", + "address": "test_value", + "email": "test_value@a.test", + "birth": "19900101", + "is_corporate": True, + "tax_category": 3, + }, + { + "status": 0, + "account_address": self.account_list[1]["address"], + "key_manager": "test_value", + "name": "test_value", + "postal_code": "1000001", + "address": "test_value", + "email": "test_value@a.test", + "birth": "19900101", + "is_corporate": True, + "tax_category": 3, + }, + { + "status": 0, + "account_address": self.account_list[2]["address"], + "key_manager": "test_value", + "name": "test_value", + "postal_code": "1000001", + "address": "test_value", + "email": "test_value@a.test", + "birth": "19900101", + "is_corporate": True, + "tax_category": 3, + }, + ], } ######################################################################### @@ -178,25 +185,20 @@ def test_error_1(self, client, db): # request target API resp = client.get( - self.base_url.format(_token_address, "test_batch_id"), - headers={ - } + self.base_url.format(_token_address, "test_batch_id"), headers={} ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['header', 'issuer-address'], - 'msg': 'field required', - 'type': 'value_error.missing' + "loc": ["header", "issuer-address"], + "msg": "field required", + "type": "value_error.missing", } - ] + ], } # @@ -211,14 +213,12 @@ def test_error_2(self, client, db): self.base_url.format(_token_address, "test_batch_id"), headers={ "issuer-address": _issuer_address, - } + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, "title": "NotFound" - }, - "detail": "batch not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "batch not found", } diff --git a/tests/test_app_routers_share_tokens_{token_address}_redeem_GET.py b/tests/test_app_routers_share_tokens_{token_address}_redeem_GET.py index 9e711263..1abc23e0 100644 --- a/tests/test_app_routers_share_tokens_{token_address}_redeem_GET.py +++ b/tests/test_app_routers_share_tokens_{token_address}_redeem_GET.py @@ -22,17 +22,17 @@ import config from app.model.db import ( + IDXIssueRedeem, + IDXIssueRedeemEventType, + IDXIssueRedeemSortItem, Token, TokenType, - IDXIssueRedeem, - IDXIssueRedeemEventType, IDXIssueRedeemSortItem ) local_tz = timezone(config.TZ) class TestAppRoutersShareTokensTokenAddressRedeemGET: - # target API endpoint base_url = "/share/tokens/{}/redeem" @@ -48,9 +48,9 @@ class TestAppRoutersShareTokensTokenAddressRedeemGET: test_amount = [10, 20, 30] test_block_timestamp = [ - datetime.strptime("2022/01/02 15:20:30", '%Y/%m/%d %H:%M:%S'), # JST 2022/01/03 - datetime.strptime("2022/01/01 15:20:30", '%Y/%m/%d %H:%M:%S'), # JST 2022/01/02 - datetime.strptime("2022/01/02 00:20:30", '%Y/%m/%d %H:%M:%S'), # JST 2022/01/02 + datetime.strptime("2022/01/02 15:20:30", "%Y/%m/%d %H:%M:%S"), # JST 2022/01/03 + datetime.strptime("2022/01/01 15:20:30", "%Y/%m/%d %H:%M:%S"), # JST 2022/01/02 + datetime.strptime("2022/01/02 00:20:30", "%Y/%m/%d %H:%M:%S"), # JST 2022/01/02 ] test_block_timestamp_str = [ "2022-01-03T00:20:30+09:00", @@ -86,20 +86,13 @@ def test_normal_1(self, client, db): db.add(_record) # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 0, - 'offset': None, - 'limit': None, - 'total': 0 - }, - 'history': [] + "result_set": {"count": 0, "offset": None, "limit": None, "total": 0}, + "history": [], } # Normal_2 @@ -146,45 +139,38 @@ def test_normal_2(self, client, db): db.add(_record) # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 3, - 'offset': None, - 'limit': None, - 'total': 3 - }, - 'history': [ + "result_set": {"count": 3, "offset": None, "limit": None, "total": 3}, + "history": [ { - 'transaction_hash': self.test_transaction_hash, - 'token_address': self.test_token_address, - 'locked_address': self.test_locked_address, - 'target_address': self.test_target_address, - 'amount': self.test_amount[0], - 'block_timestamp': self.test_block_timestamp_str[0] + "transaction_hash": self.test_transaction_hash, + "token_address": self.test_token_address, + "locked_address": self.test_locked_address, + "target_address": self.test_target_address, + "amount": self.test_amount[0], + "block_timestamp": self.test_block_timestamp_str[0], }, { - 'transaction_hash': self.test_transaction_hash, - 'token_address': self.test_token_address, - 'locked_address': self.test_locked_address, - 'target_address': self.test_target_address, - 'amount': self.test_amount[2], - 'block_timestamp': self.test_block_timestamp_str[2] + "transaction_hash": self.test_transaction_hash, + "token_address": self.test_token_address, + "locked_address": self.test_locked_address, + "target_address": self.test_target_address, + "amount": self.test_amount[2], + "block_timestamp": self.test_block_timestamp_str[2], }, { - 'transaction_hash': self.test_transaction_hash, - 'token_address': self.test_token_address, - 'locked_address': self.test_locked_address, - 'target_address': self.test_target_address, - 'amount': self.test_amount[1], - 'block_timestamp': self.test_block_timestamp_str[1] - } - ] + "transaction_hash": self.test_transaction_hash, + "token_address": self.test_token_address, + "locked_address": self.test_locked_address, + "target_address": self.test_target_address, + "amount": self.test_amount[1], + "block_timestamp": self.test_block_timestamp_str[1], + }, + ], } # Normal_3 @@ -235,45 +221,40 @@ def test_normal_3(self, client, db): self.base_url.format(self.test_token_address), params={ "sort_item": IDXIssueRedeemSortItem.BLOCK_TIMESTAMP.value, - "sort_order": 0 - } + "sort_order": 0, + }, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 3, - 'offset': None, - 'limit': None, - 'total': 3 - }, - 'history': [ + "result_set": {"count": 3, "offset": None, "limit": None, "total": 3}, + "history": [ { - 'transaction_hash': self.test_transaction_hash, - 'token_address': self.test_token_address, - 'locked_address': self.test_locked_address, - 'target_address': self.test_target_address, - 'amount': self.test_amount[1], - 'block_timestamp': self.test_block_timestamp_str[1] + "transaction_hash": self.test_transaction_hash, + "token_address": self.test_token_address, + "locked_address": self.test_locked_address, + "target_address": self.test_target_address, + "amount": self.test_amount[1], + "block_timestamp": self.test_block_timestamp_str[1], }, { - 'transaction_hash': self.test_transaction_hash, - 'token_address': self.test_token_address, - 'locked_address': self.test_locked_address, - 'target_address': self.test_target_address, - 'amount': self.test_amount[2], - 'block_timestamp': self.test_block_timestamp_str[2] + "transaction_hash": self.test_transaction_hash, + "token_address": self.test_token_address, + "locked_address": self.test_locked_address, + "target_address": self.test_target_address, + "amount": self.test_amount[2], + "block_timestamp": self.test_block_timestamp_str[2], }, { - 'transaction_hash': self.test_transaction_hash, - 'token_address': self.test_token_address, - 'locked_address': self.test_locked_address, - 'target_address': self.test_target_address, - 'amount': self.test_amount[0], - 'block_timestamp': self.test_block_timestamp_str[0] - } - ] + "transaction_hash": self.test_transaction_hash, + "token_address": self.test_token_address, + "locked_address": self.test_locked_address, + "target_address": self.test_target_address, + "amount": self.test_amount[0], + "block_timestamp": self.test_block_timestamp_str[0], + }, + ], } # Normal_4 @@ -322,31 +303,23 @@ def test_normal_4(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "offset": 1, - "limit": 1 - } + params={"offset": 1, "limit": 1}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'result_set': { - 'count': 3, - 'offset': 1, - 'limit': 1, - 'total': 3 - }, - 'history': [ + "result_set": {"count": 3, "offset": 1, "limit": 1, "total": 3}, + "history": [ { - 'transaction_hash': self.test_transaction_hash, - 'token_address': self.test_token_address, - 'locked_address': self.test_locked_address, - 'target_address': self.test_target_address, - 'amount': self.test_amount[2], - 'block_timestamp': self.test_block_timestamp_str[2] + "transaction_hash": self.test_transaction_hash, + "token_address": self.test_token_address, + "locked_address": self.test_locked_address, + "target_address": self.test_target_address, + "amount": self.test_amount[2], + "block_timestamp": self.test_block_timestamp_str[2], } - ] + ], } ########################################################################### @@ -357,18 +330,13 @@ def test_normal_4(self, client, db): # NotFound def test_error_1(self, client, db): # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # Error_2 @@ -386,18 +354,13 @@ def test_error_2(self, client, db): db.add(_token) # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } # Error_3 @@ -407,33 +370,28 @@ def test_error_3(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "sort_item": "block_timestamp12345" - } + params={"sort_item": "block_timestamp12345"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['query', 'sort_item'], - 'msg': "value is not a valid enumeration member; permitted: 'block_timestamp', 'locked_address', 'target_address', 'amount'", - 'type': 'type_error.enum', - 'ctx': { - 'enum_values': [ - 'block_timestamp', - 'locked_address', - 'target_address', - 'amount' + "loc": ["query", "sort_item"], + "msg": "value is not a valid enumeration member; permitted: 'block_timestamp', 'locked_address', 'target_address', 'amount'", + "type": "type_error.enum", + "ctx": { + "enum_values": [ + "block_timestamp", + "locked_address", + "target_address", + "amount", ] - } + }, } - ] + ], } # Error_4_1 @@ -442,27 +400,21 @@ def test_error_3(self, client, db): def test_error_4_1(self, client, db): # request target API resp = client.get( - self.base_url.format(self.test_token_address), - params={ - "sort_order": -1 - } + self.base_url.format(self.test_token_address), params={"sort_order": -1} ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "ctx": {"limit_value": 0}, "loc": ["query", "sort_order"], "msg": "ensure this value is greater than or equal to 0", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", } - ] + ], } # Error_4_2 @@ -471,25 +423,19 @@ def test_error_4_1(self, client, db): def test_error_4_2(self, client, db): # request target API resp = client.get( - self.base_url.format(self.test_token_address), - params={ - "sort_order": 2 - } + self.base_url.format(self.test_token_address), params={"sort_order": 2} ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "ctx": {"limit_value": 1}, "loc": ["query", "sort_order"], "msg": "ensure this value is less than or equal to 1", - "type": "value_error.number.not_le" + "type": "value_error.number.not_le", } - ] + ], } diff --git a/tests/test_app_routers_share_tokens_{token_address}_redeem_POST.py b/tests/test_app_routers_share_tokens_{token_address}_redeem_POST.py index f6f278b5..f90b406a 100644 --- a/tests/test_app_routers_share_tokens_{token_address}_redeem_POST.py +++ b/tests/test_app_routers_share_tokens_{token_address}_redeem_POST.py @@ -20,14 +20,9 @@ from unittest import mock from unittest.mock import ANY, MagicMock -from app.model.db import ( - Account, - AuthToken, - Token, - TokenType -) -from app.utils.e2ee_utils import E2EEUtils from app.exceptions import SendTransactionError +from app.model.db import Account, AuthToken, Token, TokenType +from app.utils.e2ee_utils import E2EEUtils from tests.account_config import config_eth_account @@ -67,24 +62,19 @@ def test_normal_1(self, IbetShareContract_mock, client, db): IbetShareContract_mock.side_effect = [None] # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion IbetShareContract_mock.assert_any_call( - data=req_param, - tx_from=_issuer_address, - private_key=ANY + data=req_param, tx_from=_issuer_address, private_key=ANY ) assert resp.status_code == 200 @@ -124,24 +114,19 @@ def test_normal_2(self, IbetShareContract_mock, client, db): IbetShareContract_mock.side_effect = [None] # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "auth-token": "test_auth_token" - } + "auth-token": "test_auth_token", + }, ) # assertion IbetShareContract_mock.assert_any_call( - data=req_param, - tx_from=_issuer_address, - private_key=ANY + data=req_param, tx_from=_issuer_address, private_key=ANY ) assert resp.status_code == 200 @@ -157,29 +142,24 @@ def test_error_1(self, client, db): _token_address = "token_address_test" # request target API - resp = client.post( - self.base_url.format(_token_address) - ) + resp = client.post(self.base_url.format(_token_address)) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, { "loc": ["body"], "msg": "field required", - "type": "value_error.missing" - } - ] + "type": "value_error.missing", + }, + ], } # @@ -190,43 +170,30 @@ def test_error_2(self, client, db): _token_address = "token_address_test" # request target API - req_param = { - "account_address": "0x0", - "amount": 0 - } + req_param = {"account_address": "0x0", "amount": 0} resp = client.post( self.base_url.format(_token_address), json=req_param, - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "account_address"], "msg": "account_address is not a valid address", - "type": "value_error" + "type": "value_error", }, { - "ctx": { - "limit_value": 1 - }, - "loc": [ - "body", - "amount" - ], + "ctx": {"limit_value": 1}, + "loc": ["body", "amount"], "msg": "ensure this value is greater than or equal to 1", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, - ] + ], } # @@ -237,38 +204,25 @@ def test_error_3(self, client, db): _token_address = "token_address_test" # request target API - req_param = { - "account_address": _issuer_address, - "amount": 1_000_000_000_001 - } + req_param = {"account_address": _issuer_address, "amount": 1_000_000_000_001} resp = client.post( self.base_url.format(_token_address), json=req_param, - headers={ - "issuer-address": _issuer_address - } + headers={"issuer-address": _issuer_address}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "ctx": { - "limit_value": 1_000_000_000_000 - }, - "loc": [ - "body", - "amount" - ], + "ctx": {"limit_value": 1_000_000_000_000}, + "loc": ["body", "amount"], "msg": "ensure this value is less than or equal to 1000000000000", - "type": "value_error.number.not_le" + "type": "value_error.number.not_le", }, - ] + ], } # @@ -279,32 +233,24 @@ def test_error_4(self, client, db): _token_address = "token_address_test" # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, - headers={ - "issuer-address": "issuer-address" - } + headers={"issuer-address": "issuer-address"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -325,32 +271,25 @@ def test_error_5(self, client, db): db.add(token) # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, - headers={ - "issuer-address": _issuer_address, - "eoa-password": "password" - } + headers={"issuer-address": _issuer_address, "eoa-password": "password"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, - "detail": [{ - "loc": ["header", "eoa-password"], - "msg": "eoa-password is not a Base64-encoded encrypted data", - "type": "value_error" - }] + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ + { + "loc": ["header", "eoa-password"], + "msg": "eoa-password is not a Base64-encoded encrypted data", + "type": "value_error", + } + ], } # @@ -371,28 +310,22 @@ def test_error_6(self, client, db): db.add(token) # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -411,26 +344,20 @@ def test_error_7(self, client, db): db.add(account) # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password_test") - } + "eoa-password": E2EEUtils.encrypt("password_test"), + }, ) assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -449,26 +376,20 @@ def test_error_8(self, client, db): db.add(account) # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # @@ -496,33 +417,29 @@ def test_error_9(self, client, db): db.add(token) # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } # # Send Transaction Error - @mock.patch("app.model.blockchain.token.IbetShareContract.redeem", - MagicMock(side_effect=SendTransactionError())) + @mock.patch( + "app.model.blockchain.token.IbetShareContract.redeem", + MagicMock(side_effect=SendTransactionError()), + ) def test_error_10(self, client, db): test_account = config_eth_account("user1") _issuer_address = test_account["address"] @@ -545,25 +462,19 @@ def test_error_10(self, client, db): db.add(token) # request target API - req_param = { - "account_address": _issuer_address, - "amount": 10 - } + req_param = {"account_address": _issuer_address, "amount": 10} resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 2, - "title": "SendTransactionError" - }, - "detail": "failed to send transaction" + "meta": {"code": 2, "title": "SendTransactionError"}, + "detail": "failed to send transaction", } diff --git a/tests/test_app_routers_share_tokens_{token_address}_redeem_batch_GET.py b/tests/test_app_routers_share_tokens_{token_address}_redeem_batch_GET.py index 0c351f1b..2e486f87 100644 --- a/tests/test_app_routers_share_tokens_{token_address}_redeem_batch_GET.py +++ b/tests/test_app_routers_share_tokens_{token_address}_redeem_batch_GET.py @@ -20,10 +20,10 @@ from unittest import mock from app.model.db import ( + BatchIssueRedeemProcessingCategory, + BatchIssueRedeemUpload, Token, TokenType, - BatchIssueRedeemUpload, - BatchIssueRedeemProcessingCategory ) from tests.account_config import config_eth_account @@ -53,21 +53,13 @@ def test_normal_1(self, client, db): db.add(token) # request target API - resp = client.get( - self.base_url.format(token_address), - headers={} - ) + resp = client.get(self.base_url.format(token_address), headers={}) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 0, - "limit": None, - "offset": None, - "total": 0 - }, - "uploads": [] - } + "result_set": {"count": 0, "limit": None, "offset": None, "total": 0}, + "uploads": [], + } # # 1 record @@ -95,30 +87,21 @@ def test_normal_2(self, client, db): db.add(redeem_upload1) # request target API - resp = client.get( - self.base_url.format(token_address), - headers={} - ) + resp = client.get(self.base_url.format(token_address), headers={}) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 1, - "limit": None, - "offset": None, - "total": 1 - }, - "uploads": - [ + "result_set": {"count": 1, "limit": None, "offset": None, "total": 1}, + "uploads": [ { "issuer_address": issuer_address, "processed": False, "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, } - ] + ], } # @@ -184,19 +167,11 @@ def test_normal_3_1(self, client, db): db.add(redeem_upload5) # request target API - resp = client.get( - self.base_url.format(token_address), - headers={} - ) + resp = client.get(self.base_url.format(token_address), headers={}) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 4, - "limit": None, - "offset": None, - "total": 4 - }, + "result_set": {"count": 4, "limit": None, "offset": None, "total": 4}, "uploads": [ { "issuer_address": issuer_address, @@ -204,7 +179,7 @@ def test_normal_3_1(self, client, db): "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -212,7 +187,7 @@ def test_normal_3_1(self, client, db): "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -220,7 +195,7 @@ def test_normal_3_1(self, client, db): "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -228,9 +203,9 @@ def test_normal_3_1(self, client, db): "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY - } - ] + "created": mock.ANY, + }, + ], } # @@ -298,19 +273,12 @@ def test_normal_3_2(self, client, db): # request target API resp = client.get( self.base_url.format(token_address), - headers={ - "issuer-address": issuer_address - } + headers={"issuer-address": issuer_address}, ) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 2, - "limit": None, - "offset": None, - "total": 2 - }, + "result_set": {"count": 2, "limit": None, "offset": None, "total": 2}, "uploads": [ { "issuer_address": issuer_address, @@ -318,7 +286,7 @@ def test_normal_3_2(self, client, db): "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -326,10 +294,10 @@ def test_normal_3_2(self, client, db): "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY - } - ] - } + "created": mock.ANY, + }, + ], + } # # Multi record (status) @@ -394,31 +362,20 @@ def test_normal_3_3(self, client, db): db.add(redeem_upload5) # request target API - req_param = { - "processed": False - } - resp = client.get( - self.base_url.format(token_address), - params=req_param - ) + req_param = {"processed": False} + resp = client.get(self.base_url.format(token_address), params=req_param) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 3, - "limit": None, - "offset": None, - "total": 4 - }, - "uploads": - [ + "result_set": {"count": 3, "limit": None, "offset": None, "total": 4}, + "uploads": [ { "issuer_address": issuer_address, "processed": False, "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -426,7 +383,7 @@ def test_normal_3_3(self, client, db): "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -434,9 +391,9 @@ def test_normal_3_3(self, client, db): "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY - } - ] + "created": mock.ANY, + }, + ], } # @@ -502,23 +459,12 @@ def test_normal_4(self, client, db): db.add(redeem_upload5) # request target API - req_param = { - "limit": 2, - "offset": 2 - } - resp = client.get( - self.base_url.format(token_address), - params=req_param - ) + req_param = {"limit": 2, "offset": 2} + resp = client.get(self.base_url.format(token_address), params=req_param) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 4, - "limit": 2, - "offset": 2, - "total": 4 - }, + "result_set": {"count": 4, "limit": 2, "offset": 2, "total": 4}, "uploads": [ { "issuer_address": issuer_address, @@ -526,7 +472,7 @@ def test_normal_4(self, client, db): "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -534,9 +480,9 @@ def test_normal_4(self, client, db): "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY - } - ] + "created": mock.ANY, + }, + ], } # @@ -561,7 +507,9 @@ def test_normal_5(self, client, db): additional_issue_upload1.token_address = token_address additional_issue_upload1.issuer_address = issuer_address additional_issue_upload1.token_type = TokenType.IBET_SHARE.value - additional_issue_upload1.category = BatchIssueRedeemProcessingCategory.REDEEM.value + additional_issue_upload1.category = ( + BatchIssueRedeemProcessingCategory.REDEEM.value + ) additional_issue_upload1.processed = True db.add(additional_issue_upload1) @@ -570,7 +518,9 @@ def test_normal_5(self, client, db): additional_issue_upload2.token_address = token_address additional_issue_upload2.issuer_address = issuer_address additional_issue_upload2.token_type = TokenType.IBET_SHARE.value - additional_issue_upload2.category = BatchIssueRedeemProcessingCategory.REDEEM.value + additional_issue_upload2.category = ( + BatchIssueRedeemProcessingCategory.REDEEM.value + ) additional_issue_upload2.processed = False db.add(additional_issue_upload2) @@ -579,7 +529,9 @@ def test_normal_5(self, client, db): additional_issue_upload3.token_address = token_address additional_issue_upload3.issuer_address = issuer_address additional_issue_upload3.token_type = TokenType.IBET_SHARE.value - additional_issue_upload3.category = BatchIssueRedeemProcessingCategory.REDEEM.value + additional_issue_upload3.category = ( + BatchIssueRedeemProcessingCategory.REDEEM.value + ) additional_issue_upload3.processed = True db.add(additional_issue_upload3) @@ -588,7 +540,9 @@ def test_normal_5(self, client, db): additional_issue_upload4.token_address = token_address additional_issue_upload4.issuer_address = issuer_address additional_issue_upload4.token_type = TokenType.IBET_SHARE.value - additional_issue_upload4.category = BatchIssueRedeemProcessingCategory.REDEEM.value + additional_issue_upload4.category = ( + BatchIssueRedeemProcessingCategory.REDEEM.value + ) additional_issue_upload4.processed = False db.add(additional_issue_upload4) @@ -597,27 +551,19 @@ def test_normal_5(self, client, db): additional_issue_upload5.token_address = "other_token" additional_issue_upload5.issuer_address = issuer_address additional_issue_upload5.token_type = TokenType.IBET_SHARE.value - additional_issue_upload5.category = BatchIssueRedeemProcessingCategory.REDEEM.value + additional_issue_upload5.category = ( + BatchIssueRedeemProcessingCategory.REDEEM.value + ) additional_issue_upload5.processed = False db.add(additional_issue_upload5) # request target API - req_param = { - "sort_order": 0 - } - resp = client.get( - self.base_url.format(token_address), - params=req_param - ) + req_param = {"sort_order": 0} + resp = client.get(self.base_url.format(token_address), params=req_param) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 4, - "limit": None, - "offset": None, - "total": 4 - }, + "result_set": {"count": 4, "limit": None, "offset": None, "total": 4}, "uploads": [ { "issuer_address": issuer_address, @@ -625,7 +571,7 @@ def test_normal_5(self, client, db): "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -633,7 +579,7 @@ def test_normal_5(self, client, db): "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -641,7 +587,7 @@ def test_normal_5(self, client, db): "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY + "created": mock.ANY, }, { "issuer_address": issuer_address, @@ -649,9 +595,9 @@ def test_normal_5(self, client, db): "token_address": "token_address_test", "token_type": "IbetShare", "batch_id": mock.ANY, - "created": mock.ANY - } - ] + "created": mock.ANY, + }, + ], } ########################################################################### @@ -677,13 +623,8 @@ def test_error_1(self, client, db): db.add(token) # request target API - req_param = { - "processed": "invalid_value" - } - resp = client.get( - self.base_url.format(token_address), - params=req_param - ) + req_param = {"processed": "invalid_value"} + resp = client.get(self.base_url.format(token_address), params=req_param) assert resp.status_code == 422 assert resp.json() == { @@ -691,10 +632,8 @@ def test_error_1(self, client, db): { "loc": ["query", "processed"], "msg": "value could not be parsed to a boolean", - "type": "type_error.bool" + "type": "type_error.bool", } ], - "meta": { - "code": 1, "title": "RequestValidationError" - } + "meta": {"code": 1, "title": "RequestValidationError"}, } diff --git a/tests/test_app_routers_share_tokens_{token_address}_redeem_batch_POST.py b/tests/test_app_routers_share_tokens_{token_address}_redeem_batch_POST.py index 8cb2fd20..a03a9eeb 100644 --- a/tests/test_app_routers_share_tokens_{token_address}_redeem_batch_POST.py +++ b/tests/test_app_routers_share_tokens_{token_address}_redeem_batch_POST.py @@ -20,10 +20,11 @@ from app.model.db import ( Account, + BatchIssueRedeem, + BatchIssueRedeemProcessingCategory, + BatchIssueRedeemUpload, Token, TokenType, - BatchIssueRedeemUpload, - BatchIssueRedeem, BatchIssueRedeemProcessingCategory ) from app.utils.e2ee_utils import E2EEUtils from tests.account_config import config_eth_account @@ -64,23 +65,20 @@ def test_normal_1(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 10 - } - ] + req_param = [{"account_address": test_account_1, "amount": 10}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion - upload: Optional[BatchIssueRedeemUpload] = db.query(BatchIssueRedeemUpload).first() + upload: Optional[BatchIssueRedeemUpload] = db.query( + BatchIssueRedeemUpload + ).first() assert upload.issuer_address == issuer_address assert upload.token_type == TokenType.IBET_SHARE.value assert upload.token_address == token_address @@ -128,26 +126,22 @@ def test_normal_2(self, client, db): # request target API req_param = [ - { - "account_address": test_account_1, - "amount": 10 - }, - { - "account_address": test_account_2, - "amount": 20 - } + {"account_address": test_account_1, "amount": 10}, + {"account_address": test_account_2, "amount": 20}, ] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion - upload: Optional[BatchIssueRedeemUpload] = db.query(BatchIssueRedeemUpload).first() + upload: Optional[BatchIssueRedeemUpload] = db.query( + BatchIssueRedeemUpload + ).first() assert upload.issuer_address == issuer_address assert upload.token_type == TokenType.IBET_SHARE.value assert upload.token_address == token_address @@ -207,24 +201,21 @@ def test_error_1_1(self, client, db): json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['body'], - 'msg': 'value is not a valid list', - 'type': 'type_error.list' + "loc": ["body"], + "msg": "value is not a valid list", + "type": "type_error.list", } - ] + ], } # Error_1_2 @@ -252,35 +243,27 @@ def test_error_1_2(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": "0x0", - "amount": 10 - } - ] + req_param = [{"account_address": "0x0", "amount": 10}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['body', 0, 'account_address'], - 'msg': 'account_address is not a valid address', - 'type': 'value_error' + "loc": ["body", 0, "account_address"], + "msg": "account_address is not a valid address", + "type": "value_error", } - ] + ], } # Error_1_3_1 @@ -310,36 +293,28 @@ def test_error_1_3_1(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 0 - } - ] + req_param = [{"account_address": test_account_1, "amount": 0}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['body', 0, 'amount'], - 'msg': 'ensure this value is greater than or equal to 1', - 'type': 'value_error.number.not_ge', - 'ctx': {'limit_value': 1} + "loc": ["body", 0, "amount"], + "msg": "ensure this value is greater than or equal to 1", + "type": "value_error.number.not_ge", + "ctx": {"limit_value": 1}, } - ] + ], } # Error_1_3_2 @@ -369,36 +344,28 @@ def test_error_1_3_2(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 1_000_000_000_001 - } - ] + req_param = [{"account_address": test_account_1, "amount": 1_000_000_000_001}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['body', 0, 'amount'], - 'msg': 'ensure this value is less than or equal to 1000000000000', - 'type': 'value_error.number.not_le', - 'ctx': {'limit_value': 1000000000000} + "loc": ["body", 0, "amount"], + "msg": "ensure this value is less than or equal to 1000000000000", + "type": "value_error.number.not_le", + "ctx": {"limit_value": 1000000000000}, } - ] + ], } # Error_1_4 @@ -428,32 +395,22 @@ def test_error_1_4(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 10 - } - ] + req_param = [{"account_address": test_account_1, "amount": 10}] resp = client.post( - self.base_url.format(token_address), - json=req_param, - headers=None + self.base_url.format(token_address), json=req_param, headers=None ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['header', 'issuer-address'], - 'msg': 'field required', - 'type': 'value_error.missing' + "loc": ["header", "issuer-address"], + "msg": "field required", + "type": "value_error.missing", } - ] + ], } # Error_1_5 @@ -483,35 +440,24 @@ def test_error_1_5(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 10 - } - ] + req_param = [{"account_address": test_account_1, "amount": 10}] resp = client.post( self.base_url.format(token_address), json=req_param, - headers={ - "issuer-address": issuer_address, - "eoa-password": "password" - } + headers={"issuer-address": issuer_address, "eoa-password": "password"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'RequestValidationError' - }, - 'detail': [ + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ { - 'loc': ['header', 'eoa-password'], - 'msg': 'eoa-password is not a Base64-encoded encrypted data', - 'type': 'value_error' + "loc": ["header", "eoa-password"], + "msg": "eoa-password is not a Base64-encoded encrypted data", + "type": "value_error", } - ] + ], } # Error_1_6 @@ -545,18 +491,15 @@ def test_error_1_6(self, client, db): json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'InvalidParameterError' - }, - 'detail': 'list length must be at least one' + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "list length must be at least one", } # Error_1_7_1 @@ -586,29 +529,21 @@ def test_error_1_7_1(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 10 - } - ] + req_param = [{"account_address": test_account_1, "amount": 10}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'AuthorizationError' - }, - 'detail': 'issuer does not exist, or password mismatch' + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # Error_1_7_2 @@ -638,29 +573,21 @@ def test_error_1_7_2(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 10 - } - ] + req_param = [{"account_address": test_account_1, "amount": 10}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'AuthorizationError' - }, - 'detail': 'issuer does not exist, or password mismatch' + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # Error_1_8_1 @@ -683,29 +610,21 @@ def test_error_1_8_1(self, client, db): db.add(account) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 10 - } - ] + req_param = [{"account_address": test_account_1, "amount": 10}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'NotFound' - }, - 'detail': 'token not found' + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # Error_1_8_2 @@ -737,27 +656,19 @@ def test_error_1_8_2(self, client, db): db.add(token) # request target API - req_param = [ - { - "account_address": test_account_1, - "amount": 10 - } - ] + req_param = [{"account_address": test_account_1, "amount": 10}] resp = client.post( self.base_url.format(token_address), json=req_param, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - 'meta': { - 'code': 1, - 'title': 'InvalidParameterError' - }, - 'detail': 'this token is temporarily unavailable' + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } diff --git a/tests/test_app_routers_share_tokens_{token_address}_redeem_batch_{batch_id}_GET.py b/tests/test_app_routers_share_tokens_{token_address}_redeem_batch_{batch_id}_GET.py index 819c855f..04ef3380 100644 --- a/tests/test_app_routers_share_tokens_{token_address}_redeem_batch_{batch_id}_GET.py +++ b/tests/test_app_routers_share_tokens_{token_address}_redeem_batch_{batch_id}_GET.py @@ -16,16 +16,15 @@ SPDX-License-Identifier: Apache-2.0 """ -from app.utils.e2ee_utils import E2EEUtils - from app.model.db import ( - TokenType, Account, - Token, - BatchIssueRedeemUpload, + BatchIssueRedeem, BatchIssueRedeemProcessingCategory, - BatchIssueRedeem + BatchIssueRedeemUpload, + Token, + TokenType, ) +from app.utils.e2ee_utils import E2EEUtils from tests.account_config import config_eth_account @@ -39,13 +38,8 @@ class TestAppRoutersShareTokensTokenAddressRedeemBatchBatchIdGET: ] account_list = [ - { - "address": config_eth_account("user1")["address"], - "amount": 1 - }, { - "address": config_eth_account("user2")["address"], - "amount": 2 - } + {"address": config_eth_account("user1")["address"], "amount": 1}, + {"address": config_eth_account("user2")["address"], "amount": 2}, ] ########################################################################### @@ -95,22 +89,20 @@ def test_normal_1(self, client, db): # request target API resp = client.get( self.base_url.format(test_token_address, self.upload_id_list[0]), - headers={ - "issuer-address": issuer_address - } + headers={"issuer-address": issuer_address}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'processed': True, - 'results': [ + "processed": True, + "results": [ { - 'account_address': self.account_list[0]["address"], - 'amount': self.account_list[0]["amount"], - 'status': 1 + "account_address": self.account_list[0]["address"], + "amount": self.account_list[0]["amount"], + "status": 1, } - ] + ], } # Normal_2 @@ -163,27 +155,25 @@ def test_normal_2(self, client, db): # request target API resp = client.get( self.base_url.format(test_token_address, self.upload_id_list[0]), - headers={ - "issuer-address": issuer_address - } + headers={"issuer-address": issuer_address}, ) # assertion assert resp.status_code == 200 assert resp.json() == { - 'processed': True, - 'results': [ + "processed": True, + "results": [ { - 'account_address': self.account_list[0]["address"], - 'amount': self.account_list[0]["amount"], - 'status': 1 + "account_address": self.account_list[0]["address"], + "amount": self.account_list[0]["amount"], + "status": 1, }, { - 'account_address': self.account_list[1]["address"], - 'amount': self.account_list[1]["amount"], - 'status': 1 - } - ] + "account_address": self.account_list[1]["address"], + "amount": self.account_list[1]["amount"], + "status": 1, + }, + ], } ######################################################################### @@ -226,17 +216,12 @@ def test_error_1(self, client, db): # request target API resp = client.get( self.base_url.format(test_token_address, self.upload_id_list[0]), - headers={ - "issuer-address": issuer_address - } + headers={"issuer-address": issuer_address}, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "batch not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "batch not found", } diff --git a/tests/test_app_routers_share_tokens_{token_address}_scheduled_events_GET.py b/tests/test_app_routers_share_tokens_{token_address}_scheduled_events_GET.py index eee27e73..879b456c 100644 --- a/tests/test_app_routers_share_tokens_{token_address}_scheduled_events_GET.py +++ b/tests/test_app_routers_share_tokens_{token_address}_scheduled_events_GET.py @@ -17,19 +17,12 @@ SPDX-License-Identifier: Apache-2.0 """ import uuid -from datetime import ( - datetime, - timedelta -) +from datetime import datetime, timedelta from pytz import timezone +from app.model.db import ScheduledEvents, ScheduledEventType, TokenType from config import TZ -from app.model.db import ( - TokenType, - ScheduledEvents, - ScheduledEventType -) from tests.account_config import config_eth_account @@ -52,7 +45,12 @@ def test_normal_1(self, client, db): # prepare data datetime_now_utc = datetime.utcnow() - datetime_now_str = timezone("UTC").localize(datetime_now_utc).astimezone(self.local_tz).isoformat() + datetime_now_str = ( + timezone("UTC") + .localize(datetime_now_utc) + .astimezone(self.local_tz) + .isoformat() + ) update_data = { "cancellation_date": "20221231", "dividends": 345.67, @@ -66,7 +64,7 @@ def test_normal_1(self, client, db): "contact_information": "問い合わせ先test", "privacy_policy": "プライバシーポリシーtest", "is_canceled": False, - "memo": "memo_test1" + "memo": "memo_test1", } event_id = str(uuid.uuid4()) @@ -87,7 +85,7 @@ def test_normal_1(self, client, db): self.base_url.format(_token_address), headers={ "issuer-address": _issuer_address, - } + }, ) # assertion @@ -101,7 +99,7 @@ def test_normal_1(self, client, db): "event_type": ScheduledEventType.UPDATE.value, "status": 0, "data": update_data, - "created": datetime_now_str + "created": datetime_now_str, } ] @@ -136,7 +134,7 @@ def test_normal_2(self, client, db): "contact_information": "問い合わせ先test", "privacy_policy": "プライバシーポリシーtest", "is_canceled": False, - "memo": "memo_test1" + "memo": "memo_test1", } for i, _datetime in enumerate(datetime_list): @@ -164,21 +162,34 @@ def test_normal_2(self, client, db): "scheduled_event_id": uuid_list[0], "token_address": _token_address, "token_type": TokenType.IBET_SHARE.value, - "scheduled_datetime": timezone("UTC").localize(datetime_list[0]).astimezone(self.local_tz).isoformat(), + "scheduled_datetime": timezone("UTC") + .localize(datetime_list[0]) + .astimezone(self.local_tz) + .isoformat(), "event_type": ScheduledEventType.UPDATE.value, "status": 0, "data": update_data, - "created": timezone("UTC").localize(datetime_list[0]).astimezone(self.local_tz).isoformat(), - }, { + "created": timezone("UTC") + .localize(datetime_list[0]) + .astimezone(self.local_tz) + .isoformat(), + }, + { "scheduled_event_id": uuid_list[1], "token_address": _token_address, "token_type": TokenType.IBET_SHARE.value, - "scheduled_datetime": timezone("UTC").localize(datetime_list[1]).astimezone(self.local_tz).isoformat(), + "scheduled_datetime": timezone("UTC") + .localize(datetime_list[1]) + .astimezone(self.local_tz) + .isoformat(), "event_type": ScheduledEventType.UPDATE.value, "status": 0, "data": update_data, - "created": timezone("UTC").localize(datetime_list[1]).astimezone(self.local_tz).isoformat(), - } + "created": timezone("UTC") + .localize(datetime_list[1]) + .astimezone(self.local_tz) + .isoformat(), + }, ] # @@ -193,7 +204,7 @@ def test_normal_3(self, client, db): self.base_url.format(_token_address), headers={ "issuer-address": _issuer_address, - } + }, ) # assertion diff --git a/tests/test_app_routers_share_tokens_{token_address}_scheduled_events_POST.py b/tests/test_app_routers_share_tokens_{token_address}_scheduled_events_POST.py index f98f35c4..f7aa9411 100644 --- a/tests/test_app_routers_share_tokens_{token_address}_scheduled_events_POST.py +++ b/tests/test_app_routers_share_tokens_{token_address}_scheduled_events_POST.py @@ -16,20 +16,11 @@ SPDX-License-Identifier: Apache-2.0 """ -from datetime import ( - datetime, - timezone -) +from datetime import datetime, timezone from pytz import timezone as tz -from app.model.db import ( - Account, - Token, - TokenType, - ScheduledEvents, - ScheduledEventType -) +from app.model.db import Account, ScheduledEvents, ScheduledEventType, Token, TokenType from app.utils.e2ee_utils import E2EEUtils from tests.account_config import config_eth_account @@ -83,33 +74,37 @@ def test_normal_1(self, client, db): "transfer_approval_required": False, "principal_value": 900, "is_canceled": False, - "memo": "memo_test1" + "memo": "memo_test1", } # request target API req_param = { "scheduled_datetime": datetime_now_str, "event_type": "Update", - "data": update_data + "data": update_data, } resp_1 = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion - _scheduled_event = db.query(ScheduledEvents). \ - filter(ScheduledEvents.issuer_address == _issuer_address). \ - filter(ScheduledEvents.token_address == _token_address). \ - first() + _scheduled_event = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.issuer_address == _issuer_address) + .filter(ScheduledEvents.token_address == _token_address) + .first() + ) assert resp_1.status_code == 200 assert resp_1.json() == {"scheduled_event_id": _scheduled_event.event_id} assert _scheduled_event.token_type == TokenType.IBET_SHARE.value - assert _scheduled_event.scheduled_datetime == datetime_now_utc.replace(tzinfo=None) + assert _scheduled_event.scheduled_datetime == datetime_now_utc.replace( + tzinfo=None + ) assert _scheduled_event.event_type == ScheduledEventType.UPDATE.value assert _scheduled_event.status == 0 assert _scheduled_event.data == update_data @@ -155,33 +150,37 @@ def test_normal_2(self, client, db): "transfer_approval_required": True, "principal_value": 900, "is_canceled": False, - "memo": "memo_test1" + "memo": "memo_test1", } # request target API req_param = { "scheduled_datetime": datetime_now_str, "event_type": "Update", - "data": update_data + "data": update_data, } resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion - _scheduled_event = db.query(ScheduledEvents). \ - filter(ScheduledEvents.issuer_address == _issuer_address). \ - filter(ScheduledEvents.token_address == _token_address). \ - first() + _scheduled_event = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.issuer_address == _issuer_address) + .filter(ScheduledEvents.token_address == _token_address) + .first() + ) assert resp.status_code == 200 assert resp.json() == {"scheduled_event_id": _scheduled_event.event_id} assert _scheduled_event.token_type == TokenType.IBET_SHARE.value - assert _scheduled_event.scheduled_datetime == datetime_now_jst.astimezone(timezone.utc).replace(tzinfo=None) + assert _scheduled_event.scheduled_datetime == datetime_now_jst.astimezone( + timezone.utc + ).replace(tzinfo=None) assert _scheduled_event.event_type == ScheduledEventType.UPDATE.value assert _scheduled_event.status == 0 assert _scheduled_event.data == update_data @@ -207,15 +206,15 @@ def test_error_1(self, client, db): req_param = { "scheduled_datetime": datetime_now_str, "event_type": "Update", - "data": update_data + "data": update_data, } resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address[:-1], # too short - "eoa-password": "password" # not encrypted - } + "eoa-password": "password", # not encrypted + }, ) # assertion @@ -225,12 +224,13 @@ def test_error_1(self, client, db): { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" - }, { + "type": "value_error", + }, + { "loc": ["header", "eoa-password"], "msg": "eoa-password is not a Base64-encoded encrypted data", - "type": "value_error" - } + "type": "value_error", + }, ] # @@ -250,15 +250,15 @@ def test_error_2(self, client, db): req_param = { "scheduled_datetime": datetime_now_str, "event_type": "Update", - "data": update_data + "data": update_data, } resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion @@ -299,15 +299,15 @@ def test_error_3(self, client, db): req_param = { "scheduled_datetime": datetime_now_str, "event_type": "Update", - "data": update_data + "data": update_data, } resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("mismatch-password") - } + "eoa-password": E2EEUtils.encrypt("mismatch-password"), + }, ) # assertion @@ -340,22 +340,22 @@ def test_error_4(self, client, db): req_param = { "scheduled_datetime": datetime_now_str, "event_type": "Update", - "data": update_data + "data": update_data, } resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 404 assert resp.json()["meta"] == {"code": 1, "title": "NotFound"} assert resp.json()["detail"] == "token not found" - + # # RequestValidationError # event_data @@ -363,22 +363,22 @@ def test_error_5(self, client, db): test_account = config_eth_account("user1") _issuer_address = test_account["address"] _token_address = "token_address_test" - + # request target API req_param = { "scheduled_datetime": "this is not time format", "event_type": "aUpdateb", "data": { "dividends": "must be integer, but string", - } + }, } resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion @@ -388,17 +388,19 @@ def test_error_5(self, client, db): { "loc": ["body", "scheduled_datetime"], "msg": "invalid datetime format", - "type": "value_error.datetime" - }, { + "type": "value_error.datetime", + }, + { "ctx": {"enum_values": ["Update"]}, "loc": ["body", "event_type"], "msg": "value is not a valid enumeration member; permitted: 'Update'", - "type": "type_error.enum" - }, { + "type": "type_error.enum", + }, + { "loc": ["body", "data", "dividends"], "msg": "value is not a valid float", - "type": "type_error.float" - } + "type": "type_error.float", + }, ] # @@ -435,23 +437,20 @@ def test_error_6(self, client, db): req_param = { "scheduled_datetime": datetime_now_str, "event_type": "Update", - "data": update_data + "data": update_data, } resp = client.post( self.base_url.format(_token_address), json=req_param, headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } diff --git a/tests/test_app_routers_share_tokens_{token_address}_scheduled_events_{scheduled_event_id}_DELETE.py b/tests/test_app_routers_share_tokens_{token_address}_scheduled_events_{scheduled_event_id}_DELETE.py index 3b2f3d4d..0f1b4e43 100644 --- a/tests/test_app_routers_share_tokens_{token_address}_scheduled_events_{scheduled_event_id}_DELETE.py +++ b/tests/test_app_routers_share_tokens_{token_address}_scheduled_events_{scheduled_event_id}_DELETE.py @@ -18,16 +18,12 @@ """ import uuid from datetime import datetime + from pytz import timezone -from config import TZ -from app.model.db import ( - Account, - TokenType, - ScheduledEvents, - ScheduledEventType -) +from app.model.db import Account, ScheduledEvents, ScheduledEventType, TokenType from app.utils.e2ee_utils import E2EEUtils +from config import TZ from tests.account_config import config_eth_account @@ -55,7 +51,12 @@ def test_normal_1(self, client, db): db.add(account) datetime_now_utc = datetime.utcnow() - datetime_now_str = timezone("UTC").localize(datetime_now_utc).astimezone(self.local_tz).isoformat() + datetime_now_str = ( + timezone("UTC") + .localize(datetime_now_utc) + .astimezone(self.local_tz) + .isoformat() + ) data = { "cancellation_date": "20221231", "dividends": 345.67, @@ -69,7 +70,7 @@ def test_normal_1(self, client, db): "contact_information": "問い合わせ先test", "privacy_policy": "プライバシーポリシーtest", "is_canceled": False, - "memo": "memo_test1" + "memo": "memo_test1", } event_id = str(uuid.uuid4()) @@ -90,8 +91,8 @@ def test_normal_1(self, client, db): self.base_url.format(_token_address, event_id), headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion @@ -104,9 +105,13 @@ def test_normal_1(self, client, db): "event_type": ScheduledEventType.UPDATE.value, "status": 0, "data": data, - "created": datetime_now_str + "created": datetime_now_str, } - token_event = db.query(ScheduledEvents).filter(ScheduledEvents.event_id == event_id).first() + token_event = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.event_id == event_id) + .first() + ) assert token_event is None ######################################################################### @@ -126,8 +131,8 @@ def test_error_1(self, client, db): self.base_url.format(_token_address, "test_event_id"), headers={ "issuer-address": _issuer_address[:-1], # too short - "eoa-password": "password" # not encrypted - } + "eoa-password": "password", # not encrypted + }, ) # assertion @@ -137,12 +142,13 @@ def test_error_1(self, client, db): { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" - }, { + "type": "value_error", + }, + { "loc": ["header", "eoa-password"], "msg": "eoa-password is not a Base64-encoded encrypted data", - "type": "value_error" - } + "type": "value_error", + }, ] # @@ -158,8 +164,8 @@ def test_error_2(self, client, db): self.base_url.format(_token_address, "test_event_id"), headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion @@ -188,8 +194,8 @@ def test_error_3(self, client, db): self.base_url.format(_token_address, "test_event_id"), headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("mismatch_password") - } + "eoa-password": E2EEUtils.encrypt("mismatch_password"), + }, ) # assertion @@ -218,8 +224,8 @@ def test_error_4(self, client, db): self.base_url.format(_token_address, "test_event_id"), headers={ "issuer-address": _issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion diff --git a/tests/test_app_routers_share_tokens_{token_address}_scheduled_events_{scheduled_event_id}_GET.py b/tests/test_app_routers_share_tokens_{token_address}_scheduled_events_{scheduled_event_id}_GET.py index 91e67a3f..d06303a9 100644 --- a/tests/test_app_routers_share_tokens_{token_address}_scheduled_events_{scheduled_event_id}_GET.py +++ b/tests/test_app_routers_share_tokens_{token_address}_scheduled_events_{scheduled_event_id}_GET.py @@ -18,14 +18,11 @@ """ import uuid from datetime import datetime + from pytz import timezone +from app.model.db import ScheduledEvents, ScheduledEventType, TokenType from config import TZ -from app.model.db import ( - TokenType, - ScheduledEvents, - ScheduledEventType -) from tests.account_config import config_eth_account @@ -48,7 +45,12 @@ def test_normal_1(self, client, db): # prepare data datetime_now_utc = datetime.utcnow() - datetime_now_str = timezone("UTC").localize(datetime_now_utc).astimezone(self.local_tz).isoformat() + datetime_now_str = ( + timezone("UTC") + .localize(datetime_now_utc) + .astimezone(self.local_tz) + .isoformat() + ) update_data = { "cancellation_date": "20221231", "dividends": 345.67, @@ -62,7 +64,7 @@ def test_normal_1(self, client, db): "contact_information": "問い合わせ先test", "privacy_policy": "プライバシーポリシーtest", "is_canceled": False, - "memo": "memo_test1" + "memo": "memo_test1", } event_id = str(uuid.uuid4()) @@ -83,7 +85,7 @@ def test_normal_1(self, client, db): self.base_url.format(_token_address, event_id), headers={ "issuer-address": _issuer_address, - } + }, ) # assertion @@ -109,7 +111,12 @@ def test_normal_2(self, client, db): # prepare data datetime_now_utc = datetime.utcnow() - datetime_now_str = timezone("UTC").localize(datetime_now_utc).astimezone(self.local_tz).isoformat() + datetime_now_str = ( + timezone("UTC") + .localize(datetime_now_utc) + .astimezone(self.local_tz) + .isoformat() + ) update_data = { "cancellation_date": "20221231", "dividends": 345.67, @@ -123,7 +130,7 @@ def test_normal_2(self, client, db): "contact_information": "問い合わせ先test", "privacy_policy": "プライバシーポリシーtest", "is_canceled": False, - "memo": "memo_test1" + "memo": "memo_test1", } event_id = str(uuid.uuid4()) @@ -154,7 +161,7 @@ def test_normal_2(self, client, db): "event_type": ScheduledEventType.UPDATE.value, "status": 0, "data": update_data, - "created": datetime_now_str + "created": datetime_now_str, } ######################################################################### @@ -173,14 +180,12 @@ def test_error_1(self, client, db): self.base_url.format(_token_address, "test_event_id"), headers={ "issuer-address": _issuer_address, - } + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, "title": "NotFound" - }, - "detail": "event not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "event not found", } diff --git a/tests/test_app_routers_share_transfer_approvals_GET.py b/tests/test_app_routers_share_transfer_approvals_GET.py index 9ed1b38e..cac1c383 100644 --- a/tests/test_app_routers_share_transfer_approvals_GET.py +++ b/tests/test_app_routers_share_transfer_approvals_GET.py @@ -22,11 +22,11 @@ import config from app.model.db import ( + IDXTransferApproval, Token, TokenType, - IDXTransferApproval, TransferApprovalHistory, - TransferApprovalOperationType + TransferApprovalOperationType, ) local_tz = timezone(config.TZ) @@ -48,13 +48,33 @@ class TestAppRoutersShareTransferApprovalsGET: test_from_address = "test_from_address" test_to_address = "test_to_address" test_application_datetime = datetime(year=2019, month=9, day=1) - test_application_datetime_str = timezone("UTC").localize(test_application_datetime).astimezone(local_tz).isoformat() + test_application_datetime_str = ( + timezone("UTC") + .localize(test_application_datetime) + .astimezone(local_tz) + .isoformat() + ) test_application_blocktimestamp = datetime(year=2019, month=9, day=2) - test_application_blocktimestamp_str = timezone("UTC").localize(test_application_blocktimestamp).astimezone(local_tz).isoformat() + test_application_blocktimestamp_str = ( + timezone("UTC") + .localize(test_application_blocktimestamp) + .astimezone(local_tz) + .isoformat() + ) test_approval_datetime = datetime(year=2019, month=9, day=3) - test_approval_datetime_str = timezone("UTC").localize(test_approval_datetime).astimezone(local_tz).isoformat() + test_approval_datetime_str = ( + timezone("UTC") + .localize(test_approval_datetime) + .astimezone(local_tz) + .isoformat() + ) test_approval_blocktimestamp = datetime(year=2019, month=9, day=4) - test_approval_blocktimestamp_str = timezone("UTC").localize(test_approval_blocktimestamp).astimezone(local_tz).isoformat() + test_approval_blocktimestamp_str = ( + timezone("UTC") + .localize(test_approval_blocktimestamp) + .astimezone(local_tz) + .isoformat() + ) ########################################################################### # Normal Case @@ -91,9 +111,13 @@ def test_normal_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 1 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = None _idx_transfer_approval.transfer_approved = None db.add(_idx_transfer_approval) @@ -107,9 +131,13 @@ def test_normal_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 1 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = None _idx_transfer_approval.transfer_approved = None db.add(_idx_transfer_approval) @@ -123,9 +151,13 @@ def test_normal_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 1 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = None _idx_transfer_approval.transfer_approved = None db.add(_idx_transfer_approval) @@ -138,13 +170,8 @@ def test_normal_1(self, client, db): # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 0, - "offset": None, - "limit": None, - "total": 0 - }, - "transfer_approvals": [] + "result_set": {"count": 0, "offset": None, "limit": None, "total": 0}, + "transfer_approvals": [], } assert resp.json() == assumed_response @@ -169,7 +196,9 @@ def test_normal_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 1 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -186,7 +215,9 @@ def test_normal_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 11 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -203,9 +234,13 @@ def test_normal_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 21 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = None _idx_transfer_approval.escrow_finished = True # escrow_finished _idx_transfer_approval.transfer_approved = None # event not synchronized @@ -215,7 +250,9 @@ def test_normal_2(self, client, db): _transfer_approval_history.token_address = self.test_token_address_1 _transfer_approval_history.exchange_address = config.ZERO_ADDRESS _transfer_approval_history.application_id = 21 - _transfer_approval_history.operation_type = TransferApprovalOperationType.APPROVE.value + _transfer_approval_history.operation_type = ( + TransferApprovalOperationType.APPROVE.value + ) db.add(_transfer_approval_history) # prepare data: IDXTransferApproval(Approve(transferred)) @@ -227,9 +264,13 @@ def test_normal_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 31 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = None _idx_transfer_approval.escrow_finished = True # escrow_finished _idx_transfer_approval.transfer_approved = True # transferred @@ -244,7 +285,9 @@ def test_normal_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 41 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None # event not synchronized @@ -256,7 +299,9 @@ def test_normal_2(self, client, db): _transfer_approval_history.token_address = self.test_token_address_1 _transfer_approval_history.exchange_address = config.ZERO_ADDRESS _transfer_approval_history.application_id = 41 - _transfer_approval_history.operation_type = TransferApprovalOperationType.CANCEL.value + _transfer_approval_history.operation_type = ( + TransferApprovalOperationType.CANCEL.value + ) db.add(_transfer_approval_history) # prepare data: IDXTransferApproval(Cancel(canceled)) @@ -268,7 +313,9 @@ def test_normal_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 51 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = True # cancelled @@ -286,12 +333,7 @@ def test_normal_2(self, client, db): # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 1, - "offset": None, - "limit": None, - "total": 1 - }, + "result_set": {"count": 1, "offset": None, "limit": None, "total": 1}, "transfer_approvals": [ { "issuer_address": self.test_issuer_address_1, @@ -302,7 +344,7 @@ def test_normal_2(self, client, db): "transferred_count": 2, "canceled_count": 2, }, - ] + ], } assert resp.json() == assumed_response @@ -346,7 +388,9 @@ def test_normal_3_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 1 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -362,7 +406,9 @@ def test_normal_3_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 11 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -378,7 +424,9 @@ def test_normal_3_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 12 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.escrow_finished = True # escrow_finished @@ -393,7 +441,9 @@ def test_normal_3_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 31 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = True # cancelled @@ -410,7 +460,9 @@ def test_normal_3_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 1 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -427,7 +479,9 @@ def test_normal_3_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 1 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -437,21 +491,13 @@ def test_normal_3_1(self, client, db): # request target API resp = client.get( - self.base_url, - headers={ - "issuer-address": self.test_issuer_address_1 - } + self.base_url, headers={"issuer-address": self.test_issuer_address_1} ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 2, - "offset": None, - "limit": None, - "total": 2 - }, + "result_set": {"count": 2, "offset": None, "limit": None, "total": 2}, "transfer_approvals": [ { "issuer_address": self.test_issuer_address_1, @@ -471,7 +517,7 @@ def test_normal_3_1(self, client, db): "transferred_count": 0, "canceled_count": 0, }, - ] + ], } assert resp.json() == assumed_response @@ -515,7 +561,9 @@ def test_normal_3_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 1 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -531,7 +579,9 @@ def test_normal_3_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 11 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -547,7 +597,9 @@ def test_normal_3_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 12 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.escrow_finished = True # escrow_finished @@ -562,7 +614,9 @@ def test_normal_3_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 31 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = True # cancelled @@ -579,7 +633,9 @@ def test_normal_3_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 1 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -596,7 +652,9 @@ def test_normal_3_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 1 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -612,12 +670,7 @@ def test_normal_3_2(self, client, db): # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 3, - "offset": None, - "limit": None, - "total": 3 - }, + "result_set": {"count": 3, "offset": None, "limit": None, "total": 3}, "transfer_approvals": [ { "issuer_address": self.test_issuer_address_1, @@ -646,7 +699,7 @@ def test_normal_3_2(self, client, db): "transferred_count": 0, "canceled_count": 0, }, - ] + ], } assert resp.json() == assumed_response @@ -698,7 +751,9 @@ def test_normal_4(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 1 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -715,7 +770,9 @@ def test_normal_4(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 1 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -732,7 +789,9 @@ def test_normal_4(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 1 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -749,7 +808,9 @@ def test_normal_4(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 1 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -763,18 +824,13 @@ def test_normal_4(self, client, db): params={ "limit": 2, "offset": 1, - } + }, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 4, - "offset": 1, - "limit": 2, - "total": 4 - }, + "result_set": {"count": 4, "offset": 1, "limit": 2, "total": 4}, "transfer_approvals": [ { "issuer_address": self.test_issuer_address_1, @@ -794,7 +850,7 @@ def test_normal_4(self, client, db): "transferred_count": 0, "canceled_count": 0, }, - ] + ], } assert resp.json() == assumed_response @@ -812,16 +868,13 @@ def test_error_1(self, client, db): params={ "offset": "c", "limit": "d", - } + }, ) # assertion assert resp.status_code == 422 assumed_response = { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["query", "offset"], @@ -833,6 +886,6 @@ def test_error_1(self, client, db): "msg": "value is not a valid integer", "type": "type_error.integer", }, - ] + ], } assert resp.json() == assumed_response diff --git a/tests/test_app_routers_share_transfer_approvals_{token_Address}_GET.py b/tests/test_app_routers_share_transfer_approvals_{token_Address}_GET.py index cf8a0578..c47bf026 100644 --- a/tests/test_app_routers_share_transfer_approvals_{token_Address}_GET.py +++ b/tests/test_app_routers_share_transfer_approvals_{token_Address}_GET.py @@ -22,18 +22,17 @@ import config from app.model.db import ( + IDXTransferApproval, Token, TokenType, - IDXTransferApproval, TransferApprovalHistory, - TransferApprovalOperationType + TransferApprovalOperationType, ) local_tz = timezone(config.TZ) class TestAppRoutersShareTransferApprovalsTokenAddressGET: - # target API endpoint base_url = "/share/transfer_approvals/{}" @@ -45,17 +44,47 @@ class TestAppRoutersShareTransferApprovalsTokenAddressGET: test_from_address = "test_from_address" test_to_address = "test_to_address" test_application_datetime = datetime(year=2019, month=9, day=1) - test_application_datetime_str = timezone("UTC").localize(test_application_datetime).astimezone(local_tz).isoformat() + test_application_datetime_str = ( + timezone("UTC") + .localize(test_application_datetime) + .astimezone(local_tz) + .isoformat() + ) test_application_datetime_2 = datetime(year=2019, month=10, day=1) - test_application_datetime_str_2 = timezone("UTC").localize(test_application_datetime_2).astimezone(local_tz).isoformat() + test_application_datetime_str_2 = ( + timezone("UTC") + .localize(test_application_datetime_2) + .astimezone(local_tz) + .isoformat() + ) test_application_blocktimestamp = datetime(year=2019, month=9, day=2) - test_application_blocktimestamp_str = timezone("UTC").localize(test_application_blocktimestamp).astimezone(local_tz).isoformat() + test_application_blocktimestamp_str = ( + timezone("UTC") + .localize(test_application_blocktimestamp) + .astimezone(local_tz) + .isoformat() + ) test_approval_datetime = datetime(year=2019, month=9, day=3) - test_approval_datetime_str = timezone("UTC").localize(test_approval_datetime).astimezone(local_tz).isoformat() + test_approval_datetime_str = ( + timezone("UTC") + .localize(test_approval_datetime) + .astimezone(local_tz) + .isoformat() + ) test_approval_datetime_2 = datetime(year=2019, month=10, day=3) - test_approval_datetime_str_2 = timezone("UTC").localize(test_approval_datetime_2).astimezone(local_tz).isoformat() + test_approval_datetime_str_2 = ( + timezone("UTC") + .localize(test_approval_datetime_2) + .astimezone(local_tz) + .isoformat() + ) test_approval_blocktimestamp = datetime(year=2019, month=9, day=4) - test_approval_blocktimestamp_str = timezone("UTC").localize(test_approval_blocktimestamp).astimezone(local_tz).isoformat() + test_approval_blocktimestamp_str = ( + timezone("UTC") + .localize(test_approval_blocktimestamp) + .astimezone(local_tz) + .isoformat() + ) ########################################################################### # Normal Case @@ -74,20 +103,13 @@ def test_normal_1_1(self, client, db): db.add(_token) # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 0, - "offset": None, - "limit": None, - "total": 0 - }, - "transfer_approval_history": [] + "result_set": {"count": 0, "offset": None, "limit": None, "total": 0}, + "transfer_approval_history": [], } assert resp.json() == assumed_response @@ -113,7 +135,9 @@ def test_normal_1_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = False @@ -121,19 +145,12 @@ def test_normal_1_2(self, client, db): db.add(_idx_transfer_approval) # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 3, - "offset": None, - "limit": None, - "total": 3 - }, + "result_set": {"count": 3, "offset": None, "limit": None, "total": 3}, "transfer_approval_history": [ { "id": 3, @@ -189,7 +206,7 @@ def test_normal_1_2(self, client, db): "status": 0, "issuer_cancelable": True, }, - ] + ], } assert resp.json() == assumed_response @@ -215,9 +232,13 @@ def test_normal_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = False _idx_transfer_approval.transfer_approved = False db.add(_idx_transfer_approval) @@ -230,12 +251,7 @@ def test_normal_2(self, client, db): # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 3, - "offset": 1, - "limit": 1, - "total": 3 - }, + "result_set": {"count": 3, "offset": 1, "limit": 1, "total": 3}, "transfer_approval_history": [ { "id": 2, @@ -255,7 +271,7 @@ def test_normal_2(self, client, db): "status": 0, "issuer_cancelable": True, } - ] + ], } assert resp.json() == assumed_response @@ -276,35 +292,36 @@ def test_normal_3(self, client, db): _idx_transfer_approval = IDXTransferApproval() _idx_transfer_approval.token_address = self.test_token_address if i == 1: - _idx_transfer_approval.exchange_address = self.test_exchange_address + "0" + _idx_transfer_approval.exchange_address = ( + self.test_exchange_address + "0" + ) else: - _idx_transfer_approval.exchange_address = self.test_exchange_address + "1" + _idx_transfer_approval.exchange_address = ( + self.test_exchange_address + "1" + ) _idx_transfer_approval.application_id = i _idx_transfer_approval.from_address = self.test_from_address _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = False _idx_transfer_approval.transfer_approved = False db.add(_idx_transfer_approval) # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 3, - "offset": None, - "limit": None, - "total": 3 - }, + "result_set": {"count": 3, "offset": None, "limit": None, "total": 3}, "transfer_approval_history": [ { "id": 3, @@ -360,7 +377,7 @@ def test_normal_3(self, client, db): "status": 0, "issuer_cancelable": False, }, - ] + ], } assert resp.json() == assumed_response @@ -387,9 +404,13 @@ def test_normal_4_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = False _idx_transfer_approval.transfer_approved = False db.add(_idx_transfer_approval) @@ -397,20 +418,13 @@ def test_normal_4_1(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "from_address": self.test_from_address + "1" - } + params={"from_address": self.test_from_address + "1"}, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 1, - "offset": None, - "limit": None, - "total": 3 - }, + "result_set": {"count": 1, "offset": None, "limit": None, "total": 3}, "transfer_approval_history": [ { "id": 2, @@ -430,7 +444,7 @@ def test_normal_4_1(self, client, db): "status": 0, "issuer_cancelable": True, } - ] + ], } assert resp.json() == assumed_response @@ -457,9 +471,13 @@ def test_normal_4_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address + str(i) _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = False _idx_transfer_approval.transfer_approved = False db.add(_idx_transfer_approval) @@ -467,20 +485,13 @@ def test_normal_4_2(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "to_address": self.test_to_address + "1" - } + params={"to_address": self.test_to_address + "1"}, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 1, - "offset": None, - "limit": None, - "total": 3 - }, + "result_set": {"count": 1, "offset": None, "limit": None, "total": 3}, "transfer_approval_history": [ { "id": 2, @@ -500,7 +511,7 @@ def test_normal_4_2(self, client, db): "status": 0, "issuer_cancelable": True, } - ] + ], } assert resp.json() == assumed_response @@ -527,7 +538,9 @@ def test_normal_4_3_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) if i == 0: # unapproved _idx_transfer_approval.exchange_address = config.ZERO_ADDRESS _idx_transfer_approval.cancelled = None @@ -557,21 +570,13 @@ def test_normal_4_3_1(self, client, db): # request target API resp = client.get( - self.base_url.format(self.test_token_address), - params={ - "status": 0 - } + self.base_url.format(self.test_token_address), params={"status": 0} ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 1, - "offset": None, - "limit": None, - "total": 5 - }, + "result_set": {"count": 1, "offset": None, "limit": None, "total": 5}, "transfer_approval_history": [ { "id": 1, @@ -591,7 +596,7 @@ def test_normal_4_3_1(self, client, db): "status": 0, "issuer_cancelable": True, }, - ] + ], } assert resp.json() == assumed_response @@ -618,7 +623,9 @@ def test_normal_4_3_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) if i == 0: # unapproved _idx_transfer_approval.exchange_address = config.ZERO_ADDRESS _idx_transfer_approval.cancelled = None @@ -648,21 +655,13 @@ def test_normal_4_3_2(self, client, db): # request target API resp = client.get( - self.base_url.format(self.test_token_address), - params={ - "status": 1 - } + self.base_url.format(self.test_token_address), params={"status": 1} ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 1, - "offset": None, - "limit": None, - "total": 5 - }, + "result_set": {"count": 1, "offset": None, "limit": None, "total": 5}, "transfer_approval_history": [ { "id": 2, @@ -682,7 +681,7 @@ def test_normal_4_3_2(self, client, db): "status": 1, "issuer_cancelable": True, } - ] + ], } assert resp.json() == assumed_response @@ -709,7 +708,9 @@ def test_normal_4_3_3(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) if i == 0: # unapproved _idx_transfer_approval.exchange_address = config.ZERO_ADDRESS _idx_transfer_approval.cancelled = None @@ -726,7 +727,9 @@ def test_normal_4_3_3(self, client, db): _idx_transfer_approval.escrow_finished = True _idx_transfer_approval.transfer_approved = True _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) elif i == 3: # transferred_2 _idx_transfer_approval.exchange_address = config.ZERO_ADDRESS _idx_transfer_approval.cancelled = None @@ -736,7 +739,9 @@ def test_normal_4_3_3(self, client, db): _transfer_approval_history.token_address = self.test_token_address _transfer_approval_history.exchange_address = config.ZERO_ADDRESS _transfer_approval_history.application_id = i - _transfer_approval_history.operation_type = TransferApprovalOperationType.APPROVE.value + _transfer_approval_history.operation_type = ( + TransferApprovalOperationType.APPROVE.value + ) db.add(_transfer_approval_history) elif i == 4: # transferred_3 _idx_transfer_approval.exchange_address = config.ZERO_ADDRESS @@ -744,7 +749,9 @@ def test_normal_4_3_3(self, client, db): _idx_transfer_approval.escrow_finished = None _idx_transfer_approval.transfer_approved = True _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) elif i == 5: # canceled-1 _idx_transfer_approval.exchange_address = config.ZERO_ADDRESS _idx_transfer_approval.cancelled = None @@ -754,7 +761,9 @@ def test_normal_4_3_3(self, client, db): _transfer_approval_history.token_address = self.test_token_address _transfer_approval_history.exchange_address = config.ZERO_ADDRESS _transfer_approval_history.application_id = i - _transfer_approval_history.operation_type = TransferApprovalOperationType.CANCEL.value + _transfer_approval_history.operation_type = ( + TransferApprovalOperationType.CANCEL.value + ) db.add(_transfer_approval_history) elif i == 6: # canceled-2 _idx_transfer_approval.exchange_address = config.ZERO_ADDRESS @@ -765,21 +774,13 @@ def test_normal_4_3_3(self, client, db): # request target API resp = client.get( - self.base_url.format(self.test_token_address), - params={ - "status": 2 - } + self.base_url.format(self.test_token_address), params={"status": 2} ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 3, - "offset": None, - "limit": None, - "total": 7 - }, + "result_set": {"count": 3, "offset": None, "limit": None, "total": 7}, "transfer_approval_history": [ { "id": 5, @@ -834,8 +835,8 @@ def test_normal_4_3_3(self, client, db): "transfer_approved": True, "status": 2, "issuer_cancelable": False, - } - ] + }, + ], } assert resp.json() == assumed_response @@ -862,7 +863,9 @@ def test_normal_4_3_4(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) if i == 0: # unapproved _idx_transfer_approval.exchange_address = config.ZERO_ADDRESS _idx_transfer_approval.cancelled = None @@ -892,7 +895,9 @@ def test_normal_4_3_4(self, client, db): _transfer_approval_history.token_address = self.test_token_address _transfer_approval_history.exchange_address = config.ZERO_ADDRESS _transfer_approval_history.application_id = i - _transfer_approval_history.operation_type = TransferApprovalOperationType.CANCEL.value + _transfer_approval_history.operation_type = ( + TransferApprovalOperationType.CANCEL.value + ) db.add(_transfer_approval_history) elif i == 5: # canceled-2 _idx_transfer_approval.exchange_address = config.ZERO_ADDRESS @@ -904,21 +909,13 @@ def test_normal_4_3_4(self, client, db): # request target API resp = client.get( - self.base_url.format(self.test_token_address), - params={ - "status": 3 - } + self.base_url.format(self.test_token_address), params={"status": 3} ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 2, - "offset": None, - "limit": None, - "total": 6 - }, + "result_set": {"count": 2, "offset": None, "limit": None, "total": 6}, "transfer_approval_history": [ { "id": 6, @@ -955,8 +952,8 @@ def test_normal_4_3_4(self, client, db): "transfer_approved": False, "status": 3, "issuer_cancelable": True, - } - ] + }, + ], } assert resp.json() == assumed_response @@ -983,7 +980,9 @@ def test_normal_4_3_5(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) if i == 0: # unapproved _idx_transfer_approval.exchange_address = config.ZERO_ADDRESS _idx_transfer_approval.cancelled = None @@ -1008,7 +1007,9 @@ def test_normal_4_3_5(self, client, db): _transfer_approval_history.token_address = self.test_token_address _transfer_approval_history.exchange_address = config.ZERO_ADDRESS _transfer_approval_history.application_id = i - _transfer_approval_history.operation_type = TransferApprovalOperationType.APPROVE.value + _transfer_approval_history.operation_type = ( + TransferApprovalOperationType.APPROVE.value + ) db.add(_transfer_approval_history) elif i == 4: # transferred_3 _idx_transfer_approval.exchange_address = config.ZERO_ADDRESS @@ -1024,7 +1025,9 @@ def test_normal_4_3_5(self, client, db): _transfer_approval_history.token_address = self.test_token_address _transfer_approval_history.exchange_address = config.ZERO_ADDRESS _transfer_approval_history.application_id = i - _transfer_approval_history.operation_type = TransferApprovalOperationType.CANCEL.value + _transfer_approval_history.operation_type = ( + TransferApprovalOperationType.CANCEL.value + ) db.add(_transfer_approval_history) elif i == 6: # canceled-2 _idx_transfer_approval.exchange_address = config.ZERO_ADDRESS @@ -1035,21 +1038,13 @@ def test_normal_4_3_5(self, client, db): # request target API resp = client.get( - self.base_url.format(self.test_token_address), - params={ - "status": [0, 1] - } + self.base_url.format(self.test_token_address), params={"status": [0, 1]} ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 2, - "offset": None, - "limit": None, - "total": 7 - }, + "result_set": {"count": 2, "offset": None, "limit": None, "total": 7}, "transfer_approval_history": [ { "id": 2, @@ -1087,7 +1082,7 @@ def test_normal_4_3_5(self, client, db): "status": 0, "issuer_cancelable": True, }, - ] + ], } assert resp.json() == assumed_response @@ -1114,9 +1109,13 @@ def test_normal_5_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = False _idx_transfer_approval.transfer_approved = False db.add(_idx_transfer_approval) @@ -1124,21 +1123,13 @@ def test_normal_5_1(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "sort_item": "id", - "sort_order": 0 - } + params={"sort_item": "id", "sort_order": 0}, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 3, - "offset": None, - "limit": None, - "total": 3 - }, + "result_set": {"count": 3, "offset": None, "limit": None, "total": 3}, "transfer_approval_history": [ { "id": 1, @@ -1194,7 +1185,7 @@ def test_normal_5_1(self, client, db): "status": 0, "issuer_cancelable": False, }, - ] + ], } assert resp.json() == assumed_response @@ -1222,9 +1213,13 @@ def test_normal_5_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = False _idx_transfer_approval.transfer_approved = False db.add(_idx_transfer_approval) @@ -1232,21 +1227,13 @@ def test_normal_5_2(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "sort_item": "exchange_address", - "sort_order": 1 - } + params={"sort_item": "exchange_address", "sort_order": 1}, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 4, - "offset": None, - "limit": None, - "total": 4 - }, + "result_set": {"count": 4, "offset": None, "limit": None, "total": 4}, "transfer_approval_history": [ { "id": 3, @@ -1320,7 +1307,7 @@ def test_normal_5_2(self, client, db): "status": 0, "issuer_cancelable": True, }, - ] + ], } assert resp.json() == assumed_response @@ -1348,9 +1335,13 @@ def test_normal_5_3(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = False _idx_transfer_approval.transfer_approved = False db.add(_idx_transfer_approval) @@ -1358,21 +1349,13 @@ def test_normal_5_3(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "sort_item": "application_id", - "sort_order": 0 - } + params={"sort_item": "application_id", "sort_order": 0}, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 4, - "offset": None, - "limit": None, - "total": 4 - }, + "result_set": {"count": 4, "offset": None, "limit": None, "total": 4}, "transfer_approval_history": [ { "id": 2, @@ -1446,7 +1429,7 @@ def test_normal_5_3(self, client, db): "status": 0, "issuer_cancelable": False, }, - ] + ], } assert resp.json() == assumed_response @@ -1469,13 +1452,19 @@ def test_normal_5_4(self, client, db): _idx_transfer_approval.token_address = self.test_token_address _idx_transfer_approval.exchange_address = self.test_exchange_address _idx_transfer_approval.application_id = i - _idx_transfer_approval.from_address = self.test_from_address + str(int((3 - i) / 2)) + _idx_transfer_approval.from_address = self.test_from_address + str( + int((3 - i) / 2) + ) _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = False _idx_transfer_approval.transfer_approved = False db.add(_idx_transfer_approval) @@ -1483,21 +1472,13 @@ def test_normal_5_4(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "sort_item": "from_address", - "sort_order": 1 - } + params={"sort_item": "from_address", "sort_order": 1}, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 4, - "offset": None, - "limit": None, - "total": 4 - }, + "result_set": {"count": 4, "offset": None, "limit": None, "total": 4}, "transfer_approval_history": [ { "id": 2, @@ -1571,7 +1552,7 @@ def test_normal_5_4(self, client, db): "status": 0, "issuer_cancelable": False, }, - ] + ], } assert resp.json() == assumed_response @@ -1598,9 +1579,13 @@ def test_normal_5_5(self, client, db): _idx_transfer_approval.to_address = self.test_to_address + str(int(i / 2)) _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = False _idx_transfer_approval.transfer_approved = False db.add(_idx_transfer_approval) @@ -1608,21 +1593,13 @@ def test_normal_5_5(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "sort_item": "to_address", - "sort_order": 0 - } + params={"sort_item": "to_address", "sort_order": 0}, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 4, - "offset": None, - "limit": None, - "total": 4 - }, + "result_set": {"count": 4, "offset": None, "limit": None, "total": 4}, "transfer_approval_history": [ { "id": 2, @@ -1696,7 +1673,7 @@ def test_normal_5_5(self, client, db): "status": 0, "issuer_cancelable": False, }, - ] + ], } assert resp.json() == assumed_response @@ -1723,9 +1700,13 @@ def test_normal_5_6(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = int((3 - i) / 2) _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = False _idx_transfer_approval.transfer_approved = False db.add(_idx_transfer_approval) @@ -1733,21 +1714,13 @@ def test_normal_5_6(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "sort_item": "amount", - "sort_order": 1 - } + params={"sort_item": "amount", "sort_order": 1}, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 4, - "offset": None, - "limit": None, - "total": 4 - }, + "result_set": {"count": 4, "offset": None, "limit": None, "total": 4}, "transfer_approval_history": [ { "id": 2, @@ -1821,7 +1794,7 @@ def test_normal_5_6(self, client, db): "status": 0, "issuer_cancelable": False, }, - ] + ], } assert resp.json() == assumed_response @@ -1848,12 +1821,20 @@ def test_normal_5_7(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i if i % 2 == 0: - _idx_transfer_approval.application_datetime = self.test_application_datetime + _idx_transfer_approval.application_datetime = ( + self.test_application_datetime + ) else: - _idx_transfer_approval.application_datetime = self.test_application_datetime_2 - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_datetime = ( + self.test_application_datetime_2 + ) + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = False _idx_transfer_approval.transfer_approved = False db.add(_idx_transfer_approval) @@ -1861,21 +1842,13 @@ def test_normal_5_7(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "sort_item": "application_datetime", - "sort_order": 0 - } + params={"sort_item": "application_datetime", "sort_order": 0}, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 4, - "offset": None, - "limit": None, - "total": 4 - }, + "result_set": {"count": 4, "offset": None, "limit": None, "total": 4}, "transfer_approval_history": [ { "id": 3, @@ -1949,7 +1922,7 @@ def test_normal_5_7(self, client, db): "status": 0, "issuer_cancelable": False, }, - ] + ], } assert resp.json() == assumed_response @@ -1976,12 +1949,16 @@ def test_normal_5_8(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) if i % 2 == 0: _idx_transfer_approval.approval_datetime = self.test_approval_datetime else: _idx_transfer_approval.approval_datetime = self.test_approval_datetime_2 - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = False _idx_transfer_approval.transfer_approved = False db.add(_idx_transfer_approval) @@ -1989,21 +1966,13 @@ def test_normal_5_8(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "sort_item": "approval_datetime", - "sort_order": 1 - } + params={"sort_item": "approval_datetime", "sort_order": 1}, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 4, - "offset": None, - "limit": None, - "total": 4 - }, + "result_set": {"count": 4, "offset": None, "limit": None, "total": 4}, "transfer_approval_history": [ { "id": 4, @@ -2077,7 +2046,7 @@ def test_normal_5_8(self, client, db): "status": 0, "issuer_cancelable": False, }, - ] + ], } assert resp.json() == assumed_response @@ -2103,7 +2072,9 @@ def test_normal_5_9(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = i _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) if i == 0 or i == 1: # unapproved _idx_transfer_approval.approval_datetime = None @@ -2126,7 +2097,9 @@ def test_normal_5_9(self, client, db): _idx_transfer_approval.escrow_finished = None _idx_transfer_approval.transfer_approved = True _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) else: # canceled _idx_transfer_approval.approval_datetime = None @@ -2139,21 +2112,13 @@ def test_normal_5_9(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "sort_item": "status", - "sort_order": 0 - } + params={"sort_item": "status", "sort_order": 0}, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 8, - "offset": None, - "limit": None, - "total": 8 - }, + "result_set": {"count": 8, "offset": None, "limit": None, "total": 8}, "transfer_approval_history": [ { "id": 2, @@ -2299,7 +2264,7 @@ def test_normal_5_9(self, client, db): "status": 3, "issuer_cancelable": True, }, - ] + ], } assert resp.json() == assumed_response @@ -2318,16 +2283,13 @@ def test_error_1_1(self, client, db): "status": "a", "offset": "c", "limit": "d", - } + }, ) # assertion assert resp.status_code == 422 assumed_response = { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["query", "status", 0], @@ -2344,7 +2306,7 @@ def test_error_1_1(self, client, db): "msg": "value is not a valid integer", "type": "type_error.integer", }, - ] + ], } assert resp.json() == assumed_response @@ -2357,16 +2319,13 @@ def test_error_1_2(self, client, db): self.base_url.format(self.test_token_address), params={ "status": -1, - } + }, ) # assertion assert resp.status_code == 422 assumed_response = { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["query", "status", 0], @@ -2374,7 +2333,7 @@ def test_error_1_2(self, client, db): "msg": "ensure this value is greater than or equal to 0", "type": "value_error.number.not_ge", }, - ] + ], } assert resp.json() == assumed_response @@ -2387,16 +2346,13 @@ def test_error_1_3(self, client, db): self.base_url.format(self.test_token_address), params={ "status": 4, - } + }, ) # assertion assert resp.status_code == 422 assumed_response = { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["query", "status", 0], @@ -2404,7 +2360,7 @@ def test_error_1_3(self, client, db): "msg": "ensure this value is less than or equal to 3", "type": "value_error.number.not_le", }, - ] + ], } assert resp.json() == assumed_response @@ -2412,18 +2368,13 @@ def test_error_1_3(self, client, db): # token not found def test_error_1(self, client, db): # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 404 assumed_response = { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } assert resp.json() == assumed_response @@ -2441,16 +2392,11 @@ def test_error_2(self, client, db): db.add(_token) # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } diff --git a/tests/test_app_routers_share_transfer_approvals_{token_Address}_{id}_GET.py b/tests/test_app_routers_share_transfer_approvals_{token_Address}_{id}_GET.py index f04c6785..d6e2ebd4 100644 --- a/tests/test_app_routers_share_transfer_approvals_{token_Address}_{id}_GET.py +++ b/tests/test_app_routers_share_transfer_approvals_{token_Address}_{id}_GET.py @@ -22,11 +22,11 @@ import config from app.model.db import ( + IDXTransferApproval, Token, TokenType, - IDXTransferApproval, TransferApprovalHistory, - TransferApprovalOperationType + TransferApprovalOperationType, ) local_tz = timezone(config.TZ) @@ -44,13 +44,33 @@ class TestAppRoutersShareTransferApprovalsTokenAddressIdGET: test_from_address = "test_from_address" test_to_address = "test_to_address" test_application_datetime = datetime(year=2019, month=9, day=1) - test_application_datetime_str = timezone("UTC").localize(test_application_datetime).astimezone(local_tz).isoformat() + test_application_datetime_str = ( + timezone("UTC") + .localize(test_application_datetime) + .astimezone(local_tz) + .isoformat() + ) test_application_blocktimestamp = datetime(year=2019, month=9, day=2) - test_application_blocktimestamp_str = timezone("UTC").localize(test_application_blocktimestamp).astimezone(local_tz).isoformat() + test_application_blocktimestamp_str = ( + timezone("UTC") + .localize(test_application_blocktimestamp) + .astimezone(local_tz) + .isoformat() + ) test_approval_datetime = datetime(year=2019, month=9, day=3) - test_approval_datetime_str = timezone("UTC").localize(test_approval_datetime).astimezone(local_tz).isoformat() + test_approval_datetime_str = ( + timezone("UTC") + .localize(test_approval_datetime) + .astimezone(local_tz) + .isoformat() + ) test_approval_blocktimestamp = datetime(year=2019, month=9, day=4) - test_approval_blocktimestamp_str = timezone("UTC").localize(test_approval_blocktimestamp).astimezone(local_tz).isoformat() + test_approval_blocktimestamp_str = ( + timezone("UTC") + .localize(test_approval_blocktimestamp) + .astimezone(local_tz) + .isoformat() + ) ########################################################################### # Normal Case @@ -78,7 +98,9 @@ def test_normal_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -87,9 +109,7 @@ def test_normal_1(self, client, db): db.add(_idx_transfer_approval) # request target API - resp = client.get( - self.base_url.format(self.test_token_address, id) - ) + resp = client.get(self.base_url.format(self.test_token_address, id)) # assertion assert resp.status_code == 200 @@ -135,7 +155,9 @@ def test_normal_2_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -151,9 +173,7 @@ def test_normal_2_1(self, client, db): db.add(_cancel_op) # request target API - resp = client.get( - self.base_url.format(self.test_token_address, id) - ) + resp = client.get(self.base_url.format(self.test_token_address, id)) # assertion assert resp.status_code == 200 @@ -198,7 +218,9 @@ def test_normal_2_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = True @@ -207,9 +229,7 @@ def test_normal_2_2(self, client, db): db.add(_idx_transfer_approval) # request target API - resp = client.get( - self.base_url.format(self.test_token_address, id) - ) + resp = client.get(self.base_url.format(self.test_token_address, id)) # assertion assert resp.status_code == 200 @@ -254,7 +274,9 @@ def test_normal_3(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -263,9 +285,7 @@ def test_normal_3(self, client, db): db.add(_idx_transfer_approval) # request target API - resp = client.get( - self.base_url.format(self.test_token_address, id) - ) + resp = client.get(self.base_url.format(self.test_token_address, id)) # assertion assert resp.status_code == 200 @@ -311,9 +331,13 @@ def test_normal_4_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = None _idx_transfer_approval.escrow_finished = True _idx_transfer_approval.transfer_approved = None @@ -327,9 +351,7 @@ def test_normal_4_1(self, client, db): db.add(_approval_op) # request target API - resp = client.get( - self.base_url.format(self.test_token_address, id) - ) + resp = client.get(self.base_url.format(self.test_token_address, id)) # assertion assert resp.status_code == 200 @@ -374,18 +396,20 @@ def test_normal_4_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = None _idx_transfer_approval.escrow_finished = True _idx_transfer_approval.transfer_approved = True db.add(_idx_transfer_approval) # request target API - resp = client.get( - self.base_url.format(self.test_token_address, id) - ) + resp = client.get(self.base_url.format(self.test_token_address, id)) # assertion assert resp.status_code == 200 @@ -418,18 +442,13 @@ def test_error_1(self, client, db): id = 10 # request target API - resp = client.get( - self.base_url.format(self.test_token_address, id) - ) + resp = client.get(self.base_url.format(self.test_token_address, id)) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # @@ -448,18 +467,13 @@ def test_error_2(self, client, db): db.add(_token) # request target API - resp = client.get( - self.base_url.format(self.test_token_address, id) - ) + resp = client.get(self.base_url.format(self.test_token_address, id)) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } # @@ -478,16 +492,11 @@ def test_error_3(self, client, db): db.add(_token) # request target API - resp = client.get( - self.base_url.format(self.test_token_address, id) - ) + resp = client.get(self.base_url.format(self.test_token_address, id)) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "transfer approval not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "transfer approval not found", } diff --git a/tests/test_app_routers_share_transfer_approvals_{token_Address}_{id}_POST.py b/tests/test_app_routers_share_transfer_approvals_{token_Address}_{id}_POST.py index b6f7c4e2..0f2bd659 100644 --- a/tests/test_app_routers_share_transfer_approvals_{token_Address}_{id}_POST.py +++ b/tests/test_app_routers_share_transfer_approvals_{token_Address}_{id}_POST.py @@ -17,36 +17,29 @@ SPDX-License-Identifier: Apache-2.0 """ import hashlib - -import pytest -from unittest import mock -from unittest.mock import ( - ANY, - MagicMock -) from datetime import datetime +from unittest import mock +from unittest.mock import ANY, MagicMock +import pytest from pytz import timezone import config +from app.exceptions import ContractRevertError, SendTransactionError +from app.model.blockchain.tx_params.ibet_security_token_escrow import ( + ApproveTransferParams as EscrowApproveTransferParams, +) +from app.model.blockchain.tx_params.ibet_straight_bond import ApproveTransferParams from app.model.db import ( Account, AuthToken, + IDXTransferApproval, Token, TokenType, - IDXTransferApproval, TransferApprovalHistory, - TransferApprovalOperationType -) -from app.model.blockchain.tx_params.ibet_straight_bond import ( - ApproveTransferParams, -) -from app.model.blockchain.tx_params.ibet_security_token_escrow import ( - ApproveTransferParams as EscrowApproveTransferParams, + TransferApprovalOperationType, ) from app.utils.e2ee_utils import E2EEUtils -from app.exceptions import SendTransactionError, ContractRevertError - from tests.account_config import config_eth_account local_tz = timezone(config.TZ) @@ -63,10 +56,19 @@ class TestAppRoutersShareTransferApprovalsTokenAddressIdPOST: test_from_address = "test_from_address" test_to_address = "test_to_address" test_application_datetime = datetime(year=2019, month=9, day=1) - test_application_datetime_str = timezone("UTC").localize(test_application_datetime).astimezone(local_tz).isoformat() + test_application_datetime_str = ( + timezone("UTC") + .localize(test_application_datetime) + .astimezone(local_tz) + .isoformat() + ) test_application_blocktimestamp = datetime(year=2019, month=9, day=2) - test_application_blocktimestamp_str = timezone("UTC").localize(test_application_blocktimestamp).astimezone( - local_tz).isoformat() + test_application_blocktimestamp_str = ( + timezone("UTC") + .localize(test_application_blocktimestamp) + .astimezone(local_tz) + .isoformat() + ) test_approval_datetime = datetime(year=2019, month=9, day=3) test_approval_blocktimestamp = datetime(year=2019, month=9, day=4) @@ -77,7 +79,7 @@ class TestAppRoutersShareTransferApprovalsTokenAddressIdPOST: # # APPROVE # token - @pytest.mark.freeze_time('2021-04-27 12:34:56') + @pytest.mark.freeze_time("2021-04-27 12:34:56") def test_normal_1_1(self, client, db): issuer = config_eth_account("user1") issuer_address = issuer["address"] @@ -107,7 +109,9 @@ def test_normal_1_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -116,38 +120,35 @@ def test_normal_1_1(self, client, db): # mock IbetSecurityTokenContract_approve_transfer = mock.patch( target="app.model.blockchain.token.IbetSecurityTokenInterface.approve_transfer", - return_value=("test_tx_hash", {"status": 1}) + return_value=("test_tx_hash", {"status": 1}), ) # request target API with IbetSecurityTokenContract_approve_transfer as mock_transfer: resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "approve" - }, + json={"operation_type": "approve"}, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # Assertion assert resp.status_code == 200 assert resp.json() is None - _expected = { - "application_id": 100, - "data": str(datetime.utcnow().timestamp()) - } + _expected = {"application_id": 100, "data": str(datetime.utcnow().timestamp())} mock_transfer.assert_called_once_with( data=ApproveTransferParams(**_expected), tx_from=issuer_address, - private_key=ANY + private_key=ANY, ) - approval_op_list: list[TransferApprovalHistory] = db.query(TransferApprovalHistory).all() + approval_op_list: list[TransferApprovalHistory] = db.query( + TransferApprovalHistory + ).all() assert len(approval_op_list) == 1 approval_op = approval_op_list[0] assert approval_op.token_address == self.test_token_address @@ -158,7 +159,7 @@ def test_normal_1_1(self, client, db): # # APPROVE # exchange - @pytest.mark.freeze_time('2021-04-27 12:34:56') + @pytest.mark.freeze_time("2021-04-27 12:34:56") def test_normal_1_2(self, client, db): issuer = config_eth_account("user1") issuer_address = issuer["address"] @@ -188,7 +189,9 @@ def test_normal_1_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -198,38 +201,35 @@ def test_normal_1_2(self, client, db): # mock IbetSecurityTokenEscrow_approve_transfer = mock.patch( target="app.model.blockchain.exchange.IbetSecurityTokenEscrow.approve_transfer", - return_value=("test_tx_hash", {"status": 1}) + return_value=("test_tx_hash", {"status": 1}), ) # request target API with IbetSecurityTokenEscrow_approve_transfer as mock_transfer: resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "approve" - }, + json={"operation_type": "approve"}, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # Assertion assert resp.status_code == 200 assert resp.json() is None - _expected = { - "escrow_id": 100, - "data": str(datetime.utcnow().timestamp()) - } + _expected = {"escrow_id": 100, "data": str(datetime.utcnow().timestamp())} mock_transfer.assert_called_once_with( data=EscrowApproveTransferParams(**_expected), tx_from=issuer_address, - private_key=ANY + private_key=ANY, ) - approval_op_list: list[TransferApprovalHistory] = db.query(TransferApprovalHistory).all() + approval_op_list: list[TransferApprovalHistory] = db.query( + TransferApprovalHistory + ).all() assert len(approval_op_list) == 1 approval_op = approval_op_list[0] assert approval_op.token_address == self.test_token_address @@ -240,7 +240,7 @@ def test_normal_1_2(self, client, db): # # CANCEL # token - @pytest.mark.freeze_time('2021-04-27 12:34:56') + @pytest.mark.freeze_time("2021-04-27 12:34:56") def test_normal_2_1(self, client, db): issuer = config_eth_account("user1") issuer_address = issuer["address"] @@ -270,7 +270,9 @@ def test_normal_2_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -279,7 +281,7 @@ def test_normal_2_1(self, client, db): # mock IbetSecurityTokenContract_cancel_transfer = mock.patch( target="app.model.blockchain.token.IbetSecurityTokenInterface.cancel_transfer", - return_value=("test_tx_hash", {"status": 1}) + return_value=("test_tx_hash", {"status": 1}), ) # request target API @@ -288,29 +290,26 @@ def test_normal_2_1(self, client, db): self.base_url.format(self.test_token_address, id), headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") + "eoa-password": E2EEUtils.encrypt("password"), }, - json={ - "operation_type": "cancel" - } + json={"operation_type": "cancel"}, ) # Assertion assert resp.status_code == 200 assert resp.json() is None - _expected = { - "application_id": 100, - "data": str(datetime.utcnow().timestamp()) - } + _expected = {"application_id": 100, "data": str(datetime.utcnow().timestamp())} mock_transfer.assert_called_once_with( data=ApproveTransferParams(**_expected), tx_from=issuer_address, - private_key=ANY + private_key=ANY, ) - cancel_op_list: list[TransferApprovalHistory] = db.query(TransferApprovalHistory).all() + cancel_op_list: list[TransferApprovalHistory] = db.query( + TransferApprovalHistory + ).all() assert len(cancel_op_list) == 1 cancel_op = cancel_op_list[0] assert cancel_op.token_address == self.test_token_address @@ -320,7 +319,7 @@ def test_normal_2_1(self, client, db): # # Authorization by auth-token - @pytest.mark.freeze_time('2021-04-27 12:34:56') + @pytest.mark.freeze_time("2021-04-27 12:34:56") def test_normal_3(self, client, db): issuer = config_eth_account("user1") issuer_address = issuer["address"] @@ -356,7 +355,9 @@ def test_normal_3(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -365,35 +366,30 @@ def test_normal_3(self, client, db): # mock IbetSecurityTokenContract_approve_transfer = mock.patch( target="app.model.blockchain.token.IbetSecurityTokenInterface.approve_transfer", - return_value=("test_tx_hash", {"status": 1}) + return_value=("test_tx_hash", {"status": 1}), ) # request target API with IbetSecurityTokenContract_approve_transfer as mock_transfer: resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "approve" - }, + json={"operation_type": "approve"}, headers={ "issuer-address": issuer_address, - "auth-token": "test_auth_token" - } + "auth-token": "test_auth_token", + }, ) # Assertion assert resp.status_code == 200 assert resp.json() is None - _expected = { - "application_id": 100, - "data": str(datetime.utcnow().timestamp()) - } + _expected = {"application_id": 100, "data": str(datetime.utcnow().timestamp())} mock_transfer.assert_called_once_with( data=ApproveTransferParams(**_expected), tx_from=issuer_address, - private_key=ANY + private_key=ANY, ) ########################################################################### @@ -414,22 +410,19 @@ def test_error_1_1(self, client, db): # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, { "loc": ["body"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, - ] + ], } # @@ -446,23 +439,20 @@ def test_error_1_2(self, client, db): json={}, headers={ "issuer-address": issuer_address, - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "operation_type"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, - ] + ], } # @@ -476,30 +466,25 @@ def test_error_1_3(self, client, db): # request target api resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "test" - }, + json={"operation_type": "test"}, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "operation_type"], "ctx": {"enum_values": ["approve", "cancel"]}, "msg": "value is not a valid enumeration member; permitted: 'approve', 'cancel'", - "type": "type_error.enum" + "type": "type_error.enum", }, - ] + ], } # @@ -511,34 +496,26 @@ def test_error_1_4(self, client, db): # request target api resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "approve" - }, - headers={ - "issuer-address": "issuer_address", - "eoa-password": "password" - } + json={"operation_type": "approve"}, + headers={"issuer-address": "issuer_address", "eoa-password": "password"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", }, { "loc": ["header", "eoa-password"], "msg": "eoa-password is not a Base64-encoded encrypted data", - "type": "value_error" - } - ] + "type": "value_error", + }, + ], } # @@ -553,23 +530,18 @@ def test_error_2_1(self, client, db): # request target api resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "approve" - }, + json={"operation_type": "approve"}, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -591,23 +563,18 @@ def test_error_2_2(self, client, db): # request target api resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "approve" - }, + json={"operation_type": "approve"}, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password_test") - } + "eoa-password": E2EEUtils.encrypt("password_test"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -629,23 +596,18 @@ def test_error_3_1(self, client, db): # request target api resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "approve" - }, + json={"operation_type": "approve"}, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # @@ -675,23 +637,18 @@ def test_error_3_2(self, client, db): # request target api resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "approve" - }, + json={"operation_type": "approve"}, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "transfer approval not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "transfer approval not found", } # @@ -722,23 +679,18 @@ def test_error_4_1(self, client, db): # request target api resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "approve" - }, + json={"operation_type": "approve"}, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } # @@ -773,9 +725,13 @@ def test_error_4_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = self.test_approval_datetime - _idx_transfer_approval.approval_blocktimestamp = self.test_approval_blocktimestamp + _idx_transfer_approval.approval_blocktimestamp = ( + self.test_approval_blocktimestamp + ) _idx_transfer_approval.cancelled = None _idx_transfer_approval.escrow_finished = None _idx_transfer_approval.transfer_approved = True @@ -784,23 +740,18 @@ def test_error_4_2(self, client, db): # request target api resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "approve" - }, + json={"operation_type": "approve"}, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "already approved" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "already approved", } # @@ -835,7 +786,9 @@ def test_error_4_3(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = True @@ -846,23 +799,18 @@ def test_error_4_3(self, client, db): # request target api resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "approve" - }, + json={"operation_type": "approve"}, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "canceled application" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "canceled application", } # @@ -897,7 +845,9 @@ def test_error_4_4(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = False @@ -910,21 +860,16 @@ def test_error_4_4(self, client, db): self.base_url.format(self.test_token_address, id), headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") + "eoa-password": E2EEUtils.encrypt("password"), }, - json={ - "operation_type": "cancel" - } + json={"operation_type": "cancel"}, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "escrow has not been finished yet" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "escrow has not been finished yet", } # @@ -959,7 +904,9 @@ def test_error_4_5(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = False @@ -972,21 +919,16 @@ def test_error_4_5(self, client, db): self.base_url.format(self.test_token_address, id), headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") + "eoa-password": E2EEUtils.encrypt("password"), }, - json={ - "operation_type": "cancel" - } + json={"operation_type": "cancel"}, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "application that cannot be canceled" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "application that cannot be canceled", } # @@ -1021,7 +963,9 @@ def test_error_4_6(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = False @@ -1041,21 +985,16 @@ def test_error_4_6(self, client, db): self.base_url.format(self.test_token_address, id), headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") + "eoa-password": E2EEUtils.encrypt("password"), }, - json={ - "operation_type": "cancel" - } + json={"operation_type": "cancel"}, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "duplicate operation" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "duplicate operation", } # @@ -1065,7 +1004,8 @@ def test_error_4_6(self, client, db): # raise SendTransactionError @mock.patch( "app.model.blockchain.token.IbetSecurityTokenInterface.approve_transfer", - MagicMock(side_effect=SendTransactionError())) + MagicMock(side_effect=SendTransactionError()), + ) def test_error_5_1(self, client, db): issuer = config_eth_account("user1") issuer_address = issuer["address"] @@ -1095,7 +1035,9 @@ def test_error_5_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -1104,23 +1046,18 @@ def test_error_5_1(self, client, db): # request target API resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "approve" - }, + json={"operation_type": "approve"}, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 2, - "title": "SendTransactionError" - }, - "detail": "failed to send transaction" + "meta": {"code": 2, "title": "SendTransactionError"}, + "detail": "failed to send transaction", } # @@ -1157,7 +1094,9 @@ def test_error_5_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -1166,34 +1105,31 @@ def test_error_5_2(self, client, db): # mock IbetSecurityTokenContract_approve_transfer = mock.patch( target="app.model.blockchain.token.IbetSecurityTokenInterface.approve_transfer", - side_effect=ContractRevertError("110902") + side_effect=ContractRevertError("110902"), ) IbetSecurityTokenContract_cancel_transfer = mock.patch( target="app.model.blockchain.token.IbetSecurityTokenInterface.cancel_transfer", - return_value=("test_tx_hash", {"status": 1}) + return_value=("test_tx_hash", {"status": 1}), ) # request target API - with IbetSecurityTokenContract_approve_transfer, IbetSecurityTokenContract_cancel_transfer: + with ( + IbetSecurityTokenContract_approve_transfer + ), IbetSecurityTokenContract_cancel_transfer: resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "approve" - }, + json={"operation_type": "approve"}, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 110902, - "title": "ContractRevertError" - }, - "detail": "Application is invalid." + "meta": {"code": 110902, "title": "ContractRevertError"}, + "detail": "Application is invalid.", } # @@ -1203,7 +1139,8 @@ def test_error_5_2(self, client, db): # raise SendTransactionError @mock.patch( "app.model.blockchain.exchange.IbetSecurityTokenEscrow.approve_transfer", - MagicMock(side_effect=SendTransactionError())) + MagicMock(side_effect=SendTransactionError()), + ) def test_error_5_3(self, client, db): issuer = config_eth_account("user1") issuer_address = issuer["address"] @@ -1233,7 +1170,9 @@ def test_error_5_3(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -1243,23 +1182,18 @@ def test_error_5_3(self, client, db): # request target API resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "approve" - }, + json={"operation_type": "approve"}, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 2, - "title": "SendTransactionError" - }, - "detail": "failed to send transaction" + "meta": {"code": 2, "title": "SendTransactionError"}, + "detail": "failed to send transaction", } # @@ -1296,7 +1230,9 @@ def test_error_5_4(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -1306,30 +1242,25 @@ def test_error_5_4(self, client, db): # mock IbetSecurityTokenEscrow_approve_transfer = mock.patch( target="app.model.blockchain.exchange.IbetSecurityTokenEscrow.approve_transfer", - side_effect=ContractRevertError("110902") + side_effect=ContractRevertError("110902"), ) # request target API with IbetSecurityTokenEscrow_approve_transfer: resp = client.post( self.base_url.format(self.test_token_address, id), - json={ - "operation_type": "approve" - }, + json={"operation_type": "approve"}, headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 110902, - "title": "ContractRevertError" - }, - "detail": "Application is invalid." + "meta": {"code": 110902, "title": "ContractRevertError"}, + "detail": "Application is invalid.", } # @@ -1339,7 +1270,8 @@ def test_error_5_4(self, client, db): # raise SendTransactionError @mock.patch( "app.model.blockchain.token.IbetSecurityTokenInterface.cancel_transfer", - MagicMock(side_effect=SendTransactionError())) + MagicMock(side_effect=SendTransactionError()), + ) def test_error_6_1(self, client, db): issuer = config_eth_account("user1") issuer_address = issuer["address"] @@ -1369,7 +1301,9 @@ def test_error_6_1(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -1380,21 +1314,16 @@ def test_error_6_1(self, client, db): self.base_url.format(self.test_token_address, id), headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") + "eoa-password": E2EEUtils.encrypt("password"), }, - json={ - "operation_type": "cancel" - } + json={"operation_type": "cancel"}, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 2, - "title": "SendTransactionError" - }, - "detail": "failed to send transaction" + "meta": {"code": 2, "title": "SendTransactionError"}, + "detail": "failed to send transaction", } # @@ -1431,7 +1360,9 @@ def test_error_6_2(self, client, db): _idx_transfer_approval.to_address = self.test_to_address _idx_transfer_approval.amount = 200 _idx_transfer_approval.application_datetime = self.test_application_datetime - _idx_transfer_approval.application_blocktimestamp = self.test_application_blocktimestamp + _idx_transfer_approval.application_blocktimestamp = ( + self.test_application_blocktimestamp + ) _idx_transfer_approval.approval_datetime = None _idx_transfer_approval.approval_blocktimestamp = None _idx_transfer_approval.cancelled = None @@ -1440,7 +1371,7 @@ def test_error_6_2(self, client, db): # mock IbetSecurityTokenContract_cancel_transfer = mock.patch( target="app.model.blockchain.token.IbetSecurityTokenInterface.cancel_transfer", - side_effect=ContractRevertError("110802") + side_effect=ContractRevertError("110802"), ) # request target API @@ -1449,19 +1380,14 @@ def test_error_6_2(self, client, db): self.base_url.format(self.test_token_address, id), headers={ "issuer-address": issuer_address, - "eoa-password": E2EEUtils.encrypt("password") + "eoa-password": E2EEUtils.encrypt("password"), }, - json={ - "operation_type": "cancel" - } + json={"operation_type": "cancel"}, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 110802, - "title": "ContractRevertError" - }, - "detail": "Application is invalid." + "meta": {"code": 110802, "title": "ContractRevertError"}, + "detail": "Application is invalid.", } diff --git a/tests/test_app_routers_share_transfers_POST.py b/tests/test_app_routers_share_transfers_POST.py index 9325c329..db575d6e 100644 --- a/tests/test_app_routers_share_transfers_POST.py +++ b/tests/test_app_routers_share_transfers_POST.py @@ -20,14 +20,9 @@ from unittest import mock from unittest.mock import ANY, MagicMock -from app.model.db import ( - Account, - AuthToken, - Token, - TokenType -) -from app.utils.e2ee_utils import E2EEUtils from app.exceptions import SendTransactionError +from app.model.db import Account, AuthToken, Token, TokenType +from app.utils.e2ee_utils import E2EEUtils from tests.account_config import config_eth_account @@ -78,15 +73,15 @@ def test_normal_1(self, IbetShareContract_mock, client, db): "token_address": _token_address, "from_address": _from_address, "to_address": _to_address, - "amount": 10 + "amount": 10, } resp = client.post( self.test_url, json=req_param, headers={ "issuer-address": _admin_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion @@ -94,10 +89,10 @@ def test_normal_1(self, IbetShareContract_mock, client, db): data={ "from_address": _from_address, "to_address": _to_address, - "amount": 10 + "amount": 10, }, tx_from=_admin_address, - private_key=ANY + private_key=ANY, ) assert resp.status_code == 200 @@ -148,15 +143,12 @@ def test_normal_2(self, IbetShareContract_mock, client, db): "token_address": _token_address, "from_address": _from_address, "to_address": _to_address, - "amount": 10 + "amount": 10, } resp = client.post( self.test_url, json=req_param, - headers={ - "issuer-address": _admin_address, - "auth-token": "test_auth_token" - } + headers={"issuer-address": _admin_address, "auth-token": "test_auth_token"}, ) # assertion @@ -164,10 +156,10 @@ def test_normal_2(self, IbetShareContract_mock, client, db): data={ "from_address": _from_address, "to_address": _to_address, - "amount": 10 + "amount": 10, }, tx_from=_admin_address, - private_key=ANY + private_key=ANY, ) assert resp.status_code == 200 @@ -191,51 +183,39 @@ def test_error_1(self, client, db): "token_address": _token_address, "from_address": _from_address, "to_address": _to_address, - "amount": 0 + "amount": 0, } resp = client.post( - self.test_url, - json=req_param, - headers={ - "issuer-address": _admin_address - } + self.test_url, json=req_param, headers={"issuer-address": _admin_address} ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["body", "token_address"], "msg": "token_address is not a valid address", - "type": "value_error" + "type": "value_error", }, { "loc": ["body", "from_address"], "msg": "from_address is not a valid address", - "type": "value_error" + "type": "value_error", }, { "loc": ["body", "to_address"], "msg": "to_address is not a valid address", - "type": "value_error" + "type": "value_error", }, { - "ctx": { - "limit_value": 1 - }, - "loc": [ - "body", - "amount" - ], + "ctx": {"limit_value": 1}, + "loc": ["body", "amount"], "msg": "ensure this value is greater than or equal to 1", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", }, - ] + ], } # @@ -258,65 +238,48 @@ def test_error_2(self, client, db): "token_address": _token_address, "from_address": _from_address, "to_address": _to_address, - "amount": 1_000_000_000_001 + "amount": 1_000_000_000_001, } resp = client.post( - self.test_url, - json=req_param, - headers={ - "issuer-address": _admin_address - } + self.test_url, json=req_param, headers={"issuer-address": _admin_address} ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "ctx": { - "limit_value": 1_000_000_000_000 - }, - "loc": [ - "body", - "amount" - ], + "ctx": {"limit_value": 1_000_000_000_000}, + "loc": ["body", "amount"], "msg": "ensure this value is less than or equal to 1000000000000", - "type": "value_error.number.not_le" + "type": "value_error.number.not_le", }, - ] + ], } # # RequestValidationError: headers and body required def test_error_3(self, client, db): # request target API - resp = client.post( - self.test_url - ) + resp = client.post(self.test_url) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "field required", - "type": "value_error.missing" + "type": "value_error.missing", }, { "loc": ["body"], "msg": "field required", - "type": "value_error.missing" - } - ] + "type": "value_error.missing", + }, + ], } # @@ -339,30 +302,23 @@ def test_error_4(self, client, db): "token_address": _token_address, "from_address": _from_address, "to_address": _to_address, - "amount": 10 + "amount": 10, } resp = client.post( - self.test_url, - json=req_param, - headers={ - "issuer-address": "issuer-address" - } + self.test_url, json=req_param, headers={"issuer-address": "issuer-address"} ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -385,29 +341,25 @@ def test_error_5(self, client, db): "token_address": _token_address, "from_address": _from_address, "to_address": _to_address, - "amount": 10 + "amount": 10, } resp = client.post( self.test_url, json=req_param, - headers={ - "issuer-address": _admin_address, - "eoa-password": "password" - } + headers={"issuer-address": _admin_address, "eoa-password": "password"}, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, - "detail": [{ - "loc": ["header", "eoa-password"], - "msg": "eoa-password is not a Base64-encoded encrypted data", - "type": "value_error" - }] + "meta": {"code": 1, "title": "RequestValidationError"}, + "detail": [ + { + "loc": ["header", "eoa-password"], + "msg": "eoa-password is not a Base64-encoded encrypted data", + "type": "value_error", + } + ], } # @@ -430,25 +382,22 @@ def test_error_6(self, client, db): "token_address": _token_address, "from_address": _from_address, "to_address": _to_address, - "amount": 10 + "amount": 10, } resp = client.post( self.test_url, json=req_param, headers={ "issuer-address": _admin_address, # Non-existent issuer - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -478,25 +427,22 @@ def test_error_7(self, client, db): "token_address": _token_address, "from_address": _from_address, "to_address": _to_address, - "amount": 10 + "amount": 10, } resp = client.post( self.test_url, json=req_param, headers={ "issuer-address": _admin_address, - "eoa-password": E2EEUtils.encrypt("password_test") - } + "eoa-password": E2EEUtils.encrypt("password_test"), + }, ) # assertion assert resp.status_code == 401 assert resp.json() == { - "meta": { - "code": 1, - "title": "AuthorizationError" - }, - "detail": "issuer does not exist, or password mismatch" + "meta": {"code": 1, "title": "AuthorizationError"}, + "detail": "issuer does not exist, or password mismatch", } # @@ -526,25 +472,22 @@ def test_error_8(self, client, db): "token_address": _token_address, "from_address": _from_address, "to_address": _to_address, - "amount": 10 + "amount": 10, } resp = client.post( self.test_url, json=req_param, headers={ "issuer-address": _admin_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } # @@ -583,31 +526,30 @@ def test_error_9(self, client, db): "token_address": _token_address, "from_address": _from_address, "to_address": _to_address, - "amount": 10 + "amount": 10, } resp = client.post( self.test_url, json=req_param, headers={ "issuer-address": _admin_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } # # Send Transaction Error - @mock.patch("app.model.blockchain.token.IbetShareContract.transfer", - MagicMock(side_effect=SendTransactionError())) + @mock.patch( + "app.model.blockchain.token.IbetShareContract.transfer", + MagicMock(side_effect=SendTransactionError()), + ) def test_error_10(self, client, db): _admin_account = config_eth_account("user1") _admin_address = _admin_account["address"] @@ -641,23 +583,20 @@ def test_error_10(self, client, db): "token_address": _token_address, "from_address": _from_address, "to_address": _to_address, - "amount": 10 + "amount": 10, } resp = client.post( self.test_url, json=req_param, headers={ "issuer-address": _admin_address, - "eoa-password": E2EEUtils.encrypt("password") - } + "eoa-password": E2EEUtils.encrypt("password"), + }, ) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 2, - "title": "SendTransactionError" - }, - "detail": "failed to send transaction" + "meta": {"code": 2, "title": "SendTransactionError"}, + "detail": "failed to send transaction", } diff --git a/tests/test_app_routers_share_transfers_{token_Address}_GET.py b/tests/test_app_routers_share_transfers_{token_Address}_GET.py index 9b8e87ca..b65f9b2c 100644 --- a/tests/test_app_routers_share_transfers_{token_Address}_GET.py +++ b/tests/test_app_routers_share_transfers_{token_Address}_GET.py @@ -21,12 +21,7 @@ from pytz import timezone import config -from app.model.db import ( - Token, - TokenType, - IDXTransfer, - IDXTransferSourceEventType -) +from app.model.db import IDXTransfer, IDXTransferSourceEventType, Token, TokenType local_tz = timezone(config.TZ) @@ -41,9 +36,9 @@ class TestAppRoutersShareTransfersGET: test_from_address = "test_from_address" test_to_address = "test_to_address" test_block_timestamp = [ - datetime.strptime("2022/01/02 15:20:30", '%Y/%m/%d %H:%M:%S'), # JST 2022/01/03 - datetime.strptime("2022/01/01 15:20:30", '%Y/%m/%d %H:%M:%S'), # JST 2022/01/02 - datetime.strptime("2022/01/02 00:20:30", '%Y/%m/%d %H:%M:%S'), # JST 2022/01/02 + datetime.strptime("2022/01/02 15:20:30", "%Y/%m/%d %H:%M:%S"), # JST 2022/01/03 + datetime.strptime("2022/01/01 15:20:30", "%Y/%m/%d %H:%M:%S"), # JST 2022/01/02 + datetime.strptime("2022/01/02 00:20:30", "%Y/%m/%d %H:%M:%S"), # JST 2022/01/02 ] test_block_timestamp_str = [ "2022-01-03T00:20:30+09:00", @@ -81,19 +76,12 @@ def test_normal_1(self, client, db): db.add(_idx_transfer) # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 3, - "offset": None, - "limit": None, - "total": 3 - }, + "result_set": {"count": 3, "offset": None, "limit": None, "total": 3}, "transfer_history": [ { "transaction_hash": self.test_transaction_hash, @@ -103,7 +91,7 @@ def test_normal_1(self, client, db): "amount": 0, "source_event": IDXTransferSourceEventType.TRANSFER.value, "data": None, - "block_timestamp": self.test_block_timestamp_str[0] + "block_timestamp": self.test_block_timestamp_str[0], }, { "transaction_hash": self.test_transaction_hash, @@ -113,7 +101,7 @@ def test_normal_1(self, client, db): "amount": 2, "source_event": IDXTransferSourceEventType.TRANSFER.value, "data": None, - "block_timestamp": self.test_block_timestamp_str[2] + "block_timestamp": self.test_block_timestamp_str[2], }, { "transaction_hash": self.test_transaction_hash, @@ -123,9 +111,9 @@ def test_normal_1(self, client, db): "amount": 1, "source_event": IDXTransferSourceEventType.TRANSFER.value, "data": None, - "block_timestamp": self.test_block_timestamp_str[1] + "block_timestamp": self.test_block_timestamp_str[1], }, - ] + ], } assert resp.json() == assumed_response @@ -162,12 +150,7 @@ def test_normal_2_1(self, client, db): # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 3, - "offset": 1, - "limit": 1, - "total": 3 - }, + "result_set": {"count": 3, "offset": 1, "limit": 1, "total": 3}, "transfer_history": [ { "transaction_hash": self.test_transaction_hash, @@ -177,9 +160,9 @@ def test_normal_2_1(self, client, db): "amount": 2, "source_event": IDXTransferSourceEventType.TRANSFER.value, "data": None, - "block_timestamp": self.test_block_timestamp_str[2] + "block_timestamp": self.test_block_timestamp_str[2], }, - ] + ], } assert resp.json() == assumed_response @@ -232,20 +215,13 @@ def test_normal_2_2(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "source_event": IDXTransferSourceEventType.UNLOCK.value - } + params={"source_event": IDXTransferSourceEventType.UNLOCK.value}, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 1, - "offset": None, - "limit": None, - "total": 3 - }, + "result_set": {"count": 1, "offset": None, "limit": None, "total": 3}, "transfer_history": [ { "transaction_hash": self.test_transaction_hash, @@ -255,9 +231,9 @@ def test_normal_2_2(self, client, db): "amount": 2, "source_event": IDXTransferSourceEventType.UNLOCK.value, "data": {"message": "unlock"}, - "block_timestamp": self.test_block_timestamp_str[2] + "block_timestamp": self.test_block_timestamp_str[2], }, - ] + ], } assert resp.json() == assumed_response @@ -309,21 +285,13 @@ def test_normal_2_3(self, client, db): # request target API resp = client.get( - self.base_url.format(self.test_token_address), - params={ - "data": "unlo" - } + self.base_url.format(self.test_token_address), params={"data": "unlo"} ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 1, - "offset": None, - "limit": None, - "total": 3 - }, + "result_set": {"count": 1, "offset": None, "limit": None, "total": 3}, "transfer_history": [ { "transaction_hash": self.test_transaction_hash, @@ -333,9 +301,9 @@ def test_normal_2_3(self, client, db): "amount": 2, "source_event": IDXTransferSourceEventType.UNLOCK.value, "data": {"message": "unlock"}, - "block_timestamp": self.test_block_timestamp_str[2] + "block_timestamp": self.test_block_timestamp_str[2], }, - ] + ], } assert resp.json() == assumed_response @@ -370,18 +338,13 @@ def test_normal_3(self, client, db): params={ "sort_item": "block_timestamp", "sort_order": 0, - } + }, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 3, - "offset": None, - "limit": None, - "total": 3 - }, + "result_set": {"count": 3, "offset": None, "limit": None, "total": 3}, "transfer_history": [ { "transaction_hash": self.test_transaction_hash, @@ -391,7 +354,7 @@ def test_normal_3(self, client, db): "amount": 1, "source_event": IDXTransferSourceEventType.TRANSFER.value, "data": None, - "block_timestamp": self.test_block_timestamp_str[1] + "block_timestamp": self.test_block_timestamp_str[1], }, { "transaction_hash": self.test_transaction_hash, @@ -401,7 +364,7 @@ def test_normal_3(self, client, db): "amount": 2, "source_event": IDXTransferSourceEventType.TRANSFER.value, "data": None, - "block_timestamp": self.test_block_timestamp_str[2] + "block_timestamp": self.test_block_timestamp_str[2], }, { "transaction_hash": self.test_transaction_hash, @@ -411,9 +374,9 @@ def test_normal_3(self, client, db): "amount": 0, "source_event": IDXTransferSourceEventType.TRANSFER.value, "data": None, - "block_timestamp": self.test_block_timestamp_str[0] - } - ] + "block_timestamp": self.test_block_timestamp_str[0], + }, + ], } assert resp.json() == assumed_response @@ -469,18 +432,13 @@ def test_normal_4(self, client, db): params={ "sort_item": "from_address", "sort_order": 0, - } + }, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 3, - "offset": None, - "limit": None, - "total": 3 - }, + "result_set": {"count": 3, "offset": None, "limit": None, "total": 3}, "transfer_history": [ { "transaction_hash": self.test_transaction_hash, @@ -490,7 +448,7 @@ def test_normal_4(self, client, db): "amount": 2, "source_event": IDXTransferSourceEventType.UNLOCK.value, "data": {"message": "unlock"}, - "block_timestamp": self.test_block_timestamp_str[2] + "block_timestamp": self.test_block_timestamp_str[2], }, { "transaction_hash": self.test_transaction_hash, @@ -500,7 +458,7 @@ def test_normal_4(self, client, db): "amount": 0, "source_event": IDXTransferSourceEventType.TRANSFER.value, "data": None, - "block_timestamp": self.test_block_timestamp_str[0] + "block_timestamp": self.test_block_timestamp_str[0], }, { "transaction_hash": self.test_transaction_hash, @@ -510,9 +468,9 @@ def test_normal_4(self, client, db): "amount": 1, "source_event": IDXTransferSourceEventType.TRANSFER.value, "data": None, - "block_timestamp": self.test_block_timestamp_str[1] + "block_timestamp": self.test_block_timestamp_str[1], }, - ] + ], } assert resp.json() == assumed_response @@ -568,18 +526,13 @@ def test_normal_5(self, client, db): params={ "sort_item": "to_address", "sort_order": 1, - } + }, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 3, - "offset": None, - "limit": None, - "total": 3 - }, + "result_set": {"count": 3, "offset": None, "limit": None, "total": 3}, "transfer_history": [ { "transaction_hash": self.test_transaction_hash, @@ -589,7 +542,7 @@ def test_normal_5(self, client, db): "amount": 0, "source_event": IDXTransferSourceEventType.TRANSFER.value, "data": None, - "block_timestamp": self.test_block_timestamp_str[0] + "block_timestamp": self.test_block_timestamp_str[0], }, { "transaction_hash": self.test_transaction_hash, @@ -599,7 +552,7 @@ def test_normal_5(self, client, db): "amount": 2, "source_event": IDXTransferSourceEventType.UNLOCK.value, "data": {"message": "unlock"}, - "block_timestamp": self.test_block_timestamp_str[2] + "block_timestamp": self.test_block_timestamp_str[2], }, { "transaction_hash": self.test_transaction_hash, @@ -609,9 +562,9 @@ def test_normal_5(self, client, db): "amount": 1, "source_event": IDXTransferSourceEventType.TRANSFER.value, "data": None, - "block_timestamp": self.test_block_timestamp_str[1] + "block_timestamp": self.test_block_timestamp_str[1], }, - ] + ], } assert resp.json() == assumed_response @@ -667,18 +620,13 @@ def test_normal_6(self, client, db): params={ "sort_item": "amount", "sort_order": 0, - } + }, ) # assertion assert resp.status_code == 200 assumed_response = { - "result_set": { - "count": 3, - "offset": None, - "limit": None, - "total": 3 - }, + "result_set": {"count": 3, "offset": None, "limit": None, "total": 3}, "transfer_history": [ { "transaction_hash": self.test_transaction_hash, @@ -688,7 +636,7 @@ def test_normal_6(self, client, db): "amount": 1, "source_event": IDXTransferSourceEventType.TRANSFER.value, "data": None, - "block_timestamp": self.test_block_timestamp_str[0] + "block_timestamp": self.test_block_timestamp_str[0], }, { "transaction_hash": self.test_transaction_hash, @@ -698,7 +646,7 @@ def test_normal_6(self, client, db): "amount": 2, "source_event": IDXTransferSourceEventType.UNLOCK.value, "data": {"message": "unlock"}, - "block_timestamp": self.test_block_timestamp_str[2] + "block_timestamp": self.test_block_timestamp_str[2], }, { "transaction_hash": self.test_transaction_hash, @@ -708,9 +656,9 @@ def test_normal_6(self, client, db): "amount": 2, "source_event": IDXTransferSourceEventType.TRANSFER.value, "data": None, - "block_timestamp": self.test_block_timestamp_str[1] + "block_timestamp": self.test_block_timestamp_str[1], }, - ] + ], } assert resp.json() == assumed_response @@ -722,18 +670,13 @@ def test_normal_6(self, client, db): # token not found def test_error_1(self, client, db): # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 404 assumed_response = { - "meta": { - "code": 1, - "title": "NotFound" - }, - "detail": "token not found" + "meta": {"code": 1, "title": "NotFound"}, + "detail": "token not found", } assert resp.json() == assumed_response @@ -751,18 +694,13 @@ def test_error_2(self, client, db): db.add(_token) # request target API - resp = client.get( - self.base_url.format(self.test_token_address) - ) + resp = client.get(self.base_url.format(self.test_token_address)) # assertion assert resp.status_code == 400 assert resp.json() == { - "meta": { - "code": 1, - "title": "InvalidParameterError" - }, - "detail": "this token is temporarily unavailable" + "meta": {"code": 1, "title": "InvalidParameterError"}, + "detail": "this token is temporarily unavailable", } # @@ -771,27 +709,29 @@ def test_error_3(self, client, db): # request target API resp = client.get( self.base_url.format(self.test_token_address), - params={ - "sort_item": "block_timestamp12345" - } + params={"sort_item": "block_timestamp12345"}, ) # assertion assert resp.status_code == 422 assumed_response = { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "ctx": {"enum_values": ["block_timestamp", "from_address", "to_address", "amount"]}, + "ctx": { + "enum_values": [ + "block_timestamp", + "from_address", + "to_address", + "amount", + ] + }, "loc": ["query", "sort_item"], "msg": "value is not a valid enumeration member; permitted: 'block_timestamp', 'from_address', " - "'to_address', 'amount'", - "type": "type_error.enum" + "'to_address', 'amount'", + "type": "type_error.enum", } - ] + ], } assert resp.json() == assumed_response @@ -800,29 +740,21 @@ def test_error_3(self, client, db): def test_error_4(self, client, db): # request target API resp = client.get( - self.base_url.format(self.test_token_address), - params={ - "sort_order": -1 - } + self.base_url.format(self.test_token_address), params={"sort_order": -1} ) # assertion assert resp.status_code == 422 assumed_response = { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "ctx": { - "limit_value": 0 - }, + "ctx": {"limit_value": 0}, "loc": ["query", "sort_order"], "msg": "ensure this value is greater than or equal to 0", - "type": "value_error.number.not_ge" + "type": "value_error.number.not_ge", } - ] + ], } assert resp.json() == assumed_response @@ -831,28 +763,20 @@ def test_error_4(self, client, db): def test_error_5(self, client, db): # request target API resp = client.get( - self.base_url.format(self.test_token_address), - params={ - "sort_order": 2 - } + self.base_url.format(self.test_token_address), params={"sort_order": 2} ) # assertion assert resp.status_code == 422 assumed_response = { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - "ctx": { - "limit_value": 1 - }, + "ctx": {"limit_value": 1}, "loc": ["query", "sort_order"], "msg": "ensure this value is less than or equal to 1", - "type": "value_error.number.not_le" + "type": "value_error.number.not_le", } - ] + ], } assert resp.json() == assumed_response diff --git a/tests/test_app_routers_token_holders_{token_address}_GET.py b/tests/test_app_routers_token_holders_{token_address}_GET.py index 68bc52fd..b3c4a642 100644 --- a/tests/test_app_routers_token_holders_{token_address}_GET.py +++ b/tests/test_app_routers_token_holders_{token_address}_GET.py @@ -19,12 +19,7 @@ import uuid from unittest import mock -from app.model.db import ( - Token, - TokenType, - TokenHoldersList, - TokenHolderBatchStatus -) +from app.model.db import Token, TokenHolderBatchStatus, TokenHoldersList, TokenType from tests.account_config import config_eth_account @@ -53,21 +48,13 @@ def test_normal_1(self, client, db): db.add(token) # request target API - resp = client.get( - self.base_url.format(token_address), - headers={} - ) + resp = client.get(self.base_url.format(token_address), headers={}) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 0, - "limit": None, - "offset": None, - "total": 0 - }, - "collections": [] - } + "result_set": {"count": 0, "limit": None, "offset": None, "total": 0}, + "collections": [], + } # # 1 record @@ -93,27 +80,19 @@ def test_normal_2(self, client, db): db.add(token_holder_list1) # request target API - resp = client.get( - self.base_url.format(token_address), - headers={} - ) + resp = client.get(self.base_url.format(token_address), headers={}) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 1, - "limit": None, - "offset": None, - "total": 1 - }, + "result_set": {"count": 1, "limit": None, "offset": None, "total": 1}, "collections": [ { "token_address": token_address, "block_number": 100, "list_id": mock.ANY, - "status": TokenHolderBatchStatus.PENDING.value + "status": TokenHolderBatchStatus.PENDING.value, } - ] + ], } # @@ -169,51 +148,43 @@ def test_normal_3_1(self, client, db): db.add(token_holder_list5) # request target API - resp = client.get( - self.base_url.format(token_address), - headers={} - ) + resp = client.get(self.base_url.format(token_address), headers={}) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 5, - "limit": None, - "offset": None, - "total": 5 - }, + "result_set": {"count": 5, "limit": None, "offset": None, "total": 5}, "collections": [ { "token_address": token_address, "block_number": 500, "list_id": mock.ANY, - "status": TokenHolderBatchStatus.DONE.value + "status": TokenHolderBatchStatus.DONE.value, }, { "token_address": token_address, "block_number": 400, "list_id": mock.ANY, - "status": TokenHolderBatchStatus.DONE.value + "status": TokenHolderBatchStatus.DONE.value, }, { "token_address": token_address, "block_number": 300, "list_id": mock.ANY, - "status": TokenHolderBatchStatus.FAILED.value + "status": TokenHolderBatchStatus.FAILED.value, }, { "token_address": token_address, "block_number": 200, "list_id": mock.ANY, - "status": TokenHolderBatchStatus.FAILED.value + "status": TokenHolderBatchStatus.FAILED.value, }, { "token_address": token_address, "block_number": 100, "list_id": mock.ANY, - "status": TokenHolderBatchStatus.PENDING.value - } - ] + "status": TokenHolderBatchStatus.PENDING.value, + }, + ], } # @@ -270,51 +241,44 @@ def test_normal_3_2(self, client, db): # request target API resp = client.get( self.base_url.format(token_address), - headers={ - "issuer-address": issuer_address - } + headers={"issuer-address": issuer_address}, ) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 5, - "limit": None, - "offset": None, - "total": 5 - }, + "result_set": {"count": 5, "limit": None, "offset": None, "total": 5}, "collections": [ { "token_address": token_address, "block_number": 500, "list_id": mock.ANY, - "status": TokenHolderBatchStatus.DONE.value + "status": TokenHolderBatchStatus.DONE.value, }, { "token_address": token_address, "block_number": 400, "list_id": mock.ANY, - "status": TokenHolderBatchStatus.DONE.value + "status": TokenHolderBatchStatus.DONE.value, }, { "token_address": token_address, "block_number": 300, "list_id": mock.ANY, - "status": TokenHolderBatchStatus.FAILED.value + "status": TokenHolderBatchStatus.FAILED.value, }, { "token_address": token_address, "block_number": 200, "list_id": mock.ANY, - "status": TokenHolderBatchStatus.FAILED.value + "status": TokenHolderBatchStatus.FAILED.value, }, { "token_address": token_address, "block_number": 100, "list_id": mock.ANY, - "status": TokenHolderBatchStatus.PENDING.value - } - ] + "status": TokenHolderBatchStatus.PENDING.value, + }, + ], } # @@ -371,30 +335,21 @@ def test_normal_3_3(self, client, db): # request target API resp = client.get( self.base_url.format(token_address), - headers={ - "issuer-address": issuer_address - }, - params={ - "status": str(TokenHolderBatchStatus.PENDING.value) - } + headers={"issuer-address": issuer_address}, + params={"status": str(TokenHolderBatchStatus.PENDING.value)}, ) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 1, - "limit": None, - "offset": None, - "total": 5 - }, + "result_set": {"count": 1, "limit": None, "offset": None, "total": 5}, "collections": [ { "token_address": token_address, "block_number": 100, "list_id": mock.ANY, - "status": TokenHolderBatchStatus.PENDING.value + "status": TokenHolderBatchStatus.PENDING.value, } - ] + ], } # @@ -449,37 +404,26 @@ def test_normal_4(self, client, db): db.add(token_holder_list5) # request target API - req_param = { - "limit": 2, - "offset": 2 - } - resp = client.get( - self.base_url.format(token_address), - params=req_param - ) + req_param = {"limit": 2, "offset": 2} + resp = client.get(self.base_url.format(token_address), params=req_param) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 5, - "limit": 2, - "offset": 2, - "total": 5 - }, + "result_set": {"count": 5, "limit": 2, "offset": 2, "total": 5}, "collections": [ { "token_address": token_address, "block_number": 300, "list_id": mock.ANY, - "status": TokenHolderBatchStatus.FAILED.value + "status": TokenHolderBatchStatus.FAILED.value, }, { "token_address": token_address, "block_number": 200, "list_id": mock.ANY, - "status": TokenHolderBatchStatus.FAILED.value - } - ] + "status": TokenHolderBatchStatus.FAILED.value, + }, + ], } # @@ -534,54 +478,44 @@ def test_normal_5(self, client, db): db.add(token_holder_list5) # request target API - req_param = { - "sort_order": 0 - } - resp = client.get( - self.base_url.format(token_address), - params=req_param - ) + req_param = {"sort_order": 0} + resp = client.get(self.base_url.format(token_address), params=req_param) assert resp.status_code == 200 assert resp.json() == { - "result_set": { - "count": 5, - "limit": None, - "offset": None, - "total": 5 - }, + "result_set": {"count": 5, "limit": None, "offset": None, "total": 5}, "collections": [ { "token_address": token_address, "block_number": 100, "list_id": mock.ANY, - "status": TokenHolderBatchStatus.PENDING.value + "status": TokenHolderBatchStatus.PENDING.value, }, { "token_address": token_address, "block_number": 200, "list_id": mock.ANY, - "status": TokenHolderBatchStatus.FAILED.value + "status": TokenHolderBatchStatus.FAILED.value, }, { "token_address": token_address, "block_number": 300, "list_id": mock.ANY, - "status": TokenHolderBatchStatus.FAILED.value + "status": TokenHolderBatchStatus.FAILED.value, }, { "token_address": token_address, "block_number": 400, "list_id": mock.ANY, - "status": TokenHolderBatchStatus.DONE.value + "status": TokenHolderBatchStatus.DONE.value, }, { "token_address": token_address, "block_number": 500, "list_id": mock.ANY, - "status": TokenHolderBatchStatus.DONE.value - } - ] + "status": TokenHolderBatchStatus.DONE.value, + }, + ], } ########################################################################### @@ -596,23 +530,20 @@ def test_error_1(self, client, db): self.base_url, headers={ "issuer-address": "test", - } + }, ) # assertion assert resp.status_code == 422 assert resp.json() == { - "meta": { - "code": 1, - "title": "RequestValidationError" - }, + "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { "loc": ["header", "issuer-address"], "msg": "issuer-address is not a valid address", - "type": "value_error" + "type": "value_error", } - ] + ], } # @@ -624,18 +555,14 @@ def test_error_2(self, client, db): # request target API resp = client.get( self.base_url.format("invalid_address"), - headers={ - "issuer-address": issuer_address - } + headers={"issuer-address": issuer_address}, ) # assertion assert resp.status_code == 404 assert resp.json() == { - "detail": "token not found", - "meta": { - "code": 1, "title": "NotFound" - } + "detail": "token not found", + "meta": {"code": 1, "title": "NotFound"}, } # @@ -658,16 +585,12 @@ def test_error_3(self, client, db): # request target API resp = client.get( self.base_url.format(token_address), - headers={ - "issuer-address": issuer_address - } + headers={"issuer-address": issuer_address}, ) # assertion assert resp.status_code == 400 assert resp.json() == { "detail": "this token is temporarily unavailable", - "meta": { - "code": 1, "title": "InvalidParameterError" - } + "meta": {"code": 1, "title": "InvalidParameterError"}, } diff --git a/tests/test_app_routers_token_holders_{token_address}_collection_POST.py b/tests/test_app_routers_token_holders_{token_address}_collection_POST.py index b2b52200..3e01f4f8 100644 --- a/tests/test_app_routers_token_holders_{token_address}_collection_POST.py +++ b/tests/test_app_routers_token_holders_{token_address}_collection_POST.py @@ -18,11 +18,12 @@ """ import uuid from unittest import mock + from web3 import Web3 from web3.middleware import geth_poa_middleware -from app.model.db import Token, TokenType, TokenHolderBatchStatus, TokenHoldersList import config +from app.model.db import Token, TokenHolderBatchStatus, TokenHoldersList, TokenType from tests.account_config import config_eth_account web3 = Web3(Web3.HTTPProvider(config.WEB3_HTTP_PROVIDER)) @@ -67,7 +68,11 @@ def test_normal_1(self, client, db): headers={"issuer-address": issuer_address}, ) - stored_data: TokenHoldersList = db.query(TokenHoldersList).filter(TokenHoldersList.list_id == list_id).first() + stored_data: TokenHoldersList = ( + db.query(TokenHoldersList) + .filter(TokenHoldersList.list_id == list_id) + .first() + ) # assertion assert resp.status_code == 200 assert resp.json() == { @@ -275,7 +280,13 @@ def test_error_3(self, client, db): assert resp.status_code == 422 assert resp.json() == { "meta": {"code": 1, "title": "RequestValidationError"}, - "detail": [{"loc": ["body", "list_id"], "msg": "list_id is not UUIDv4.", "type": "value_error"}], + "detail": [ + { + "loc": ["body", "list_id"], + "msg": "list_id is not UUIDv4.", + "type": "value_error", + } + ], } # Error_4 @@ -446,5 +457,11 @@ def test_error_7(self, client, db): assert resp.status_code == 422 assert resp.json() == { "meta": {"code": 1, "title": "RequestValidationError"}, - "detail": [{"loc": ["header", "issuer-address"], "msg": "field required", "type": "value_error.missing"}], + "detail": [ + { + "loc": ["header", "issuer-address"], + "msg": "field required", + "type": "value_error.missing", + } + ], } diff --git a/tests/test_app_routers_token_holders_{token_address}_collection_{collection_id}_GET.py b/tests/test_app_routers_token_holders_{token_address}_collection_{collection_id}_GET.py index 8711cb55..2f735bcb 100644 --- a/tests/test_app_routers_token_holders_{token_address}_collection_{collection_id}_GET.py +++ b/tests/test_app_routers_token_holders_{token_address}_collection_{collection_id}_GET.py @@ -18,17 +18,18 @@ """ import uuid from unittest import mock + from web3 import Web3 from web3.middleware import geth_poa_middleware +import config from app.model.db import ( Token, - TokenType, + TokenHolder, TokenHolderBatchStatus, TokenHoldersList, - TokenHolder, + TokenType, ) -import config from tests.account_config import config_eth_account web3 = Web3(Web3.HTTPProvider(config.WEB3_HTTP_PROVIDER)) @@ -117,8 +118,8 @@ def test_normal_2(self, client, db): _token_holder = TokenHolder() _token_holder.holder_list_id = _token_holders_list.id _token_holder.account_address = config_eth_account(user)["address"] - _token_holder.hold_balance = 10000 * (i+1) - _token_holder.locked_balance = 20000 * (i+1) + _token_holder.hold_balance = 10000 * (i + 1) + _token_holder.locked_balance = 20000 * (i + 1) db.add(_token_holder) holders.append(_token_holder.json()) @@ -128,7 +129,7 @@ def test_normal_2(self, client, db): headers={"issuer-address": issuer_address}, ) db.query(TokenHolder).filter().all() - sorted_holders = sorted(holders, key=lambda x: x['account_address']) + sorted_holders = sorted(holders, key=lambda x: x["account_address"]) # assertion assert resp.status_code == 200 assert resp.json() == { @@ -360,9 +361,9 @@ def test_error_6(self, client, db): "meta": {"code": 1, "title": "RequestValidationError"}, "detail": [ { - 'loc': ['header', 'issuer-address'], - 'msg': 'field required', - 'type': 'value_error.missing' + "loc": ["header", "issuer-address"], + "msg": "field required", + "type": "value_error.missing", } - ] + ], } diff --git a/tests/test_batch_indexer_block_tx_data.py b/tests/test_batch_indexer_block_tx_data.py index 9531957d..eb7c1937 100644 --- a/tests/test_batch_indexer_block_tx_data.py +++ b/tests/test_batch_indexer_block_tx_data.py @@ -24,25 +24,17 @@ from eth_keyfile import decode_keyfile_json from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.orm import Session +from utils.contract_utils import IbetStandardTokenUtils from web3 import Web3 from web3.middleware import geth_poa_middleware from web3.types import RPCEndpoint -from config import ( - CHAIN_ID, - WEB3_HTTP_PROVIDER, - ZERO_ADDRESS -) from app.exceptions import ServiceUnavailableError -from app.model.db import ( - IDXBlockData, - IDXBlockDataBlockNumber, - IDXTxData -) +from app.model.db import IDXBlockData, IDXBlockDataBlockNumber, IDXTxData from batch import indexer_block_tx_data from batch.indexer_block_tx_data import LOG +from config import CHAIN_ID, WEB3_HTTP_PROVIDER, ZERO_ADDRESS from tests.account_config import config_eth_account -from utils.contract_utils import IbetStandardTokenUtils web3 = Web3(Web3.HTTPProvider(WEB3_HTTP_PROVIDER)) web3.middleware_onion.inject(geth_poa_middleware, layer=0) @@ -59,9 +51,7 @@ def processor(db, caplog: pytest.LogCaptureFixture): LOG.setLevel(default_log_level) - class TestProcessor: - @staticmethod def set_block_number(db, block_number): indexed_block_number = IDXBlockDataBlockNumber() @@ -84,9 +74,11 @@ def test_normal_1(self, processor, db, caplog): processor.process() # Assertion - indexed_block = db.query(IDXBlockDataBlockNumber).\ - filter(IDXBlockDataBlockNumber.chain_id == str(CHAIN_ID)).\ - first() + indexed_block = ( + db.query(IDXBlockDataBlockNumber) + .filter(IDXBlockDataBlockNumber.chain_id == str(CHAIN_ID)) + .first() + ) assert indexed_block.latest_block_number == before_block_number block_data = db.query(IDXBlockData).all() @@ -95,11 +87,9 @@ def test_normal_1(self, processor, db, caplog): tx_data = db.query(IDXTxData).all() assert len(tx_data) == 0 - assert 1 == caplog.record_tuples.count(( - LOG.name, - logging.INFO, - "skip process: from_block > latest_block" - )) + assert 1 == caplog.record_tuples.count( + (LOG.name, logging.INFO, "skip process: from_block > latest_block") + ) # Normal_2 # BlockData: Empty block is generated @@ -115,9 +105,11 @@ def test_normal_2(self, processor, db, caplog): after_block_number = web3.eth.block_number # Assertion: Data - indexed_block = db.query(IDXBlockDataBlockNumber).\ - filter(IDXBlockDataBlockNumber.chain_id == str(CHAIN_ID)).\ - first() + indexed_block = ( + db.query(IDXBlockDataBlockNumber) + .filter(IDXBlockDataBlockNumber.chain_id == str(CHAIN_ID)) + .first() + ) assert indexed_block.latest_block_number == after_block_number block_data: list[IDXBlockData] = db.query(IDXBlockData).all() @@ -128,16 +120,16 @@ def test_normal_2(self, processor, db, caplog): assert len(tx_data) == 0 # Assertion: Log - assert 1 == caplog.record_tuples.count(( - LOG.name, - logging.INFO, - f"syncing from={before_block_number + 1}, to={after_block_number}" - )) - assert 1 == caplog.record_tuples.count(( - LOG.name, - logging.INFO, - "sync process has been completed" - )) + assert 1 == caplog.record_tuples.count( + ( + LOG.name, + logging.INFO, + f"syncing from={before_block_number + 1}, to={after_block_number}", + ) + ) + assert 1 == caplog.record_tuples.count( + (LOG.name, logging.INFO, "sync process has been completed") + ) # Normal_3_1 # TxData: Contract deployment @@ -145,7 +137,7 @@ def test_normal_3_1(self, processor, db, caplog): deployer = config_eth_account("user1") deployer_pk = decode_keyfile_json( raw_keyfile_json=deployer["keyfile_json"], - password="password".encode("utf-8") + password="password".encode("utf-8"), ) before_block_number = web3.eth.block_number @@ -161,8 +153,8 @@ def test_normal_3_1(self, processor, db, caplog): "totalSupply": 1000, "tradableExchange": ZERO_ADDRESS, "contactInformation": "test_contact_info", - "privacyPolicy": "test_privacy_policy" - } + "privacyPolicy": "test_privacy_policy", + }, ) # Execute batch processing @@ -170,9 +162,11 @@ def test_normal_3_1(self, processor, db, caplog): after_block_number = web3.eth.block_number # Assertion - indexed_block = db.query(IDXBlockDataBlockNumber).\ - filter(IDXBlockDataBlockNumber.chain_id == str(CHAIN_ID)).\ - first() + indexed_block = ( + db.query(IDXBlockDataBlockNumber) + .filter(IDXBlockDataBlockNumber.chain_id == str(CHAIN_ID)) + .first() + ) assert indexed_block.latest_block_number == after_block_number block_data: list[IDXBlockData] = db.query(IDXBlockData).all() @@ -194,7 +188,7 @@ def test_normal_3_2(self, processor, db, caplog): deployer = config_eth_account("user1") deployer_pk = decode_keyfile_json( raw_keyfile_json=deployer["keyfile_json"], - password="password".encode("utf-8") + password="password".encode("utf-8"), ) to_address = config_eth_account("user2")["address"] @@ -211,14 +205,14 @@ def test_normal_3_2(self, processor, db, caplog): "totalSupply": 1000, "tradableExchange": ZERO_ADDRESS, "contactInformation": "test_contact_info", - "privacyPolicy": "test_privacy_policy" - } + "privacyPolicy": "test_privacy_policy", + }, ) tx_hash = IbetStandardTokenUtils.transfer( contract_address=token_contract.address, tx_from=deployer["address"], private_key=deployer_pk, - args=[to_address, 1] + args=[to_address, 1], ) # Execute batch processing @@ -226,12 +220,16 @@ def test_normal_3_2(self, processor, db, caplog): after_block_number = web3.eth.block_number # Assertion - indexed_block = db.query(IDXBlockDataBlockNumber).\ - filter(IDXBlockDataBlockNumber.chain_id == str(CHAIN_ID)).\ - first() + indexed_block = ( + db.query(IDXBlockDataBlockNumber) + .filter(IDXBlockDataBlockNumber.chain_id == str(CHAIN_ID)) + .first() + ) assert indexed_block.latest_block_number == after_block_number - block_data: list[IDXBlockData] = db.query(IDXBlockData).order_by(IDXBlockData.number).all() + block_data: list[IDXBlockData] = ( + db.query(IDXBlockData).order_by(IDXBlockData.number).all() + ) assert len(block_data) == 2 assert block_data[0].number == before_block_number + 1 @@ -266,14 +264,18 @@ def test_error_1(self, processor, db): self.set_block_number(db, before_block_number) # Execute batch processing - with mock.patch("web3.providers.rpc.HTTPProvider.make_request", MagicMock(side_effect=ServiceUnavailableError())), \ - pytest.raises(ServiceUnavailableError): + with mock.patch( + "web3.providers.rpc.HTTPProvider.make_request", + MagicMock(side_effect=ServiceUnavailableError()), + ), pytest.raises(ServiceUnavailableError): processor.process() # Assertion - indexed_block = db.query(IDXBlockDataBlockNumber). \ - filter(IDXBlockDataBlockNumber.chain_id == str(CHAIN_ID)). \ - first() + indexed_block = ( + db.query(IDXBlockDataBlockNumber) + .filter(IDXBlockDataBlockNumber.chain_id == str(CHAIN_ID)) + .first() + ) assert indexed_block.latest_block_number == before_block_number block_data = db.query(IDXBlockData).all() @@ -291,14 +293,17 @@ def test_error_2(self, processor, db): web3.provider.make_request(RPCEndpoint("evm_mine"), []) # Execute batch processing - with mock.patch.object(Session, "commit", side_effect=SQLAlchemyError()), \ - pytest.raises(SQLAlchemyError): + with mock.patch.object( + Session, "commit", side_effect=SQLAlchemyError() + ), pytest.raises(SQLAlchemyError): processor.process() # Assertion - indexed_block = db.query(IDXBlockDataBlockNumber). \ - filter(IDXBlockDataBlockNumber.chain_id == str(CHAIN_ID)). \ - first() + indexed_block = ( + db.query(IDXBlockDataBlockNumber) + .filter(IDXBlockDataBlockNumber.chain_id == str(CHAIN_ID)) + .first() + ) assert indexed_block.latest_block_number == before_block_number block_data = db.query(IDXBlockData).all() diff --git a/tests/test_batch_indexer_e2e_messaging.py b/tests/test_batch_indexer_e2e_messaging.py index e5bd7066..09e024f6 100644 --- a/tests/test_batch_indexer_e2e_messaging.py +++ b/tests/test_batch_indexer_e2e_messaging.py @@ -16,32 +16,29 @@ SPDX-License-Identifier: Apache-2.0 """ -import pytest -import os import base64 import json +import os import time from datetime import datetime -from eth_keyfile import decode_keyfile_json +import pytest from Crypto import Random -from Crypto.Cipher import ( - AES, - PKCS1_OAEP -) +from Crypto.Cipher import AES, PKCS1_OAEP from Crypto.PublicKey import RSA from Crypto.Util.Padding import pad +from eth_keyfile import decode_keyfile_json +import batch.indexer_e2e_messaging as indexer_e2e_messaging from app.model.blockchain import E2EMessaging from app.model.db import ( E2EMessagingAccount, E2EMessagingAccountRsaKey, IDXE2EMessaging, - IDXE2EMessagingBlockNumber + IDXE2EMessagingBlockNumber, ) -from app.utils.web3_utils import Web3Wrapper from app.utils.e2ee_utils import E2EEUtils -import batch.indexer_e2e_messaging as indexer_e2e_messaging +from app.utils.web3_utils import Web3Wrapper from batch.indexer_e2e_messaging import Processor from tests.account_config import config_eth_account @@ -50,7 +47,9 @@ @pytest.fixture(scope="function") def processor(db, e2e_messaging_contract): - indexer_e2e_messaging.E2E_MESSAGING_CONTRACT_ADDRESS = e2e_messaging_contract.address + indexer_e2e_messaging.E2E_MESSAGING_CONTRACT_ADDRESS = ( + e2e_messaging_contract.address + ) return Processor() @@ -144,7 +143,9 @@ def test_normal_1(self, processor, db): processor.process() # Assertion - _e2e_messaging_list = db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + _e2e_messaging_list = ( + db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + ) assert len(_e2e_messaging_list) == 0 _idx_e2e_messaging_block_number = db.query(IDXE2EMessagingBlockNumber).first() assert _idx_e2e_messaging_block_number.id == 1 @@ -159,8 +160,7 @@ def test_normal_2_1(self, processor, db, e2e_messaging_contract): user_2 = config_eth_account("user2") user_address_2 = user_2["address"] user_private_key_2 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : E2EMessagingAccount @@ -188,7 +188,9 @@ def test_normal_2_1(self, processor, db, e2e_messaging_contract): "address": "東京都1", } message_message_str = json.dumps(message) - sending_tx_hash, sending_tx_receipt = E2EMessaging(e2e_messaging_contract.address).send_message_external( + sending_tx_hash, sending_tx_receipt = E2EMessaging( + e2e_messaging_contract.address + ).send_message_external( user_address_1, _type, message_message_str, @@ -204,7 +206,9 @@ def test_normal_2_1(self, processor, db, e2e_messaging_contract): processor.process() # Assertion - _e2e_messaging_list = db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + _e2e_messaging_list = ( + db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + ) assert len(_e2e_messaging_list) == 1 _e2e_messaging = _e2e_messaging_list[0] assert _e2e_messaging.id == 1 @@ -228,8 +232,7 @@ def test_normal_2_2(self, processor, db, e2e_messaging_contract): user_2 = config_eth_account("user2") user_address_2 = user_2["address"] user_private_key_2 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : E2EMessagingAccount @@ -275,7 +278,9 @@ def test_normal_2_2(self, processor, db, e2e_messaging_contract): "address": "東京都1", } message_message_str = json.dumps(message) - sending_tx_hash, sending_tx_receipt = E2EMessaging(e2e_messaging_contract.address).send_message_external( + sending_tx_hash, sending_tx_receipt = E2EMessaging( + e2e_messaging_contract.address + ).send_message_external( user_address_1, _type, message_message_str, @@ -313,7 +318,9 @@ def test_normal_2_2(self, processor, db, e2e_messaging_contract): processor.process() # Assertion - _e2e_messaging_list = db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + _e2e_messaging_list = ( + db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + ) assert len(_e2e_messaging_list) == 1 _e2e_messaging = _e2e_messaging_list[0] assert _e2e_messaging.id == 1 @@ -338,8 +345,7 @@ def test_normal_3(self, processor, db, e2e_messaging_contract): user_3 = config_eth_account("user3") user_address_3 = user_3["address"] user_private_key_3 = decode_keyfile_json( - raw_keyfile_json=user_3["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : E2EMessagingAccount @@ -383,7 +389,9 @@ def test_normal_3(self, processor, db, e2e_messaging_contract): "address": "東京都1", } message_message_str_1 = json.dumps(message) - sending_tx_hash_1, sending_tx_receipt = E2EMessaging(e2e_messaging_contract.address).send_message_external( + sending_tx_hash_1, sending_tx_receipt = E2EMessaging( + e2e_messaging_contract.address + ).send_message_external( user_address_1, _type_1, message_message_str_1, @@ -392,13 +400,17 @@ def test_normal_3(self, processor, db, e2e_messaging_contract): user_private_key_3, ) sending_block = web3.eth.get_block(sending_tx_receipt["blockNumber"]) - sending_block_timestamp_1 = datetime.utcfromtimestamp(sending_block["timestamp"]) + sending_block_timestamp_1 = datetime.utcfromtimestamp( + sending_block["timestamp"] + ) # Send Message(user3 -> user2) _type_2 = "test_type2" message = ["テスト太郎2", "東京都2"] message_message_str_2 = json.dumps(message) - sending_tx_hash_2, sending_tx_receipt = E2EMessaging(e2e_messaging_contract.address).send_message_external( + sending_tx_hash_2, sending_tx_receipt = E2EMessaging( + e2e_messaging_contract.address + ).send_message_external( user_address_2, _type_2, message_message_str_2, @@ -407,12 +419,16 @@ def test_normal_3(self, processor, db, e2e_messaging_contract): user_private_key_3, ) sending_block = web3.eth.get_block(sending_tx_receipt["blockNumber"]) - sending_block_timestamp_2 = datetime.utcfromtimestamp(sending_block["timestamp"]) + sending_block_timestamp_2 = datetime.utcfromtimestamp( + sending_block["timestamp"] + ) # Send Message(user3 -> user1) _type_3 = "test_type3" message_message_str_3 = "テスト太郎1,東京都1" - sending_tx_hash_3, sending_tx_receipt = E2EMessaging(e2e_messaging_contract.address).send_message_external( + sending_tx_hash_3, sending_tx_receipt = E2EMessaging( + e2e_messaging_contract.address + ).send_message_external( user_address_1, _type_3, message_message_str_3, @@ -421,12 +437,16 @@ def test_normal_3(self, processor, db, e2e_messaging_contract): user_private_key_3, ) sending_block = web3.eth.get_block(sending_tx_receipt["blockNumber"]) - sending_block_timestamp_3 = datetime.utcfromtimestamp(sending_block["timestamp"]) + sending_block_timestamp_3 = datetime.utcfromtimestamp( + sending_block["timestamp"] + ) # Send Message(user3 -> user2) _type_4 = "a" * 50 message_message_str_4 = "a" * 5000 - sending_tx_hash_4, sending_tx_receipt = E2EMessaging(e2e_messaging_contract.address).send_message_external( + sending_tx_hash_4, sending_tx_receipt = E2EMessaging( + e2e_messaging_contract.address + ).send_message_external( user_address_2, _type_4, message_message_str_4, @@ -435,14 +455,18 @@ def test_normal_3(self, processor, db, e2e_messaging_contract): user_private_key_3, ) sending_block = web3.eth.get_block(sending_tx_receipt["blockNumber"]) - sending_block_timestamp_4 = datetime.utcfromtimestamp(sending_block["timestamp"]) + sending_block_timestamp_4 = datetime.utcfromtimestamp( + sending_block["timestamp"] + ) # Run target process block_number = web3.eth.block_number processor.process() # Assertion - _e2e_messaging_list = db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + _e2e_messaging_list = ( + db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + ) assert len(_e2e_messaging_list) == 4 _e2e_messaging = _e2e_messaging_list[0] assert _e2e_messaging.id == 1 @@ -492,8 +516,7 @@ def test_normal_4(self, processor, db, e2e_messaging_contract): user_2 = config_eth_account("user2") user_address_2 = user_2["address"] user_private_key_2 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) user_3 = config_eth_account("user3") user_address_3 = user_3["address"] @@ -537,7 +560,9 @@ def test_normal_4(self, processor, db, e2e_messaging_contract): processor.process() # Assertion - _e2e_messaging_list = db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + _e2e_messaging_list = ( + db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + ) assert len(_e2e_messaging_list) == 0 _idx_e2e_messaging_block_number = db.query(IDXE2EMessagingBlockNumber).first() assert _idx_e2e_messaging_block_number.id == 1 @@ -556,8 +581,7 @@ def test_error_1_1(self, processor, db, e2e_messaging_contract): user_2 = config_eth_account("user2") user_address_2 = user_2["address"] user_private_key_2 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : E2EMessagingAccount @@ -580,15 +604,18 @@ def test_error_1_1(self, processor, db, e2e_messaging_contract): # Send Message message = "test" - E2EMessaging(e2e_messaging_contract.address).\ - send_message(user_address_1, message, user_address_2, user_private_key_2) + E2EMessaging(e2e_messaging_contract.address).send_message( + user_address_1, message, user_address_2, user_private_key_2 + ) # Run target process block_number = web3.eth.block_number processor.process() # Assertion - _e2e_messaging_list = db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + _e2e_messaging_list = ( + db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + ) assert len(_e2e_messaging_list) == 0 _idx_e2e_messaging_block_number = db.query(IDXE2EMessagingBlockNumber).first() assert _idx_e2e_messaging_block_number.id == 1 @@ -603,8 +630,7 @@ def test_error_1_2(self, processor, db, e2e_messaging_contract): user_2 = config_eth_account("user2") user_address_2 = user_2["address"] user_private_key_2 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : E2EMessagingAccount @@ -630,25 +656,32 @@ def test_error_1_2(self, processor, db, e2e_messaging_contract): aes_iv = os.urandom(16) aes_cipher = AES.new(aes_key, AES.MODE_CBC, aes_iv) pad_message = pad("test_message".encode("utf-8"), AES.block_size) - encrypted_message = base64.b64encode(aes_iv + aes_cipher.encrypt(pad_message)).decode() + encrypted_message = base64.b64encode( + aes_iv + aes_cipher.encrypt(pad_message) + ).decode() rsa_key = RSA.import_key(self.rsa_public_key) rsa_cipher = PKCS1_OAEP.new(rsa_key) cipher_key = base64.b64encode(rsa_cipher.encrypt(aes_key)).decode() - message = json.dumps({ - "text": { - "cipher_key": cipher_key, - "message": encrypted_message, + message = json.dumps( + { + "text": { + "cipher_key": cipher_key, + "message": encrypted_message, + } } - }) - E2EMessaging(e2e_messaging_contract.address).\ - send_message(user_address_1, message, user_address_2, user_private_key_2) + ) + E2EMessaging(e2e_messaging_contract.address).send_message( + user_address_1, message, user_address_2, user_private_key_2 + ) # Run target process block_number = web3.eth.block_number processor.process() # Assertion - _e2e_messaging_list = db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + _e2e_messaging_list = ( + db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + ) assert len(_e2e_messaging_list) == 0 _idx_e2e_messaging_block_number = db.query(IDXE2EMessagingBlockNumber).first() assert _idx_e2e_messaging_block_number.id == 1 @@ -663,8 +696,7 @@ def test_error_1_3(self, processor, db, e2e_messaging_contract): user_2 = config_eth_account("user2") user_address_2 = user_2["address"] user_private_key_2 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : E2EMessagingAccount @@ -686,18 +718,23 @@ def test_error_1_3(self, processor, db, e2e_messaging_contract): db.commit() # Send Message - message = json.dumps({ - "type": "test_type", - }) - E2EMessaging(e2e_messaging_contract.address).\ - send_message(user_address_1, message, user_address_2, user_private_key_2) + message = json.dumps( + { + "type": "test_type", + } + ) + E2EMessaging(e2e_messaging_contract.address).send_message( + user_address_1, message, user_address_2, user_private_key_2 + ) # Run target process block_number = web3.eth.block_number processor.process() # Assertion - _e2e_messaging_list = db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + _e2e_messaging_list = ( + db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + ) assert len(_e2e_messaging_list) == 0 _idx_e2e_messaging_block_number = db.query(IDXE2EMessagingBlockNumber).first() assert _idx_e2e_messaging_block_number.id == 1 @@ -712,8 +749,7 @@ def test_error_1_4(self, processor, db, e2e_messaging_contract): user_2 = config_eth_account("user2") user_address_2 = user_2["address"] user_private_key_2 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : E2EMessagingAccount @@ -739,26 +775,30 @@ def test_error_1_4(self, processor, db, e2e_messaging_contract): aes_iv = os.urandom(16) aes_cipher = AES.new(aes_key, AES.MODE_CBC, aes_iv) pad_message = pad("test_message".encode("utf-8"), AES.block_size) - encrypted_message = base64.b64encode(aes_iv + aes_cipher.encrypt(pad_message)).decode() + encrypted_message = base64.b64encode( + aes_iv + aes_cipher.encrypt(pad_message) + ).decode() rsa_key = RSA.import_key(self.rsa_public_key) rsa_cipher = PKCS1_OAEP.new(rsa_key) cipher_key = base64.b64encode(rsa_cipher.encrypt(aes_key)).decode() - message = json.dumps({ - "type": "a" * 51, - "text": { - "cipher_key": cipher_key, - "message": encrypted_message + message = json.dumps( + { + "type": "a" * 51, + "text": {"cipher_key": cipher_key, "message": encrypted_message}, } - }) - E2EMessaging(e2e_messaging_contract.address).\ - send_message(user_address_1, message, user_address_2, user_private_key_2) + ) + E2EMessaging(e2e_messaging_contract.address).send_message( + user_address_1, message, user_address_2, user_private_key_2 + ) # Run target process block_number = web3.eth.block_number processor.process() # Assertion - _e2e_messaging_list = db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + _e2e_messaging_list = ( + db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + ) assert len(_e2e_messaging_list) == 0 _idx_e2e_messaging_block_number = db.query(IDXE2EMessagingBlockNumber).first() assert _idx_e2e_messaging_block_number.id == 1 @@ -773,8 +813,7 @@ def test_error_1_5(self, processor, db, e2e_messaging_contract): user_2 = config_eth_account("user2") user_address_2 = user_2["address"] user_private_key_2 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : E2EMessagingAccount @@ -800,22 +839,29 @@ def test_error_1_5(self, processor, db, e2e_messaging_contract): aes_iv = os.urandom(16) aes_cipher = AES.new(aes_key, AES.MODE_CBC, aes_iv) pad_message = pad("test_message".encode("utf-8"), AES.block_size) - encrypted_message = base64.b64encode(aes_iv + aes_cipher.encrypt(pad_message)).decode() - message = json.dumps({ - "type": "test_type", - "text": { - "message": encrypted_message, + encrypted_message = base64.b64encode( + aes_iv + aes_cipher.encrypt(pad_message) + ).decode() + message = json.dumps( + { + "type": "test_type", + "text": { + "message": encrypted_message, + }, } - }) - E2EMessaging(e2e_messaging_contract.address).\ - send_message(user_address_1, message, user_address_2, user_private_key_2) + ) + E2EMessaging(e2e_messaging_contract.address).send_message( + user_address_1, message, user_address_2, user_private_key_2 + ) # Run target process block_number = web3.eth.block_number processor.process() # Assertion - _e2e_messaging_list = db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + _e2e_messaging_list = ( + db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + ) assert len(_e2e_messaging_list) == 0 _idx_e2e_messaging_block_number = db.query(IDXE2EMessagingBlockNumber).first() assert _idx_e2e_messaging_block_number.id == 1 @@ -830,8 +876,7 @@ def test_error_1_6(self, processor, db, e2e_messaging_contract): user_2 = config_eth_account("user2") user_address_2 = user_2["address"] user_private_key_2 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : E2EMessagingAccount @@ -857,21 +902,26 @@ def test_error_1_6(self, processor, db, e2e_messaging_contract): rsa_key = RSA.import_key(self.rsa_public_key) rsa_cipher = PKCS1_OAEP.new(rsa_key) cipher_key = base64.b64encode(rsa_cipher.encrypt(aes_key)).decode() - message = json.dumps({ - "type": "test_type", - "text": { - "cipher_key": cipher_key, + message = json.dumps( + { + "type": "test_type", + "text": { + "cipher_key": cipher_key, + }, } - }) - E2EMessaging(e2e_messaging_contract.address).\ - send_message(user_address_1, message, user_address_2, user_private_key_2) + ) + E2EMessaging(e2e_messaging_contract.address).send_message( + user_address_1, message, user_address_2, user_private_key_2 + ) # Run target process block_number = web3.eth.block_number processor.process() # Assertion - _e2e_messaging_list = db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + _e2e_messaging_list = ( + db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + ) assert len(_e2e_messaging_list) == 0 _idx_e2e_messaging_block_number = db.query(IDXE2EMessagingBlockNumber).first() assert _idx_e2e_messaging_block_number.id == 1 @@ -886,8 +936,7 @@ def test_error_1_7(self, processor, db, e2e_messaging_contract): user_2 = config_eth_account("user2") user_address_2 = user_2["address"] user_private_key_2 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : E2EMessagingAccount @@ -913,26 +962,30 @@ def test_error_1_7(self, processor, db, e2e_messaging_contract): aes_iv = os.urandom(16) aes_cipher = AES.new(aes_key, AES.MODE_CBC, aes_iv) pad_message = pad(("a" * 5001).encode("utf-8"), AES.block_size) - encrypted_message = base64.b64encode(aes_iv + aes_cipher.encrypt(pad_message)).decode() + encrypted_message = base64.b64encode( + aes_iv + aes_cipher.encrypt(pad_message) + ).decode() rsa_key = RSA.import_key(self.rsa_public_key) rsa_cipher = PKCS1_OAEP.new(rsa_key) cipher_key = base64.b64encode(rsa_cipher.encrypt(aes_key)).decode() - message = json.dumps({ - "type": "test_type", - "text": { - "cipher_key": cipher_key, - "message": encrypted_message + message = json.dumps( + { + "type": "test_type", + "text": {"cipher_key": cipher_key, "message": encrypted_message}, } - }) - E2EMessaging(e2e_messaging_contract.address). \ - send_message(user_address_1, message, user_address_2, user_private_key_2) + ) + E2EMessaging(e2e_messaging_contract.address).send_message( + user_address_1, message, user_address_2, user_private_key_2 + ) # Run target process block_number = web3.eth.block_number processor.process() # Assertion - _e2e_messaging_list = db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + _e2e_messaging_list = ( + db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + ) assert len(_e2e_messaging_list) == 0 _idx_e2e_messaging_block_number = db.query(IDXE2EMessagingBlockNumber).first() assert _idx_e2e_messaging_block_number.id == 1 @@ -946,8 +999,7 @@ def test_error_2(self, processor, db, e2e_messaging_contract): user_2 = config_eth_account("user2") user_address_2 = user_2["address"] user_private_key_2 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : E2EMessagingAccount @@ -979,7 +1031,9 @@ def test_error_2(self, processor, db, e2e_messaging_contract): _e2e_account_rsa_key.rsa_private_key = self.rsa_private_key _e2e_account_rsa_key.rsa_public_key = self.rsa_public_key _e2e_account_rsa_key.rsa_passphrase = E2EEUtils.encrypt(self.rsa_passphrase) - _e2e_account_rsa_key.block_timestamp = datetime.utcnow() # Registry after send message + _e2e_account_rsa_key.block_timestamp = ( + datetime.utcnow() + ) # Registry after send message db.add(_e2e_account_rsa_key) db.commit() @@ -989,7 +1043,9 @@ def test_error_2(self, processor, db, e2e_messaging_contract): processor.process() # Assertion - _e2e_messaging_list = db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + _e2e_messaging_list = ( + db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + ) assert len(_e2e_messaging_list) == 0 _idx_e2e_messaging_block_number = db.query(IDXE2EMessagingBlockNumber).first() assert _idx_e2e_messaging_block_number.id == 1 @@ -1004,8 +1060,7 @@ def test_error_3_1(self, processor, db, e2e_messaging_contract): user_2 = config_eth_account("user2") user_address_2 = user_2["address"] user_private_key_2 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : E2EMessagingAccount @@ -1031,23 +1086,27 @@ def test_error_3_1(self, processor, db, e2e_messaging_contract): aes_iv = os.urandom(16) aes_cipher = AES.new(aes_key, AES.MODE_CBC, aes_iv) pad_message = pad("test_message".encode("utf-8"), AES.block_size) - encrypted_message = base64.b64encode(aes_iv + aes_cipher.encrypt(pad_message)).decode() - message = json.dumps({ - "type": "test_type", - "text": { - "cipher_key": "cipher_key", - "message": encrypted_message + encrypted_message = base64.b64encode( + aes_iv + aes_cipher.encrypt(pad_message) + ).decode() + message = json.dumps( + { + "type": "test_type", + "text": {"cipher_key": "cipher_key", "message": encrypted_message}, } - }) - E2EMessaging(e2e_messaging_contract.address). \ - send_message(user_address_1, message, user_address_2, user_private_key_2) + ) + E2EMessaging(e2e_messaging_contract.address).send_message( + user_address_1, message, user_address_2, user_private_key_2 + ) # Run target process block_number = web3.eth.block_number processor.process() # Assertion - _e2e_messaging_list = db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + _e2e_messaging_list = ( + db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + ) assert len(_e2e_messaging_list) == 0 _idx_e2e_messaging_block_number = db.query(IDXE2EMessagingBlockNumber).first() assert _idx_e2e_messaging_block_number.id == 1 @@ -1062,8 +1121,7 @@ def test_error_3_2(self, processor, db, e2e_messaging_contract): user_2 = config_eth_account("user2") user_address_2 = user_2["address"] user_private_key_2 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : E2EMessagingAccount @@ -1089,24 +1147,28 @@ def test_error_3_2(self, processor, db, e2e_messaging_contract): aes_iv = os.urandom(16) aes_cipher = AES.new(aes_key, AES.MODE_CBC, aes_iv) pad_message = pad("test_message".encode("utf-8"), AES.block_size) - encrypted_message = base64.b64encode(aes_iv + aes_cipher.encrypt(pad_message)).decode() + encrypted_message = base64.b64encode( + aes_iv + aes_cipher.encrypt(pad_message) + ).decode() cipher_key = base64.b64encode(aes_key).decode() - message = json.dumps({ - "type": "test_type", - "text": { - "cipher_key": cipher_key, - "message": encrypted_message + message = json.dumps( + { + "type": "test_type", + "text": {"cipher_key": cipher_key, "message": encrypted_message}, } - }) - E2EMessaging(e2e_messaging_contract.address). \ - send_message(user_address_1, message, user_address_2, user_private_key_2) + ) + E2EMessaging(e2e_messaging_contract.address).send_message( + user_address_1, message, user_address_2, user_private_key_2 + ) # Run target process block_number = web3.eth.block_number processor.process() # Assertion - _e2e_messaging_list = db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + _e2e_messaging_list = ( + db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + ) assert len(_e2e_messaging_list) == 0 _idx_e2e_messaging_block_number = db.query(IDXE2EMessagingBlockNumber).first() assert _idx_e2e_messaging_block_number.id == 1 @@ -1121,8 +1183,7 @@ def test_error_3_3(self, processor, db, e2e_messaging_contract): user_2 = config_eth_account("user2") user_address_2 = user_2["address"] user_private_key_2 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : E2EMessagingAccount @@ -1151,26 +1212,30 @@ def test_error_3_3(self, processor, db, e2e_messaging_contract): aes_iv = os.urandom(16) aes_cipher = AES.new(aes_key, AES.MODE_CBC, aes_iv) pad_message = pad("test_message".encode("utf-8"), AES.block_size) - encrypted_message = base64.b64encode(aes_iv + aes_cipher.encrypt(pad_message)).decode() + encrypted_message = base64.b64encode( + aes_iv + aes_cipher.encrypt(pad_message) + ).decode() rsa_key = RSA.import_key(other_rsa_public_key) rsa_cipher = PKCS1_OAEP.new(rsa_key) cipher_key = base64.b64encode(rsa_cipher.encrypt(aes_key)).decode() - message = json.dumps({ - "type": "test_type", - "text": { - "cipher_key": cipher_key, - "message": encrypted_message + message = json.dumps( + { + "type": "test_type", + "text": {"cipher_key": cipher_key, "message": encrypted_message}, } - }) - E2EMessaging(e2e_messaging_contract.address). \ - send_message(user_address_1, message, user_address_2, user_private_key_2) + ) + E2EMessaging(e2e_messaging_contract.address).send_message( + user_address_1, message, user_address_2, user_private_key_2 + ) # Run target process block_number = web3.eth.block_number processor.process() # Assertion - _e2e_messaging_list = db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + _e2e_messaging_list = ( + db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + ) assert len(_e2e_messaging_list) == 0 _idx_e2e_messaging_block_number = db.query(IDXE2EMessagingBlockNumber).first() assert _idx_e2e_messaging_block_number.id == 1 @@ -1185,8 +1250,7 @@ def test_error_3_4(self, processor, db, e2e_messaging_contract): user_2 = config_eth_account("user2") user_address_2 = user_2["address"] user_private_key_2 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : E2EMessagingAccount @@ -1212,22 +1276,24 @@ def test_error_3_4(self, processor, db, e2e_messaging_contract): rsa_key = RSA.import_key(self.rsa_public_key) rsa_cipher = PKCS1_OAEP.new(rsa_key) cipher_key = base64.b64encode(rsa_cipher.encrypt(aes_key)).decode() - message = json.dumps({ - "type": "test_type", - "text": { - "cipher_key": cipher_key, - "message": "test_message" + message = json.dumps( + { + "type": "test_type", + "text": {"cipher_key": cipher_key, "message": "test_message"}, } - }) - E2EMessaging(e2e_messaging_contract.address). \ - send_message(user_address_1, message, user_address_2, user_private_key_2) + ) + E2EMessaging(e2e_messaging_contract.address).send_message( + user_address_1, message, user_address_2, user_private_key_2 + ) # Run target process block_number = web3.eth.block_number processor.process() # Assertion - _e2e_messaging_list = db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + _e2e_messaging_list = ( + db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + ) assert len(_e2e_messaging_list) == 0 _idx_e2e_messaging_block_number = db.query(IDXE2EMessagingBlockNumber).first() assert _idx_e2e_messaging_block_number.id == 1 @@ -1242,8 +1308,7 @@ def test_error_3_5(self, processor, db, e2e_messaging_contract): user_2 = config_eth_account("user2") user_address_2 = user_2["address"] user_private_key_2 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : E2EMessagingAccount @@ -1269,27 +1334,31 @@ def test_error_3_5(self, processor, db, e2e_messaging_contract): aes_iv = os.urandom(16) aes_cipher = AES.new(aes_key, AES.MODE_CBC, aes_iv) pad_message = pad("test_message".encode("utf-8"), AES.block_size) - encrypted_message = base64.b64encode(aes_iv + aes_cipher.encrypt(pad_message)).decode() + encrypted_message = base64.b64encode( + aes_iv + aes_cipher.encrypt(pad_message) + ).decode() rsa_key = RSA.import_key(self.rsa_public_key) rsa_cipher = PKCS1_OAEP.new(rsa_key) other_aes_key = os.urandom(32) cipher_key = base64.b64encode(rsa_cipher.encrypt(other_aes_key)).decode() - message = json.dumps({ - "type": "test_type", - "text": { - "cipher_key": cipher_key, - "message": encrypted_message + message = json.dumps( + { + "type": "test_type", + "text": {"cipher_key": cipher_key, "message": encrypted_message}, } - }) - E2EMessaging(e2e_messaging_contract.address). \ - send_message(user_address_1, message, user_address_2, user_private_key_2) + ) + E2EMessaging(e2e_messaging_contract.address).send_message( + user_address_1, message, user_address_2, user_private_key_2 + ) # Run target process block_number = web3.eth.block_number processor.process() # Assertion - _e2e_messaging_list = db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + _e2e_messaging_list = ( + db.query(IDXE2EMessaging).order_by(IDXE2EMessaging.block_timestamp).all() + ) assert len(_e2e_messaging_list) == 0 _idx_e2e_messaging_block_number = db.query(IDXE2EMessagingBlockNumber).first() assert _idx_e2e_messaging_block_number.id == 1 diff --git a/tests/test_batch_indexer_issue_redeem.py b/tests/test_batch_indexer_issue_redeem.py index 3b5e507a..7b6599a3 100644 --- a/tests/test_batch_indexer_issue_redeem.py +++ b/tests/test_batch_indexer_issue_redeem.py @@ -16,34 +16,38 @@ SPDX-License-Identifier: Apache-2.0 """ -from datetime import datetime -from eth_keyfile import decode_keyfile_json import logging +from datetime import datetime +from unittest import mock +from unittest.mock import patch + import pytest +from eth_keyfile import decode_keyfile_json from sqlalchemy.exc import InvalidRequestError from sqlalchemy.orm import Session -from unittest import mock -from unittest.mock import patch import config from app.exceptions import ServiceUnavailableError +from app.model.blockchain import IbetShareContract, IbetStraightBondContract +from app.model.blockchain.tx_params.ibet_share import ( + UpdateParams as IbetShareUpdateParams, +) +from app.model.blockchain.tx_params.ibet_straight_bond import ( + UpdateParams as IbetStraightBondUpdateParams, +) from app.model.db import ( - Token, - TokenType, IDXIssueRedeem, + IDXIssueRedeemBlockNumber, IDXIssueRedeemEventType, - IDXIssueRedeemBlockNumber + Token, + TokenType, ) -from app.model.blockchain import IbetStraightBondContract, IbetShareContract -from app.model.blockchain.tx_params.ibet_straight_bond import UpdateParams as IbetStraightBondUpdateParams -from app.model.blockchain.tx_params.ibet_share import UpdateParams as IbetShareUpdateParams -from app.utils.web3_utils import Web3Wrapper from app.utils.contract_utils import ContractUtils -from batch.indexer_issue_redeem import Processor, LOG, main +from app.utils.web3_utils import Web3Wrapper +from batch.indexer_issue_redeem import LOG, Processor, main from config import CHAIN_ID, TX_GAS_LIMIT from tests.account_config import config_eth_account - web3 = Web3Wrapper() @@ -69,11 +73,13 @@ def processor(db, caplog: pytest.LogCaptureFixture): LOG.setLevel(default_log_level) -def deploy_bond_token_contract(address, - private_key, - personal_info_contract_address, - tradable_exchange_contract_address=None, - transfer_approval_required=None): +def deploy_bond_token_contract( + address, + private_key, + personal_info_contract_address, + tradable_exchange_contract_address=None, + transfer_approval_required=None, +): arguments = [ "token.name", "token.symbol", @@ -83,7 +89,7 @@ def deploy_bond_token_contract(address, 30, "token.return_date", "token.return_amount", - "token.purpose" + "token.purpose", ] bond_contrat = IbetStraightBondContract() token_address, _, _ = bond_contrat.create(arguments, address, private_key) @@ -92,20 +98,22 @@ def deploy_bond_token_contract(address, transferable=True, personal_info_contract_address=personal_info_contract_address, tradable_exchange_contract_address=tradable_exchange_contract_address, - transfer_approval_required=transfer_approval_required + transfer_approval_required=transfer_approval_required, ), tx_from=address, - private_key=private_key + private_key=private_key, ) return ContractUtils.get_contract("IbetStraightBond", token_address) -def deploy_share_token_contract(address, - private_key, - personal_info_contract_address, - tradable_exchange_contract_address=None, - transfer_approval_required=None): +def deploy_share_token_contract( + address, + private_key, + personal_info_contract_address, + tradable_exchange_contract_address=None, + transfer_approval_required=None, +): arguments = [ "token.name", "token.symbol", @@ -115,7 +123,7 @@ def deploy_share_token_contract(address, "token.dividend_record_date", "token.dividend_payment_date", "token.cancellation_date", - 30 + 30, ] share_contract = IbetShareContract() token_address, _, _ = share_contract.create(arguments, address, private_key) @@ -124,17 +132,16 @@ def deploy_share_token_contract(address, transferable=True, personal_info_contract_address=personal_info_contract_address, tradable_exchange_contract_address=tradable_exchange_contract_address, - transfer_approval_required=transfer_approval_required + transfer_approval_required=transfer_approval_required, ), tx_from=address, - private_key=private_key + private_key=private_key, ) return ContractUtils.get_contract("IbetShare", token_address) class TestProcessor: - ########################################################################### # Normal Case ########################################################################### @@ -174,15 +181,14 @@ def test_normal_2(self, processor, db, personal_info_contract): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token token_contract_1 = deploy_bond_token_contract( address=issuer_address, private_key=issuer_private_key, - personal_info_contract_address=personal_info_contract.address + personal_info_contract_address=personal_info_contract.address, ) token_address_1 = token_contract_1.address @@ -215,15 +221,14 @@ def test_normal_3_1(self, processor, db, personal_info_contract): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token token_contract_1 = deploy_bond_token_contract( address=issuer_address, private_key=issuer_private_key, - personal_info_contract_address=personal_info_contract.address + personal_info_contract_address=personal_info_contract.address, ) token_address_1 = token_contract_1.address @@ -239,15 +244,15 @@ def test_normal_3_1(self, processor, db, personal_info_contract): # issueFrom tx = token_contract_1.functions.issueFrom( - issuer_address, - config.ZERO_ADDRESS, - 40 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + issuer_address, config.ZERO_ADDRESS, 40 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) tx_hash_1, tx_receipt_1 = ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -279,15 +284,14 @@ def test_normal_3_2(self, processor, db, personal_info_contract): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token token_contract_1 = deploy_share_token_contract( address=issuer_address, private_key=issuer_private_key, - personal_info_contract_address=personal_info_contract.address + personal_info_contract_address=personal_info_contract.address, ) token_address_1 = token_contract_1.address @@ -303,15 +307,15 @@ def test_normal_3_2(self, processor, db, personal_info_contract): # issueFrom tx = token_contract_1.functions.issueFrom( - issuer_address, - config.ZERO_ADDRESS, - 40 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + issuer_address, config.ZERO_ADDRESS, 40 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) tx_hash_1, tx_receipt_1 = ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -343,15 +347,14 @@ def test_normal_4_1(self, processor, db, personal_info_contract): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token token_contract_1 = deploy_bond_token_contract( address=issuer_address, private_key=issuer_private_key, - personal_info_contract_address=personal_info_contract.address + personal_info_contract_address=personal_info_contract.address, ) token_address_1 = token_contract_1.address @@ -367,15 +370,15 @@ def test_normal_4_1(self, processor, db, personal_info_contract): # redeemFrom tx = token_contract_1.functions.redeemFrom( - issuer_address, - config.ZERO_ADDRESS, - 10 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + issuer_address, config.ZERO_ADDRESS, 10 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) tx_hash_1, tx_receipt_1 = ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -407,15 +410,14 @@ def test_normal_4_2(self, processor, db, personal_info_contract): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token token_contract_1 = deploy_share_token_contract( address=issuer_address, private_key=issuer_private_key, - personal_info_contract_address=personal_info_contract.address + personal_info_contract_address=personal_info_contract.address, ) token_address_1 = token_contract_1.address @@ -431,15 +433,15 @@ def test_normal_4_2(self, processor, db, personal_info_contract): # redeemFrom tx = token_contract_1.functions.redeemFrom( - issuer_address, - config.ZERO_ADDRESS, - 10 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + issuer_address, config.ZERO_ADDRESS, 10 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) tx_hash_1, tx_receipt_1 = ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -470,15 +472,14 @@ def test_normal_5(self, processor, db, personal_info_contract): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token token_contract_1 = deploy_bond_token_contract( address=issuer_address, private_key=issuer_private_key, - personal_info_contract_address=personal_info_contract.address + personal_info_contract_address=personal_info_contract.address, ) token_address_1 = token_contract_1.address @@ -494,27 +495,27 @@ def test_normal_5(self, processor, db, personal_info_contract): # issueFrom * 2 tx = token_contract_1.functions.issueFrom( - issuer_address, - config.ZERO_ADDRESS, - 10 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + issuer_address, config.ZERO_ADDRESS, 10 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) tx_hash_1, tx_receipt_1 = ContractUtils.send_transaction(tx, issuer_private_key) tx = token_contract_1.functions.issueFrom( - issuer_address, - config.ZERO_ADDRESS, - 20 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + issuer_address, config.ZERO_ADDRESS, 20 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) tx_hash_2, tx_receipt_2 = ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -553,19 +554,24 @@ def test_normal_5(self, processor, db, personal_info_contract): # Normal_6 # If DB session fails in phase sinking each event, batch outputs logs exception occurred. - def test_normal_6(self, processor: Processor, db: Session, personal_info_contract, caplog: pytest.LogCaptureFixture): + def test_normal_6( + self, + processor: Processor, + db: Session, + personal_info_contract, + caplog: pytest.LogCaptureFixture, + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token token_contract_1 = deploy_bond_token_contract( address=issuer_address, private_key=issuer_private_key, - personal_info_contract_address=personal_info_contract.address + personal_info_contract_address=personal_info_contract.address, ) token_address_1 = token_contract_1.address @@ -581,31 +587,35 @@ def test_normal_6(self, processor: Processor, db: Session, personal_info_contrac # issueFrom tx = token_contract_1.functions.issueFrom( - issuer_address, - config.ZERO_ADDRESS, - 10 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + issuer_address, config.ZERO_ADDRESS, 10 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) with patch.object(Session, "add", side_effect=Exception()): processor.sync_new_logs() - assert 1 == caplog.record_tuples.count(( - LOG.name, - logging.ERROR, - "An exception occurred during event synchronization" - )) + assert 1 == caplog.record_tuples.count( + ( + LOG.name, + logging.ERROR, + "An exception occurred during event synchronization", + ) + ) # Normal_7 # If block number processed in batch is equal or greater than current block number, # batch logs "skip process". @mock.patch("web3.eth.Eth.block_number", 100) - def test_normal_7(self, processor: Processor, db: Session, caplog: pytest.LogCaptureFixture): + def test_normal_7( + self, processor: Processor, db: Session, caplog: pytest.LogCaptureFixture + ): _idx_position_bond_block_number = IDXIssueRedeemBlockNumber() _idx_position_bond_block_number.id = 1 _idx_position_bond_block_number.latest_block_number = 1000 @@ -613,7 +623,9 @@ def test_normal_7(self, processor: Processor, db: Session, caplog: pytest.LogCap db.commit() processor.sync_new_logs() - assert 1 == caplog.record_tuples.count((LOG.name, logging.DEBUG, "skip process")) + assert 1 == caplog.record_tuples.count( + (LOG.name, logging.DEBUG, "skip process") + ) # Normal_8 # Newly tokens added @@ -621,15 +633,14 @@ def test_normal_8(self, processor: Processor, db: Session, personal_info_contrac user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token token_contract_1 = deploy_bond_token_contract( address=issuer_address, private_key=issuer_private_key, - personal_info_contract_address=personal_info_contract.address + personal_info_contract_address=personal_info_contract.address, ) token_address_1 = token_contract_1.address @@ -653,7 +664,7 @@ def test_normal_8(self, processor: Processor, db: Session, personal_info_contrac token_contract_2 = deploy_share_token_contract( address=issuer_address, private_key=issuer_private_key, - personal_info_contract_address=personal_info_contract.address + personal_info_contract_address=personal_info_contract.address, ) token_address_2 = token_contract_2.address @@ -680,19 +691,24 @@ def test_normal_8(self, processor: Processor, db: Session, personal_info_contrac # Error_1 # If each error occurs, batch will output logs and continue next sync. - def test_error_1(self, main_func, db: Session, personal_info_contract, caplog: pytest.LogCaptureFixture): + def test_error_1( + self, + main_func, + db: Session, + personal_info_contract, + caplog: pytest.LogCaptureFixture, + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token token_contract_1 = deploy_bond_token_contract( address=issuer_address, private_key=issuer_private_key, - personal_info_contract_address=personal_info_contract.address + personal_info_contract_address=personal_info_contract.address, ) token_address_1 = token_contract_1.address @@ -707,17 +723,27 @@ def test_error_1(self, main_func, db: Session, personal_info_contract, caplog: p db.commit() # Run mainloop once and fail with web3 utils error - with patch("batch.indexer_issue_redeem.INDEXER_SYNC_INTERVAL", None),\ - patch.object(web3.eth, "contract", side_effect=ServiceUnavailableError()), \ - pytest.raises(TypeError): + with patch( + "batch.indexer_issue_redeem.INDEXER_SYNC_INTERVAL", None + ), patch.object( + web3.eth, "contract", side_effect=ServiceUnavailableError() + ), pytest.raises( + TypeError + ): main_func() - assert 1 == caplog.record_tuples.count((LOG.name, logging.WARNING, "An external service was unavailable")) + assert 1 == caplog.record_tuples.count( + (LOG.name, logging.WARNING, "An external service was unavailable") + ) caplog.clear() # Run mainloop once and fail with sqlalchemy InvalidRequestError - with patch("batch.indexer_issue_redeem.INDEXER_SYNC_INTERVAL", None),\ - patch.object(Session, "query", side_effect=InvalidRequestError()), \ - pytest.raises(TypeError): + with patch( + "batch.indexer_issue_redeem.INDEXER_SYNC_INTERVAL", None + ), patch.object( + Session, "query", side_effect=InvalidRequestError() + ), pytest.raises( + TypeError + ): main_func() assert 1 == caplog.text.count("A database error has occurred") caplog.clear() diff --git a/tests/test_batch_indexer_personal_info.py b/tests/test_batch_indexer_personal_info.py index 90f2e252..dc31684c 100644 --- a/tests/test_batch_indexer_personal_info.py +++ b/tests/test_batch_indexer_personal_info.py @@ -16,41 +16,39 @@ SPDX-License-Identifier: Apache-2.0 """ +import base64 +import json import logging from unittest import mock from unittest.mock import patch -import pytest -import base64 -import json -from eth_keyfile import decode_keyfile_json +import pytest from Crypto.Cipher import PKCS1_OAEP from Crypto.PublicKey import RSA +from eth_keyfile import decode_keyfile_json from sqlalchemy.exc import InvalidRequestError from sqlalchemy.orm import Session -from app.exceptions import ServiceUnavailableError -from config import ( - CHAIN_ID, - TX_GAS_LIMIT +from app.exceptions import ServiceUnavailableError +from app.model.blockchain import IbetShareContract, IbetStraightBondContract +from app.model.blockchain.tx_params.ibet_share import ( + UpdateParams as IbetShareUpdateParams, +) +from app.model.blockchain.tx_params.ibet_straight_bond import ( + UpdateParams as IbetStraightBondUpdateParams, ) from app.model.db import ( - Token, - TokenType, + Account, IDXPersonalInfo, IDXPersonalInfoBlockNumber, - Account -) -from app.model.blockchain import ( - IbetStraightBondContract, - IbetShareContract + Token, + TokenType, ) -from app.model.blockchain.tx_params.ibet_straight_bond import UpdateParams as IbetStraightBondUpdateParams -from app.model.blockchain.tx_params.ibet_share import UpdateParams as IbetShareUpdateParams -from app.utils.web3_utils import Web3Wrapper from app.utils.contract_utils import ContractUtils from app.utils.e2ee_utils import E2EEUtils -from batch.indexer_personal_info import Processor, LOG, main +from app.utils.web3_utils import Web3Wrapper +from batch.indexer_personal_info import LOG, Processor, main +from config import CHAIN_ID, TX_GAS_LIMIT from tests.account_config import config_eth_account web3 = Web3Wrapper() @@ -78,11 +76,13 @@ def processor(db, caplog: pytest.LogCaptureFixture): LOG.setLevel(default_log_level) -def deploy_bond_token_contract(address, - private_key, - personal_info_contract_address, - tradable_exchange_contract_address=None, - transfer_approval_required=None): +def deploy_bond_token_contract( + address, + private_key, + personal_info_contract_address, + tradable_exchange_contract_address=None, + transfer_approval_required=None, +): arguments = [ "token.name", "token.symbol", @@ -92,7 +92,7 @@ def deploy_bond_token_contract(address, 30, "token.return_date", "token.return_amount", - "token.purpose" + "token.purpose", ] bond_contrat = IbetStraightBondContract() token_address, _, _ = bond_contrat.create(arguments, address, private_key) @@ -101,20 +101,22 @@ def deploy_bond_token_contract(address, transferable=True, personal_info_contract_address=personal_info_contract_address, tradable_exchange_contract_address=tradable_exchange_contract_address, - transfer_approval_required=transfer_approval_required + transfer_approval_required=transfer_approval_required, ), tx_from=address, - private_key=private_key + private_key=private_key, ) return ContractUtils.get_contract("IbetStraightBond", token_address) -def deploy_share_token_contract(address, - private_key, - personal_info_contract_address, - tradable_exchange_contract_address=None, - transfer_approval_required=None): +def deploy_share_token_contract( + address, + private_key, + personal_info_contract_address, + tradable_exchange_contract_address=None, + transfer_approval_required=None, +): arguments = [ "token.name", "token.symbol", @@ -124,7 +126,7 @@ def deploy_share_token_contract(address, "token.dividend_record_date", "token.dividend_payment_date", "token.cancellation_date", - 30 + 30, ] share_contract = IbetShareContract() token_address, _, _ = share_contract.create(arguments, address, private_key) @@ -133,10 +135,10 @@ def deploy_share_token_contract(address, transferable=True, personal_info_contract_address=personal_info_contract_address, tradable_exchange_contract_address=tradable_exchange_contract_address, - transfer_approval_required=transfer_approval_required + transfer_approval_required=transfer_approval_required, ), tx_from=address, - private_key=private_key + private_key=private_key, ) return ContractUtils.get_contract("IbetShare", token_address) @@ -145,12 +147,13 @@ def deploy_share_token_contract(address, def encrypt_personal_info(personal_info, rsa_public_key, passphrase): rsa_key = RSA.importKey(rsa_public_key, passphrase=passphrase) cipher = PKCS1_OAEP.new(rsa_key) - ciphertext = base64.encodebytes(cipher.encrypt(json.dumps(personal_info).encode('utf-8'))) + ciphertext = base64.encodebytes( + cipher.encrypt(json.dumps(personal_info).encode("utf-8")) + ) return ciphertext class TestProcessor: - ########################################################################### # Normal Case ########################################################################### @@ -203,8 +206,7 @@ def test_normal_1_2(self, processor, db, personal_info_contract): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) issuer_rsa_private_key = user_1["rsa_private_key"] issuer_rsa_public_key = user_1["rsa_public_key"] @@ -220,9 +222,9 @@ def test_normal_1_2(self, processor, db, personal_info_contract): db.add(account) # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_bond_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -268,8 +270,7 @@ def test_normal_2_1(self, processor, db, personal_info_contract): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) issuer_rsa_private_key = user_1["rsa_private_key"] issuer_rsa_public_key = user_1["rsa_public_key"] @@ -277,8 +278,7 @@ def test_normal_2_1(self, processor, db, personal_info_contract): user_2 = config_eth_account("user2") user_address_1 = user_2["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Account @@ -291,9 +291,9 @@ def test_normal_2_1(self, processor, db, personal_info_contract): db.add(account) # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_bond_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -324,15 +324,21 @@ def test_normal_2_1(self, processor, db, personal_info_contract): "email": "email_test1", "birth": "birth_test1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } - ciphertext = encrypt_personal_info(personal_info_1, issuer_rsa_public_key, issuer_rsa_passphrase) - tx = personal_info_contract.functions.register(issuer_address, ciphertext).build_transaction({ - "chainId": CHAIN_ID, - "from": user_address_1, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ciphertext = encrypt_personal_info( + personal_info_1, issuer_rsa_public_key, issuer_rsa_passphrase + ) + tx = personal_info_contract.functions.register( + issuer_address, ciphertext + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": user_address_1, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, user_private_key_1) # Run target process @@ -359,8 +365,7 @@ def test_normal_2_2(self, processor, db, personal_info_contract): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) issuer_rsa_private_key = user_1["rsa_private_key"] issuer_rsa_public_key = user_1["rsa_public_key"] @@ -368,8 +373,7 @@ def test_normal_2_2(self, processor, db, personal_info_contract): user_2 = config_eth_account("user2") user_address_1 = user_2["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Account @@ -382,9 +386,9 @@ def test_normal_2_2(self, processor, db, personal_info_contract): db.add(account) # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_bond_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -415,15 +419,21 @@ def test_normal_2_2(self, processor, db, personal_info_contract): "email": "email_test1", "birth": "birth_test1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } - ciphertext = encrypt_personal_info(personal_info_1, issuer_rsa_public_key, issuer_rsa_passphrase) - tx = personal_info_contract.functions.register(issuer_address, ciphertext).build_transaction({ - "chainId": CHAIN_ID, - "from": user_address_1, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ciphertext = encrypt_personal_info( + personal_info_1, issuer_rsa_public_key, issuer_rsa_passphrase + ) + tx = personal_info_contract.functions.register( + issuer_address, ciphertext + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": user_address_1, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, user_private_key_1) # Before run(consume accumulated events) @@ -445,15 +455,21 @@ def test_normal_2_2(self, processor, db, personal_info_contract): "email": "email_test2", "birth": "birth_test2", "is_corporate": True, - "tax_category": 20 + "tax_category": 20, } - ciphertext = encrypt_personal_info(personal_info_2, issuer_rsa_public_key, issuer_rsa_passphrase) - tx = personal_info_contract.functions.modify(user_address_1, ciphertext).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ciphertext = encrypt_personal_info( + personal_info_2, issuer_rsa_public_key, issuer_rsa_passphrase + ) + tx = personal_info_contract.functions.modify( + user_address_1, ciphertext + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -484,8 +500,7 @@ def test_normal_3(self, processor, db, personal_info_contract): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) issuer_rsa_private_key = user_1["rsa_private_key"] issuer_rsa_public_key = user_1["rsa_public_key"] @@ -493,8 +508,7 @@ def test_normal_3(self, processor, db, personal_info_contract): user_2 = config_eth_account("user2") user_address_1 = user_2["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Account @@ -507,9 +521,9 @@ def test_normal_3(self, processor, db, personal_info_contract): db.add(account) # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_bond_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -540,15 +554,21 @@ def test_normal_3(self, processor, db, personal_info_contract): "email": "email_test1", "birth": "birth_test1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } - ciphertext = encrypt_personal_info(personal_info_1, issuer_rsa_public_key, issuer_rsa_passphrase) - tx = personal_info_contract.functions.register(issuer_address, ciphertext).build_transaction({ - "chainId": CHAIN_ID, - "from": user_address_1, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ciphertext = encrypt_personal_info( + personal_info_1, issuer_rsa_public_key, issuer_rsa_passphrase + ) + tx = personal_info_contract.functions.register( + issuer_address, ciphertext + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": user_address_1, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, user_private_key_1) # Before run(consume accumulated events) @@ -570,15 +590,21 @@ def test_normal_3(self, processor, db, personal_info_contract): "email": "email_test2", "birth": "birth_test2", "is_corporate": True, - "tax_category": 20 + "tax_category": 20, } - ciphertext = encrypt_personal_info(personal_info_2, issuer_rsa_public_key, issuer_rsa_passphrase) - tx = personal_info_contract.functions.modify(user_address_1, ciphertext).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ciphertext = encrypt_personal_info( + personal_info_2, issuer_rsa_public_key, issuer_rsa_passphrase + ) + tx = personal_info_contract.functions.modify( + user_address_1, ciphertext + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -610,15 +636,21 @@ def test_normal_3(self, processor, db, personal_info_contract): "email": "email_test3", "birth": "birth_test3", "is_corporate": False, - "tax_category": 30 + "tax_category": 30, } - ciphertext = encrypt_personal_info(personal_info_3, issuer_rsa_public_key, issuer_rsa_passphrase) - tx = personal_info_contract.functions.modify(user_address_1, ciphertext).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ciphertext = encrypt_personal_info( + personal_info_3, issuer_rsa_public_key, issuer_rsa_passphrase + ) + tx = personal_info_contract.functions.modify( + user_address_1, ciphertext + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -647,8 +679,7 @@ def test_normal_4(self, processor, db): user_1 = config_eth_account("user1") issuer_address_1 = user_1["address"] issuer_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) issuer_rsa_private_key_1 = user_1["rsa_private_key"] issuer_rsa_public_key_1 = user_1["rsa_public_key"] @@ -657,8 +688,7 @@ def test_normal_4(self, processor, db): user_2 = config_eth_account("user2") issuer_address_2 = user_2["address"] issuer_private_key_2 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) issuer_rsa_private_key_2 = user_2["rsa_private_key"] issuer_rsa_passphrase_2 = "password" @@ -683,10 +713,18 @@ def test_normal_4(self, processor, db): db.add(account) # Deploy personal info contract - contract_address_1, _, _ = ContractUtils.deploy_contract("PersonalInfo", [], issuer_address_1, issuer_private_key_1) - personal_info_contract_1 = ContractUtils.get_contract("PersonalInfo", contract_address_1) - contract_address_2, _, _ = ContractUtils.deploy_contract("PersonalInfo", [], issuer_address_2, issuer_private_key_2) - personal_info_contract_2 = ContractUtils.get_contract("PersonalInfo", contract_address_2) + contract_address_1, _, _ = ContractUtils.deploy_contract( + "PersonalInfo", [], issuer_address_1, issuer_private_key_1 + ) + personal_info_contract_1 = ContractUtils.get_contract( + "PersonalInfo", contract_address_1 + ) + contract_address_2, _, _ = ContractUtils.deploy_contract( + "PersonalInfo", [], issuer_address_2, issuer_private_key_2 + ) + personal_info_contract_2 = ContractUtils.get_contract( + "PersonalInfo", contract_address_2 + ) # Issuer1 issues bond token. token_contract1 = deploy_bond_token_contract( @@ -731,15 +769,21 @@ def test_normal_4(self, processor, db): "email": "email_test1", "birth": "birth_test1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } - ciphertext = encrypt_personal_info(personal_info_1, issuer_rsa_public_key_1, issuer_rsa_passphrase_1) - tx = personal_info_contract_1.functions.register(issuer_address_1, ciphertext).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address_1, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ciphertext = encrypt_personal_info( + personal_info_1, issuer_rsa_public_key_1, issuer_rsa_passphrase_1 + ) + tx = personal_info_contract_1.functions.register( + issuer_address_1, ciphertext + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address_1, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key_1) personal_info_2 = { @@ -750,15 +794,21 @@ def test_normal_4(self, processor, db): "email": "email_test2", "birth": "birth_test2", "is_corporate": True, - "tax_category": 20 + "tax_category": 20, } - ciphertext = encrypt_personal_info(personal_info_2, issuer_rsa_public_key_2, issuer_rsa_passphrase_2) - tx = personal_info_contract_2.functions.register(issuer_address_2, ciphertext).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address_2, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ciphertext = encrypt_personal_info( + personal_info_2, issuer_rsa_public_key_2, issuer_rsa_passphrase_2 + ) + tx = personal_info_contract_2.functions.register( + issuer_address_2, ciphertext + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address_2, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key_2) # Run target process @@ -767,8 +817,14 @@ def test_normal_4(self, processor, db): # Prepare data for assertion tmp_list = [ - {"issuer_address": issuer_address_1, "personal_info_address": personal_info_contract_1.address}, - {"issuer_address": issuer_address_2, "personal_info_address": personal_info_contract_2.address} + { + "issuer_address": issuer_address_1, + "personal_info_address": personal_info_contract_1.address, + }, + { + "issuer_address": issuer_address_2, + "personal_info_address": personal_info_contract_2.address, + }, ] personal_info_dict = { issuer_address_1: personal_info_1, @@ -783,10 +839,13 @@ def test_normal_4(self, processor, db): for i in range(2): _personal_info = _personal_info_list[i] - assert _personal_info.id == i+1 + assert _personal_info.id == i + 1 assert _personal_info.account_address == stored_address_order[i] assert _personal_info.issuer_address == stored_address_order[i] - assert _personal_info.personal_info == personal_info_dict[stored_address_order[i]] + assert ( + _personal_info.personal_info + == personal_info_dict[stored_address_order[i]] + ) _idx_personal_info_block_number = db.query(IDXPersonalInfoBlockNumber).first() assert _idx_personal_info_block_number.id == 1 @@ -796,7 +855,9 @@ def test_normal_4(self, processor, db): # If block number processed in batch is equal or greater than current block number, # batch logs "skip Process". @mock.patch("web3.eth.Eth.block_number", 100) - def test_normal_5(self, processor: Processor, db: Session, caplog: pytest.LogCaptureFixture): + def test_normal_5( + self, processor: Processor, db: Session, caplog: pytest.LogCaptureFixture + ): _idx_personal_info_block_number = IDXPersonalInfoBlockNumber() _idx_personal_info_block_number.id = 1 _idx_personal_info_block_number.latest_block_number = 1000 @@ -804,16 +865,23 @@ def test_normal_5(self, processor: Processor, db: Session, caplog: pytest.LogCap db.commit() processor.process() - assert 1 == caplog.record_tuples.count((LOG.name, logging.DEBUG, "skip process")) + assert 1 == caplog.record_tuples.count( + (LOG.name, logging.DEBUG, "skip process") + ) # # If DB session fails in phase sinking register/modify events, batch logs exception message. - def test_normal_6(self, processor: Processor, db: Session, personal_info_contract, caplog: pytest.LogCaptureFixture): + def test_normal_6( + self, + processor: Processor, + db: Session, + personal_info_contract, + caplog: pytest.LogCaptureFixture, + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) issuer_rsa_private_key = user_1["rsa_private_key"] issuer_rsa_public_key = user_1["rsa_public_key"] @@ -821,8 +889,7 @@ def test_normal_6(self, processor: Processor, db: Session, personal_info_contrac user_2 = config_eth_account("user2") user_address_1 = user_2["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Account @@ -835,9 +902,9 @@ def test_normal_6(self, processor: Processor, db: Session, personal_info_contrac db.add(account) # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_bond_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -868,15 +935,21 @@ def test_normal_6(self, processor: Processor, db: Session, personal_info_contrac "email": "email_test1", "birth": "birth_test1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } - ciphertext = encrypt_personal_info(personal_info_1, issuer_rsa_public_key, issuer_rsa_passphrase) - tx = personal_info_contract.functions.register(issuer_address, ciphertext).build_transaction({ - "chainId": CHAIN_ID, - "from": user_address_1, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ciphertext = encrypt_personal_info( + personal_info_1, issuer_rsa_public_key, issuer_rsa_passphrase + ) + tx = personal_info_contract.functions.register( + issuer_address, ciphertext + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": user_address_1, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, user_private_key_1) # Modify @@ -888,31 +961,48 @@ def test_normal_6(self, processor: Processor, db: Session, personal_info_contrac "email": "email_test2", "birth": "birth_test2", "is_corporate": True, - "tax_category": 20 + "tax_category": 20, } - ciphertext = encrypt_personal_info(personal_info_2, issuer_rsa_public_key, issuer_rsa_passphrase) - tx = personal_info_contract.functions.modify(user_address_1, ciphertext).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ciphertext = encrypt_personal_info( + personal_info_2, issuer_rsa_public_key, issuer_rsa_passphrase + ) + tx = personal_info_contract.functions.modify( + user_address_1, ciphertext + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) with patch.object(Session, "add", side_effect=Exception()): # Then execute processor. processor.process() - assert 2 == caplog.record_tuples.count((LOG.name, logging.ERROR, "An exception occurred during event synchronization")) + assert 2 == caplog.record_tuples.count( + ( + LOG.name, + logging.ERROR, + "An exception occurred during event synchronization", + ) + ) # # If DB session fails in phase sinking register/modify events, batch logs exception message. - def test_error_1(self, main_func, db: Session, personal_info_contract, caplog: pytest.LogCaptureFixture): + def test_error_1( + self, + main_func, + db: Session, + personal_info_contract, + caplog: pytest.LogCaptureFixture, + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) issuer_rsa_private_key = user_1["rsa_private_key"] issuer_rsa_public_key = user_1["rsa_public_key"] @@ -928,9 +1018,9 @@ def test_error_1(self, main_func, db: Session, personal_info_contract, caplog: p db.add(account) # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_bond_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -943,25 +1033,45 @@ def test_error_1(self, main_func, db: Session, personal_info_contract, caplog: p db.commit() # Run mainloop once and fail with web3 utils error - with patch("batch.indexer_personal_info.INDEXER_SYNC_INTERVAL", None),\ - patch.object(web3.eth, "contract", side_effect=ServiceUnavailableError()), \ - pytest.raises(TypeError): + with patch( + "batch.indexer_personal_info.INDEXER_SYNC_INTERVAL", None + ), patch.object( + web3.eth, "contract", side_effect=ServiceUnavailableError() + ), pytest.raises( + TypeError + ): main_func() - assert 1 == caplog.record_tuples.count((LOG.name, logging.WARNING, "An external service was unavailable")) + assert 1 == caplog.record_tuples.count( + (LOG.name, logging.WARNING, "An external service was unavailable") + ) caplog.clear() # Run mainloop once and fail with sqlalchemy InvalidRequestError - with patch("batch.indexer_personal_info.INDEXER_SYNC_INTERVAL", None),\ - patch.object(Session, "query", side_effect=InvalidRequestError()), \ - pytest.raises(TypeError): + with patch( + "batch.indexer_personal_info.INDEXER_SYNC_INTERVAL", None + ), patch.object( + Session, "query", side_effect=InvalidRequestError() + ), pytest.raises( + TypeError + ): main_func() assert 1 == caplog.text.count("A database error has occurred") caplog.clear() # Run mainloop once and fail with connection to blockchain - with patch("batch.indexer_personal_info.INDEXER_SYNC_INTERVAL", None), \ - patch.object(ContractUtils, "call_function", ConnectionError()), \ - pytest.raises(TypeError): + with patch( + "batch.indexer_personal_info.INDEXER_SYNC_INTERVAL", None + ), patch.object( + ContractUtils, "call_function", ConnectionError() + ), pytest.raises( + TypeError + ): main_func() - assert 1 == caplog.record_tuples.count((LOG.name, logging.ERROR, "An exception occurred during event synchronization")) + assert 1 == caplog.record_tuples.count( + ( + LOG.name, + logging.ERROR, + "An exception occurred during event synchronization", + ) + ) caplog.clear() diff --git a/tests/test_batch_indexer_position_bond.py b/tests/test_batch_indexer_position_bond.py index aa97d6bf..228c0c15 100644 --- a/tests/test_batch_indexer_position_bond.py +++ b/tests/test_batch_indexer_position_bond.py @@ -16,39 +16,44 @@ SPDX-License-Identifier: Apache-2.0 """ -from eth_keyfile import decode_keyfile_json import logging +from unittest import mock +from unittest.mock import patch + import pytest +from eth_keyfile import decode_keyfile_json from sqlalchemy.exc import InvalidRequestError from sqlalchemy.orm import Session -from unittest import mock -from unittest.mock import patch from app.exceptions import ServiceUnavailableError +from app.model.blockchain import IbetStraightBondContract +from app.model.blockchain.tx_params.ibet_straight_bond import ( + UpdateParams as IbetStraightBondUpdateParams, +) from app.model.db import ( - Token, - TokenType, - IDXPosition, + IDXLock, IDXLockedPosition, + IDXPosition, IDXPositionBondBlockNumber, - IDXLock, IDXUnlock, Notification, - NotificationType + NotificationType, + Token, + TokenType, ) -from app.model.blockchain import IbetStraightBondContract -from app.model.blockchain.tx_params.ibet_straight_bond import UpdateParams as IbetStraightBondUpdateParams -from app.utils.web3_utils import Web3Wrapper from app.utils.contract_utils import ContractUtils -from batch.indexer_position_bond import Processor, LOG, main +from app.utils.web3_utils import Web3Wrapper +from batch.indexer_position_bond import LOG, Processor, main from config import CHAIN_ID, TX_GAS_LIMIT, ZERO_ADDRESS from tests.account_config import config_eth_account +from tests.utils.contract_utils import IbetExchangeContractTestUtils from tests.utils.contract_utils import ( IbetSecurityTokenContractTestUtils as STContractUtils, - IbetExchangeContractTestUtils, - PersonalInfoContractTestUtils, +) +from tests.utils.contract_utils import ( IbetSecurityTokenEscrowContractTestUtils as STEscrowContractUtils, ) +from tests.utils.contract_utils import PersonalInfoContractTestUtils web3 = Web3Wrapper() @@ -75,11 +80,13 @@ def processor(db, caplog: pytest.LogCaptureFixture): LOG.setLevel(default_log_level) -def deploy_bond_token_contract(address, - private_key, - personal_info_contract_address, - tradable_exchange_contract_address=None, - transfer_approval_required=None): +def deploy_bond_token_contract( + address, + private_key, + personal_info_contract_address, + tradable_exchange_contract_address=None, + transfer_approval_required=None, +): arguments = [ "token.name", "token.symbol", @@ -89,7 +96,7 @@ def deploy_bond_token_contract(address, 30, "token.return_date", "token.return_amount", - "token.purpose" + "token.purpose", ] bond_contrat = IbetStraightBondContract() token_address, _, _ = bond_contrat.create(arguments, address, private_key) @@ -98,17 +105,16 @@ def deploy_bond_token_contract(address, transferable=True, personal_info_contract_address=personal_info_contract_address, tradable_exchange_contract_address=tradable_exchange_contract_address, - transfer_approval_required=transfer_approval_required + transfer_approval_required=transfer_approval_required, ), tx_from=address, - private_key=private_key + private_key=private_key, ) return ContractUtils.get_contract("IbetStraightBond", token_address) class TestProcessor: - ########################################################################### # Normal Case ########################################################################### @@ -117,7 +123,9 @@ class TestProcessor: # Single Token # No event logs # not issue token - def test_normal_1_1(self, processor: Processor, db: Session, personal_info_contract): + def test_normal_1_1( + self, processor: Processor, db: Session, personal_info_contract + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] @@ -157,18 +165,19 @@ def test_normal_1_1(self, processor: Processor, db: Session, personal_info_contr # Single Token # No event logs # issued token - def test_normal_1_2(self, processor: Processor, db: Session, personal_info_contract): + def test_normal_1_2( + self, processor: Processor, db: Session, personal_info_contract + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_bond_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -211,7 +220,11 @@ def test_normal_1_2(self, processor: Processor, db: Session, personal_info_contr # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 1 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 @@ -226,20 +239,21 @@ def test_normal_1_2(self, processor: Processor, db: Session, personal_info_contr # Single Token # Single event logs # - Issue - def test_normal_2_1(self, processor: Processor, db: Session, personal_info_contract): + def test_normal_2_1( + self, processor: Processor, db: Session, personal_info_contract + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_bond_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -271,12 +285,16 @@ def test_normal_2_1(self, processor: Processor, db: Session, personal_info_contr db.commit() # Issue - tx = token_contract_1.functions.issueFrom(user_address_1, ZERO_ADDRESS, 40).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = token_contract_1.functions.issueFrom( + user_address_1, ZERO_ADDRESS, 40 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -286,14 +304,22 @@ def test_normal_2_1(self, processor: Processor, db: Session, personal_info_contr # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 2 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 40 @@ -308,20 +334,21 @@ def test_normal_2_1(self, processor: Processor, db: Session, personal_info_contr # Single Token # Single event logs # - Transfer(to account) - def test_normal_2_2_1(self, processor: Processor, db: Session, personal_info_contract): + def test_normal_2_2_1( + self, processor: Processor, db: Session, personal_info_contract + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_bond_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -353,12 +380,16 @@ def test_normal_2_2_1(self, processor: Processor, db: Session, personal_info_con db.commit() # Transfer - tx = token_contract_1.functions.transferFrom(issuer_address, user_address_1, 40).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = token_contract_1.functions.transferFrom( + issuer_address, user_address_1, 40 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -368,14 +399,22 @@ def test_normal_2_2_1(self, processor: Processor, db: Session, personal_info_con # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 2 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 40 @@ -390,19 +429,26 @@ def test_normal_2_2_1(self, processor: Processor, db: Session, personal_info_con # Single Token # Single event logs # - Transfer(to DEX) - def test_normal_2_2_2(self, processor: Processor, db: Session, personal_info_contract, ibet_escrow_contract): + def test_normal_2_2_2( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_escrow_contract, + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address, - ibet_escrow_contract.address) + token_contract_1 = deploy_bond_token_contract( + issuer_address, + issuer_private_key, + personal_info_contract.address, + ibet_escrow_contract.address, + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -436,12 +482,14 @@ def test_normal_2_2_2(self, processor: Processor, db: Session, personal_info_con # Deposit tx = token_contract_1.functions.transferFrom( issuer_address, ibet_escrow_contract.address, 40 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -451,7 +499,11 @@ def test_normal_2_2_2(self, processor: Processor, db: Session, personal_info_con # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 1 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 @@ -466,21 +518,28 @@ def test_normal_2_2_2(self, processor: Processor, db: Session, personal_info_con # Single Token # Single event logs # - Transfer(HolderChanged in DEX) - def test_normal_2_2_3(self, processor: Processor, db: Session, personal_info_contract, ibet_escrow_contract): + def test_normal_2_2_3( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_escrow_contract, + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address, - ibet_escrow_contract.address) + token_contract_1 = deploy_bond_token_contract( + issuer_address, + issuer_private_key, + personal_info_contract.address, + ibet_escrow_contract.address, + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -514,19 +573,25 @@ def test_normal_2_2_3(self, processor: Processor, db: Session, personal_info_con # Deposit tx = token_contract_1.functions.transferFrom( issuer_address, ibet_escrow_contract.address, 40 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Before run(consume accumulated events) processor.sync_new_logs() _position_list = db.query(IDXPosition).all() assert len(_position_list) == 1 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 @@ -537,21 +602,26 @@ def test_normal_2_2_3(self, processor: Processor, db: Session, personal_info_con # Holder Change tx = ibet_escrow_contract.functions.createEscrow( token_contract_1.address, user_address_1, 30, issuer_address, "" - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) escrow_id = ContractUtils.call_function( - ibet_escrow_contract, "latestEscrowId", ()) - tx = ibet_escrow_contract.functions.finishEscrow(escrow_id).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ibet_escrow_contract, "latestEscrowId", () + ) + tx = ibet_escrow_contract.functions.finishEscrow(escrow_id).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -565,14 +635,22 @@ def test_normal_2_2_3(self, processor: Processor, db: Session, personal_info_con # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 2 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 assert _position.exchange_balance == 40 - 30 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 0 @@ -587,18 +665,19 @@ def test_normal_2_2_3(self, processor: Processor, db: Session, personal_info_con # Single Token # Single event logs # - Lock - def test_normal_2_3(self, processor: Processor, db: Session, personal_info_contract): + def test_normal_2_3( + self, processor: Processor, db: Session, personal_info_contract + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_bond_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -631,15 +710,15 @@ def test_normal_2_3(self, processor: Processor, db: Session, personal_info_contr # Lock tx = token_contract_1.functions.lock( - issuer_address, - 40, - '{"message": "locked1"}' - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + issuer_address, 40, '{"message": "locked1"}' + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -650,9 +729,11 @@ def test_normal_2_3(self, processor: Processor, db: Session, personal_info_contr _position_list = db.query(IDXPosition).all() assert len(_position_list) == 1 - _position = db.query(IDXPosition).\ - filter(IDXPosition.account_address == issuer_address).\ - first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 @@ -660,10 +741,12 @@ def test_normal_2_3(self, processor: Processor, db: Session, personal_info_contr assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _locked_position = db.query(IDXLockedPosition).\ - filter(IDXLockedPosition.token_address == token_address_1).\ - filter(IDXLockedPosition.account_address == issuer_address).\ - first() + _locked_position = ( + db.query(IDXLockedPosition) + .filter(IDXLockedPosition.token_address == token_address_1) + .filter(IDXLockedPosition.account_address == issuer_address) + .first() + ) assert _locked_position.token_address == token_address_1 assert _locked_position.lock_address == issuer_address assert _locked_position.account_address == issuer_address @@ -694,9 +777,7 @@ def test_normal_2_3(self, processor: Processor, db: Session, personal_info_contr "account_address": issuer_address, "lock_address": issuer_address, "value": 40, - "data": { - "message": "locked1" - } + "data": {"message": "locked1"}, } _idx_position_bond_block_number = db.query(IDXPositionBondBlockNumber).first() @@ -707,18 +788,19 @@ def test_normal_2_3(self, processor: Processor, db: Session, personal_info_contr # Single Token # Single event logs # - Unlock - def test_normal_2_4(self, processor: Processor, db: Session, personal_info_contract): + def test_normal_2_4( + self, processor: Processor, db: Session, personal_info_contract + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_bond_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -751,15 +833,15 @@ def test_normal_2_4(self, processor: Processor, db: Session, personal_info_contr # Lock tx = token_contract_1.functions.lock( - issuer_address, - 40, - '{"message": "locked1"}' - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + issuer_address, 40, '{"message": "locked1"}' + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Before run(consume accumulated events) @@ -768,9 +850,11 @@ def test_normal_2_4(self, processor: Processor, db: Session, personal_info_contr _position_list = db.query(IDXPosition).all() assert len(_position_list) == 1 - _position = db.query(IDXPosition).\ - filter(IDXPosition.account_address == issuer_address).\ - first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 @@ -780,16 +864,15 @@ def test_normal_2_4(self, processor: Processor, db: Session, personal_info_contr # Unlock tx = token_contract_1.functions.unlock( - issuer_address, - issuer_address, - 30, - '{"message": "unlocked1"}' - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + issuer_address, issuer_address, 30, '{"message": "unlocked1"}' + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -804,9 +887,11 @@ def test_normal_2_4(self, processor: Processor, db: Session, personal_info_contr _position_list = db.query(IDXPosition).all() assert len(_position_list) == 1 - _position = db.query(IDXPosition).\ - filter(IDXPosition.account_address == issuer_address).\ - first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 + 30 @@ -814,10 +899,12 @@ def test_normal_2_4(self, processor: Processor, db: Session, personal_info_contr assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _locked_position = db.query(IDXLockedPosition).\ - filter(IDXLockedPosition.token_address == token_address_1).\ - filter(IDXLockedPosition.account_address == issuer_address).\ - first() + _locked_position = ( + db.query(IDXLockedPosition) + .filter(IDXLockedPosition.token_address == token_address_1) + .filter(IDXLockedPosition.account_address == issuer_address) + .first() + ) assert _locked_position.token_address == token_address_1 assert _locked_position.lock_address == issuer_address assert _locked_position.account_address == issuer_address @@ -844,9 +931,7 @@ def test_normal_2_4(self, processor: Processor, db: Session, personal_info_contr assert _unlock1.account_address == issuer_address assert _unlock1.recipient_address == issuer_address assert _unlock1.value == 30 - assert _unlock1.data == { - "message": "unlocked1" - } + assert _unlock1.data == {"message": "unlocked1"} _notification_list = db.query(Notification).order_by(Notification.created).all() assert len(_notification_list) == 2 @@ -862,9 +947,7 @@ def test_normal_2_4(self, processor: Processor, db: Session, personal_info_contr "account_address": issuer_address, "lock_address": issuer_address, "value": 40, - "data": { - "message": "locked1" - } + "data": {"message": "locked1"}, } _notification1 = _notification_list[1] @@ -879,9 +962,7 @@ def test_normal_2_4(self, processor: Processor, db: Session, personal_info_contr "lock_address": issuer_address, "recipient_address": issuer_address, "value": 30, - "data": { - "message": "unlocked1" - } + "data": {"message": "unlocked1"}, } _idx_position_bond_block_number = db.query(IDXPositionBondBlockNumber).first() @@ -892,18 +973,19 @@ def test_normal_2_4(self, processor: Processor, db: Session, personal_info_contr # Single Token # Single event logs # - Redeem - def test_normal_2_5(self, processor: Processor, db: Session, personal_info_contract): + def test_normal_2_5( + self, processor: Processor, db: Session, personal_info_contract + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_bond_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -935,12 +1017,16 @@ def test_normal_2_5(self, processor: Processor, db: Session, personal_info_contr db.commit() # Redeem - tx = token_contract_1.functions.redeemFrom(issuer_address, ZERO_ADDRESS, 40).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = token_contract_1.functions.redeemFrom( + issuer_address, ZERO_ADDRESS, 40 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -950,7 +1036,11 @@ def test_normal_2_5(self, processor: Processor, db: Session, personal_info_contr # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 1 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 @@ -965,25 +1055,27 @@ def test_normal_2_5(self, processor: Processor, db: Session, personal_info_contr # Single Token # Single event logs # - ApplyForTransfer - def test_normal_2_6(self, processor: Processor, db: Session, personal_info_contract): + def test_normal_2_6( + self, processor: Processor, db: Session, personal_info_contract + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address, - transfer_approval_required=True) + token_contract_1 = deploy_bond_token_contract( + issuer_address, + issuer_private_key, + personal_info_contract.address, + transfer_approval_required=True, + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -1015,16 +1107,22 @@ def test_normal_2_6(self, processor: Processor, db: Session, personal_info_contr db.commit() # ApplyForTransfer - PersonalInfoContractTestUtils.register(personal_info_contract.address, - user_address_1, - user_private_key_1, - [issuer_address, "test"]) - tx = token_contract_1.functions.applyForTransfer(user_address_1, 40, "").build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_private_key_1, + [issuer_address, "test"], + ) + tx = token_contract_1.functions.applyForTransfer( + user_address_1, 40, "" + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -1034,7 +1132,11 @@ def test_normal_2_6(self, processor: Processor, db: Session, personal_info_contr # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 1 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 @@ -1053,21 +1155,21 @@ def test_normal_2_7(self, processor, db, personal_info_contract): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address, - transfer_approval_required=True) + token_contract_1 = deploy_bond_token_contract( + issuer_address, + issuer_private_key, + personal_info_contract.address, + transfer_approval_required=True, + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -1099,23 +1201,33 @@ def test_normal_2_7(self, processor, db, personal_info_contract): db.commit() # ApplyForTransfer - PersonalInfoContractTestUtils.register(personal_info_contract.address, - user_address_1, - user_private_key_1, - [issuer_address, "test"]) - tx = token_contract_1.functions.applyForTransfer(user_address_1, 40, "").build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_private_key_1, + [issuer_address, "test"], + ) + tx = token_contract_1.functions.applyForTransfer( + user_address_1, 40, "" + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Before run(consume accumulated events) processor.sync_new_logs() _position_list = db.query(IDXPosition).all() assert len(_position_list) == 1 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 @@ -1124,12 +1236,14 @@ def test_normal_2_7(self, processor, db, personal_info_contract): assert _position.pending_transfer == 40 # CancelTransfer - tx = token_contract_1.functions.cancelTransfer(0, "").build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = token_contract_1.functions.cancelTransfer(0, "").build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -1143,7 +1257,11 @@ def test_normal_2_7(self, processor, db, personal_info_contract): # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 1 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 @@ -1158,25 +1276,27 @@ def test_normal_2_7(self, processor, db, personal_info_contract): # Single Token # Single event logs # - ApproveTransfer - def test_normal_2_8(self, processor: Processor, db: Session, personal_info_contract): + def test_normal_2_8( + self, processor: Processor, db: Session, personal_info_contract + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address, - transfer_approval_required=True) + token_contract_1 = deploy_bond_token_contract( + issuer_address, + issuer_private_key, + personal_info_contract.address, + transfer_approval_required=True, + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -1208,23 +1328,33 @@ def test_normal_2_8(self, processor: Processor, db: Session, personal_info_contr db.commit() # ApplyForTransfer - PersonalInfoContractTestUtils.register(personal_info_contract.address, - user_address_1, - user_private_key_1, - [issuer_address, "test"]) - tx = token_contract_1.functions.applyForTransfer(user_address_1, 40, "").build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_private_key_1, + [issuer_address, "test"], + ) + tx = token_contract_1.functions.applyForTransfer( + user_address_1, 40, "" + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Before run(consume accumulated events) processor.sync_new_logs() _position_list = db.query(IDXPosition).all() assert len(_position_list) == 1 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 @@ -1233,12 +1363,14 @@ def test_normal_2_8(self, processor: Processor, db: Session, personal_info_contr assert _position.pending_transfer == 40 # ApproveTransfer - tx = token_contract_1.functions.approveTransfer(0, "").build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = token_contract_1.functions.approveTransfer(0, "").build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -1252,14 +1384,22 @@ def test_normal_2_8(self, processor: Processor, db: Session, personal_info_contr # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 2 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 40 @@ -1274,19 +1414,26 @@ def test_normal_2_8(self, processor: Processor, db: Session, personal_info_contr # Single Token # Single event logs # - IbetExchange: NewOrder - def test_normal_2_9_1(self, processor: Processor, db: Session, personal_info_contract, ibet_exchange_contract): + def test_normal_2_9_1( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_exchange_contract, + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address, - tradable_exchange_contract_address=ibet_exchange_contract.address) + token_contract_1 = deploy_bond_token_contract( + issuer_address, + issuer_private_key, + personal_info_contract.address, + tradable_exchange_contract_address=ibet_exchange_contract.address, + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -1320,19 +1467,25 @@ def test_normal_2_9_1(self, processor: Processor, db: Session, personal_info_con # Deposit tx = token_contract_1.functions.transferFrom( issuer_address, ibet_exchange_contract.address, 40 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Before run(consume accumulated events) processor.sync_new_logs() _position_list = db.query(IDXPosition).all() assert len(_position_list) == 1 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 @@ -1343,12 +1496,14 @@ def test_normal_2_9_1(self, processor: Processor, db: Session, personal_info_con # NewOrder(Sell) tx = ibet_exchange_contract.functions.createOrder( token_address_1, 30, 10000, False, issuer_address - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -1362,7 +1517,11 @@ def test_normal_2_9_1(self, processor: Processor, db: Session, personal_info_con # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 1 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 @@ -1377,17 +1536,29 @@ def test_normal_2_9_1(self, processor: Processor, db: Session, personal_info_con # Single Token # Single event logs # - IbetExchange: CancelOrder - def test_normal_2_9_2(self, processor: Processor, db: Session, personal_info_contract, ibet_exchange_contract): + def test_normal_2_9_2( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_exchange_contract, + ): exchange_contract = ibet_exchange_contract user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues bond token. token_contract = deploy_bond_token_contract( @@ -1411,20 +1582,57 @@ def test_normal_2_9_2(self, processor: Processor, db: Session, personal_info_con # Before run(consume accumulated events) processor.sync_new_logs() - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 30]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_2, 10]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 30], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, 10], + ) # NewOrder(Sell) & CancelOrder - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [exchange_contract.address, 10]) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [exchange_contract.address, 10], + ) IbetExchangeContractTestUtils.create_order( - exchange_contract.address, user_address_1, user_pk_1, [token_contract.address, 10, 100, False, issuer_address] + exchange_contract.address, + user_address_1, + user_pk_1, + [token_contract.address, 10, 100, False, issuer_address], + ) + latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id( + exchange_contract.address + ) + IbetExchangeContractTestUtils.cancel_order( + exchange_contract.address, user_address_1, user_pk_1, [latest_order_id] ) - latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id(exchange_contract.address) - IbetExchangeContractTestUtils.cancel_order(exchange_contract.address, user_address_1, user_pk_1, [latest_order_id]) # Run target process block_number = web3.eth.block_number @@ -1433,21 +1641,33 @@ def test_normal_2_9_2(self, processor: Processor, db: Session, personal_info_con # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 3 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 30 - 10 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 30 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_2).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_2) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_2 assert _position.balance == 10 @@ -1462,17 +1682,29 @@ def test_normal_2_9_2(self, processor: Processor, db: Session, personal_info_con # Single Token # Single event logs # - IbetExchange: ForceCancelOrder - def test_normal_2_9_3(self, processor: Processor, db: Session, personal_info_contract, ibet_exchange_contract): + def test_normal_2_9_3( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_exchange_contract, + ): exchange_contract = ibet_exchange_contract user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues bond token. token_contract = deploy_bond_token_contract( @@ -1496,20 +1728,60 @@ def test_normal_2_9_3(self, processor: Processor, db: Session, personal_info_con # Before run(consume accumulated events) processor.sync_new_logs() - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 30]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_2, 10]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 30], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, 10], + ) # NewOrder(Sell) & ForceCancelOrder - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [exchange_contract.address, 10]) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [exchange_contract.address, 10], + ) IbetExchangeContractTestUtils.create_order( - exchange_contract.address, user_address_1, user_pk_1, [token_contract.address, 10, 100, False, issuer_address] + exchange_contract.address, + user_address_1, + user_pk_1, + [token_contract.address, 10, 100, False, issuer_address], + ) + latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id( + exchange_contract.address + ) + IbetExchangeContractTestUtils.force_cancel_order( + exchange_contract.address, + issuer_address, + issuer_private_key, + [latest_order_id], ) - latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id(exchange_contract.address) - IbetExchangeContractTestUtils.force_cancel_order(exchange_contract.address, issuer_address, issuer_private_key, [latest_order_id]) # Run target process block_number = web3.eth.block_number @@ -1518,21 +1790,33 @@ def test_normal_2_9_3(self, processor: Processor, db: Session, personal_info_con # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 3 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 30 - 10 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 30 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_2).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_2) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_2 assert _position.balance == 10 @@ -1547,17 +1831,29 @@ def test_normal_2_9_3(self, processor: Processor, db: Session, personal_info_con # Single Token # Single event logs # - IbetExchange: Agree - def test_normal_2_9_4(self, processor: Processor, db: Session, personal_info_contract, ibet_exchange_contract): + def test_normal_2_9_4( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_exchange_contract, + ): exchange_contract = ibet_exchange_contract user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues bond token. token_contract = deploy_bond_token_contract( @@ -1581,20 +1877,60 @@ def test_normal_2_9_4(self, processor: Processor, db: Session, personal_info_con # Before run(consume accumulated events) processor.sync_new_logs() - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 30]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_2, 10]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 30], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, 10], + ) # NewOrder(Sell) & ExecuteOrder - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [exchange_contract.address, 10]) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [exchange_contract.address, 10], + ) IbetExchangeContractTestUtils.create_order( - exchange_contract.address, user_address_1, user_pk_1, [token_contract.address, 10, 100, False, issuer_address] + exchange_contract.address, + user_address_1, + user_pk_1, + [token_contract.address, 10, 100, False, issuer_address], + ) + latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id( + exchange_contract.address + ) + IbetExchangeContractTestUtils.execute_order( + exchange_contract.address, + user_address_2, + user_pk_2, + [latest_order_id, 10, True], ) - latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id(exchange_contract.address) - IbetExchangeContractTestUtils.execute_order(exchange_contract.address, user_address_2, user_pk_2, [latest_order_id, 10, True]) # Run target process block_number = web3.eth.block_number @@ -1603,21 +1939,33 @@ def test_normal_2_9_4(self, processor: Processor, db: Session, personal_info_con # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 3 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 30 - 10 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 20 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 10 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_2).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_2) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_2 assert _position.balance == 10 @@ -1632,17 +1980,29 @@ def test_normal_2_9_4(self, processor: Processor, db: Session, personal_info_con # Single Token # Single event logs # - IbetExchange: SettlementOK - def test_normal_2_9_5(self, processor: Processor, db: Session, personal_info_contract, ibet_exchange_contract): + def test_normal_2_9_5( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_exchange_contract, + ): exchange_contract = ibet_exchange_contract user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues bond token. token_contract = deploy_bond_token_contract( @@ -1666,23 +2026,68 @@ def test_normal_2_9_5(self, processor: Processor, db: Session, personal_info_con # Before run(consume accumulated events) processor.sync_new_logs() - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 30]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_2, 10]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 30], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, 10], + ) # NewOrder(Sell) & ExecuteOrder & ConfirmAgreement - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [exchange_contract.address, 10]) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [exchange_contract.address, 10], + ) IbetExchangeContractTestUtils.create_order( - exchange_contract.address, user_address_1, user_pk_1, [token_contract.address, 10, 100, False, issuer_address] + exchange_contract.address, + user_address_1, + user_pk_1, + [token_contract.address, 10, 100, False, issuer_address], + ) + latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id( + exchange_contract.address + ) + IbetExchangeContractTestUtils.execute_order( + exchange_contract.address, + user_address_2, + user_pk_2, + [latest_order_id, 10, True], + ) + latest_agreement_id = IbetExchangeContractTestUtils.get_latest_agreementid( + exchange_contract.address, latest_order_id ) - latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id(exchange_contract.address) - IbetExchangeContractTestUtils.execute_order(exchange_contract.address, user_address_2, user_pk_2, [latest_order_id, 10, True]) - latest_agreement_id = IbetExchangeContractTestUtils.get_latest_agreementid(exchange_contract.address, latest_order_id) IbetExchangeContractTestUtils.confirm_agreement( - exchange_contract.address, issuer_address, issuer_private_key, [latest_order_id, latest_agreement_id] + exchange_contract.address, + issuer_address, + issuer_private_key, + [latest_order_id, latest_agreement_id], ) # Run target process @@ -1692,21 +2097,33 @@ def test_normal_2_9_5(self, processor: Processor, db: Session, personal_info_con # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 3 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 30 - 10 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 20 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_2).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_2) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_2 assert _position.balance == 20 @@ -1721,17 +2138,29 @@ def test_normal_2_9_5(self, processor: Processor, db: Session, personal_info_con # Single Token # Single event logs # - IbetExchange: SettlementNG - def test_normal_2_9_6(self, processor: Processor, db: Session, personal_info_contract, ibet_exchange_contract): + def test_normal_2_9_6( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_exchange_contract, + ): exchange_contract = ibet_exchange_contract user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues bond token. token_contract = deploy_bond_token_contract( @@ -1755,23 +2184,68 @@ def test_normal_2_9_6(self, processor: Processor, db: Session, personal_info_con # Before run(consume accumulated events) processor.sync_new_logs() - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 30]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_2, 10]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 30], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, 10], + ) # NewOrder(Sell) & ExecuteOrder & CancelAgreement - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [exchange_contract.address, 10]) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [exchange_contract.address, 10], + ) IbetExchangeContractTestUtils.create_order( - exchange_contract.address, user_address_1, user_pk_1, [token_contract.address, 10, 100, False, issuer_address] + exchange_contract.address, + user_address_1, + user_pk_1, + [token_contract.address, 10, 100, False, issuer_address], + ) + latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id( + exchange_contract.address + ) + IbetExchangeContractTestUtils.execute_order( + exchange_contract.address, + user_address_2, + user_pk_2, + [latest_order_id, 10, True], + ) + latest_agreement_id = IbetExchangeContractTestUtils.get_latest_agreementid( + exchange_contract.address, latest_order_id ) - latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id(exchange_contract.address) - IbetExchangeContractTestUtils.execute_order(exchange_contract.address, user_address_2, user_pk_2, [latest_order_id, 10, True]) - latest_agreement_id = IbetExchangeContractTestUtils.get_latest_agreementid(exchange_contract.address, latest_order_id) IbetExchangeContractTestUtils.cancel_agreement( - exchange_contract.address, issuer_address, issuer_private_key, [latest_order_id, latest_agreement_id] + exchange_contract.address, + issuer_address, + issuer_private_key, + [latest_order_id, latest_agreement_id], ) # Run target process @@ -1781,21 +2255,33 @@ def test_normal_2_9_6(self, processor: Processor, db: Session, personal_info_con # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 3 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 30 - 10 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 20 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 10 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_2).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_2) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_2 assert _position.balance == 10 @@ -1810,21 +2296,28 @@ def test_normal_2_9_6(self, processor: Processor, db: Session, personal_info_con # Single Token # Single event logs # - IbetSecurityTokenEscrow: EscrowCreated - def test_normal_2_10_1(self, processor: Processor, db: Session, personal_info_contract, ibet_security_token_escrow_contract): + def test_normal_2_10_1( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_security_token_escrow_contract, + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address, - ibet_security_token_escrow_contract.address) + token_contract_1 = deploy_bond_token_contract( + issuer_address, + issuer_private_key, + personal_info_contract.address, + ibet_security_token_escrow_contract.address, + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -1858,19 +2351,25 @@ def test_normal_2_10_1(self, processor: Processor, db: Session, personal_info_co # Deposit tx = token_contract_1.functions.transferFrom( issuer_address, ibet_security_token_escrow_contract.address, 40 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Before run(consume accumulated events) processor.sync_new_logs() _position_list = db.query(IDXPosition).all() assert len(_position_list) == 1 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 @@ -1881,12 +2380,14 @@ def test_normal_2_10_1(self, processor: Processor, db: Session, personal_info_co # EscrowCreated tx = ibet_security_token_escrow_contract.functions.createEscrow( token_contract_1.address, user_address_1, 30, issuer_address, "", "" - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -1900,7 +2401,11 @@ def test_normal_2_10_1(self, processor: Processor, db: Session, personal_info_co # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 1 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 @@ -1915,17 +2420,29 @@ def test_normal_2_10_1(self, processor: Processor, db: Session, personal_info_co # Single Token # Single event logs # - IbetSecurityTokenEscrow: EscrowCanceled - def test_normal_2_10_2(self, processor: Processor, db: Session, personal_info_contract, ibet_security_token_escrow_contract): + def test_normal_2_10_2( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_security_token_escrow_contract, + ): escrow_contract = ibet_security_token_escrow_contract user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues bond token. token_contract = deploy_bond_token_contract( @@ -1949,21 +2466,58 @@ def test_normal_2_10_2(self, processor: Processor, db: Session, personal_info_co # Before run(consume accumulated events) processor.sync_new_logs() - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 30]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_2, 10]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 30], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, 10], + ) # CreateEscrow & CancelEscrow - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [escrow_contract.address, 30]) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [escrow_contract.address, 30], + ) STEscrowContractUtils.create_escrow( - escrow_contract.address, user_address_1, user_pk_1, [token_contract.address, user_address_2, 10, issuer_address, "", ""] + escrow_contract.address, + user_address_1, + user_pk_1, + [token_contract.address, user_address_2, 10, issuer_address, "", ""], + ) + latest_escrow_id = STEscrowContractUtils.get_latest_escrow_id( + escrow_contract.address + ) + STEscrowContractUtils.cancel_escrow( + escrow_contract.address, user_address_1, user_pk_1, [latest_escrow_id] ) - latest_escrow_id = STEscrowContractUtils.get_latest_escrow_id(escrow_contract.address) - STEscrowContractUtils.cancel_escrow(escrow_contract.address, user_address_1, user_pk_1, [latest_escrow_id]) # Run target process block_number = web3.eth.block_number @@ -1972,21 +2526,33 @@ def test_normal_2_10_2(self, processor: Processor, db: Session, personal_info_co # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 3 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 30 - 10 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 0 assert _position.exchange_balance == 30 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_2).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_2) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_2 assert _position.balance == 10 @@ -2001,17 +2567,29 @@ def test_normal_2_10_2(self, processor: Processor, db: Session, personal_info_co # Single Token # Single event logs # - IbetSecurityTokenEscrow: EscrowFinished - def test_normal_2_10_3(self, processor: Processor, db: Session, personal_info_contract, ibet_security_token_escrow_contract): + def test_normal_2_10_3( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_security_token_escrow_contract, + ): escrow_contract = ibet_security_token_escrow_contract user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues bond token. token_contract = deploy_bond_token_contract( @@ -2035,22 +2613,60 @@ def test_normal_2_10_3(self, processor: Processor, db: Session, personal_info_co # Before run(consume accumulated events) processor.sync_new_logs() - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 30]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_2, 10]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 30], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, 10], + ) # CreateEscrow & CancelEscrow - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [escrow_contract.address, 30]) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [escrow_contract.address, 30], + ) STEscrowContractUtils.create_escrow( - escrow_contract.address, user_address_1, user_pk_1, [token_contract.address, user_address_2, 10, issuer_address, "", ""] + escrow_contract.address, + user_address_1, + user_pk_1, + [token_contract.address, user_address_2, 10, issuer_address, "", ""], + ) + latest_escrow_id = STEscrowContractUtils.get_latest_escrow_id( + escrow_contract.address ) - latest_escrow_id = STEscrowContractUtils.get_latest_escrow_id(escrow_contract.address) STEscrowContractUtils.finish_escrow( - ibet_security_token_escrow_contract.address, issuer_address, issuer_private_key, [latest_escrow_id] + ibet_security_token_escrow_contract.address, + issuer_address, + issuer_private_key, + [latest_escrow_id], ) # Run target process block_number = web3.eth.block_number @@ -2059,21 +2675,33 @@ def test_normal_2_10_3(self, processor: Processor, db: Session, personal_info_co # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 3 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 30 - 10 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 0 assert _position.exchange_balance == 20 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_2).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_2) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_2 assert _position.balance == 10 @@ -2088,30 +2716,29 @@ def test_normal_2_10_3(self, processor: Processor, db: Session, personal_info_co # Single Token # Multi event logs # - Transfer(twice) - def test_normal_3_1(self, processor: Processor, db: Session, personal_info_contract): + def test_normal_3_1( + self, processor: Processor, db: Session, personal_info_contract + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] user_private_key_2 = decode_keyfile_json( - raw_keyfile_json=user_3["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_bond_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -2146,29 +2773,39 @@ def test_normal_3_1(self, processor: Processor, db: Session, personal_info_contr processor.sync_new_logs() # Transfer: 1st - tx = token_contract_1.functions.transferFrom(issuer_address, user_address_1, 40).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = token_contract_1.functions.transferFrom( + issuer_address, user_address_1, 40 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Transfer: 2nd - PersonalInfoContractTestUtils.register(personal_info_contract.address, - user_address_1, - user_private_key_1, - [issuer_address, "test"]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, - user_address_2, - user_private_key_2, - [issuer_address, "test"]) - tx = token_contract_1.functions.transfer(user_address_2, 10).build_transaction({ - "chainId": CHAIN_ID, - "from": user_address_1, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_private_key_1, + [issuer_address, "test"], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_private_key_2, + [issuer_address, "test"], + ) + tx = token_contract_1.functions.transfer(user_address_2, 10).build_transaction( + { + "chainId": CHAIN_ID, + "from": user_address_1, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, user_private_key_1) # Run target process @@ -2178,21 +2815,33 @@ def test_normal_3_1(self, processor: Processor, db: Session, personal_info_contr # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 3 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 40 - 10 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_2).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_2) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_2 assert _position.balance == 10 @@ -2207,30 +2856,39 @@ def test_normal_3_1(self, processor: Processor, db: Session, personal_info_contr # Single Token # Multi event logs # - Transfer(BulkTransfer) - def test_normal_3_2(self, processor: Processor, db: Session, personal_info_contract): + def test_normal_3_2( + self, processor: Processor, db: Session, personal_info_contract + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) user_4 = config_eth_account("user4") user_address_3 = user_4["address"] - user_pk_3 = decode_keyfile_json(raw_keyfile_json=user_4["keyfile_json"], password="password".encode("utf-8")) + user_pk_3 = decode_keyfile_json( + raw_keyfile_json=user_4["keyfile_json"], password="password".encode("utf-8") + ) user_5 = config_eth_account("user5") user_address_4 = user_5["address"] - user_pk_4 = decode_keyfile_json(raw_keyfile_json=user_5["keyfile_json"], password="password".encode("utf-8")) + user_pk_4 = decode_keyfile_json( + raw_keyfile_json=user_5["keyfile_json"], password="password".encode("utf-8") + ) # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_bond_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -2254,32 +2912,65 @@ def test_normal_3_2(self, processor: Processor, db: Session, personal_info_contr # Before run(consume accumulated events) processor.sync_new_logs() - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_3, user_pk_3, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_4, user_pk_4, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_3, + user_pk_3, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_4, + user_pk_4, + [issuer_address, ""], + ) # BulkTransfer: 1st address_list1 = [user_address_1, user_address_2, user_address_3] value_list1 = [10, 20, 30] - tx = token_contract_1.functions.bulkTransfer(address_list1, value_list1).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = token_contract_1.functions.bulkTransfer( + address_list1, value_list1 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) _, _ = ContractUtils.send_transaction(tx, issuer_private_key) # BulkTransfer: 2nd address_list2 = [user_address_1, user_address_2, user_address_3, user_address_4] value_list2 = [1, 2, 3, 4] - tx = token_contract_1.functions.bulkTransfer(address_list2, value_list2).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = token_contract_1.functions.bulkTransfer( + address_list2, value_list2 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) _, _ = ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -2288,35 +2979,55 @@ def test_normal_3_2(self, processor: Processor, db: Session, personal_info_contr _position_list = db.query(IDXPosition).all() assert len(_position_list) == 5 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 60 - 10 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 11 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_2).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_2) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_2 assert _position.balance == 22 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_3).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_3) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_3 assert _position.balance == 33 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_4).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_4) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_4 assert _position.balance == 4 @@ -2336,17 +3047,29 @@ def test_normal_3_2(self, processor: Processor, db: Session, personal_info_contr # Multi event logs # - IbetExchange: NewOrder # - IbetExchange: CancelOrder - def test_normal_3_3(self, processor: Processor, db: Session, personal_info_contract, ibet_exchange_contract): + def test_normal_3_3( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_exchange_contract, + ): exchange_contract = ibet_exchange_contract user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues bond token. token_contract = deploy_bond_token_contract( @@ -2370,27 +3093,71 @@ def test_normal_3_3(self, processor: Processor, db: Session, personal_info_contr # Before run(consume accumulated events) processor.sync_new_logs() - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 30]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_2, 10]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 30], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, 10], + ) # NewOrder(Sell) & CancelOrder - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [exchange_contract.address, 10]) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [exchange_contract.address, 10], + ) IbetExchangeContractTestUtils.create_order( - exchange_contract.address, user_address_1, user_pk_1, [token_contract.address, 10, 100, False, issuer_address] + exchange_contract.address, + user_address_1, + user_pk_1, + [token_contract.address, 10, 100, False, issuer_address], + ) + latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id( + exchange_contract.address + ) + IbetExchangeContractTestUtils.cancel_order( + exchange_contract.address, user_address_1, user_pk_1, [latest_order_id] ) - latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id(exchange_contract.address) - IbetExchangeContractTestUtils.cancel_order(exchange_contract.address, user_address_1, user_pk_1, [latest_order_id]) # NewOrder(Buy) & CancelOrder IbetExchangeContractTestUtils.create_order( - exchange_contract.address, user_address_1, user_pk_1, [token_contract.address, 10, 100, True, issuer_address] + exchange_contract.address, + user_address_1, + user_pk_1, + [token_contract.address, 10, 100, True, issuer_address], + ) + latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id( + exchange_contract.address + ) + IbetExchangeContractTestUtils.cancel_order( + exchange_contract.address, user_address_1, user_pk_1, [latest_order_id] ) - latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id(exchange_contract.address) - IbetExchangeContractTestUtils.cancel_order(exchange_contract.address, user_address_1, user_pk_1, [latest_order_id]) # Run target process block_number = web3.eth.block_number @@ -2399,21 +3166,33 @@ def test_normal_3_3(self, processor: Processor, db: Session, personal_info_contr # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 3 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 30 - 10 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 30 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_2).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_2) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_2 assert _position.balance == 10 @@ -2429,17 +3208,29 @@ def test_normal_3_3(self, processor: Processor, db: Session, personal_info_contr # Multi event logs # - IbetSecurityTokenEscrow: EscrowCreated # - IbetSecurityTokenEscrow: EscrowCanceled - def test_normal_3_4(self, processor: Processor, db: Session, personal_info_contract, ibet_security_token_escrow_contract): + def test_normal_3_4( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_security_token_escrow_contract, + ): escrow_contract = ibet_security_token_escrow_contract user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues bond token. token_contract = deploy_bond_token_contract( @@ -2463,21 +3254,58 @@ def test_normal_3_4(self, processor: Processor, db: Session, personal_info_contr # Before run(consume accumulated events) processor.sync_new_logs() - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 30]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_2, 10]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 30], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, 10], + ) # CreateEscrow & CancelEscrow - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [escrow_contract.address, 30]) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [escrow_contract.address, 30], + ) for _ in range(3): STEscrowContractUtils.create_escrow( - escrow_contract.address, user_address_1, user_pk_1, [token_contract.address, user_address_2, 10, issuer_address, "", ""] + escrow_contract.address, + user_address_1, + user_pk_1, + [token_contract.address, user_address_2, 10, issuer_address, "", ""], + ) + latest_escrow_id = STEscrowContractUtils.get_latest_escrow_id( + escrow_contract.address + ) + STEscrowContractUtils.cancel_escrow( + escrow_contract.address, user_address_1, user_pk_1, [latest_escrow_id] ) - latest_escrow_id = STEscrowContractUtils.get_latest_escrow_id(escrow_contract.address) - STEscrowContractUtils.cancel_escrow(escrow_contract.address, user_address_1, user_pk_1, [latest_escrow_id]) # Run target process block_number = web3.eth.block_number @@ -2486,21 +3314,33 @@ def test_normal_3_4(self, processor: Processor, db: Session, personal_info_contr # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 3 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 30 - 10 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 0 assert _position.exchange_balance == 30 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_2).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_2) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_2 assert _position.balance == 10 @@ -2513,17 +3353,29 @@ def test_normal_3_4(self, processor: Processor, db: Session, personal_info_contr # # Multi Token - def test_normal_4(self, processor: Processor, db: Session, personal_info_contract, ibet_security_token_escrow_contract): + def test_normal_4( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_security_token_escrow_contract, + ): escrow_contract = ibet_security_token_escrow_contract user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues bond token. token_contract1 = deploy_bond_token_contract( @@ -2564,15 +3416,50 @@ def test_normal_4(self, processor: Processor, db: Session, personal_info_contrac # Before run(consume accumulated events) processor.sync_new_logs() - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_contract1.address, issuer_address, issuer_private_key, [user_address_1, 30]) - STContractUtils.transfer(token_contract1.address, issuer_address, issuer_private_key, [user_address_2, 10]) + STContractUtils.transfer( + token_contract1.address, + issuer_address, + issuer_private_key, + [user_address_1, 30], + ) + STContractUtils.transfer( + token_contract1.address, + issuer_address, + issuer_private_key, + [user_address_2, 10], + ) - STContractUtils.transfer(token_contract2.address, issuer_address, issuer_private_key, [user_address_1, 40]) - STContractUtils.transfer(token_contract2.address, issuer_address, issuer_private_key, [user_address_2, 60]) + STContractUtils.transfer( + token_contract2.address, + issuer_address, + issuer_private_key, + [user_address_1, 40], + ) + STContractUtils.transfer( + token_contract2.address, + issuer_address, + issuer_private_key, + [user_address_2, 60], + ) # Run target process block_number = web3.eth.block_number @@ -2581,42 +3468,72 @@ def test_normal_4(self, processor: Processor, db: Session, personal_info_contrac # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 6 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).filter(IDXPosition.token_address == token_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .filter(IDXPosition.token_address == token_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 30 - 10 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).filter(IDXPosition.token_address == token_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .filter(IDXPosition.token_address == token_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 30 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_2).filter(IDXPosition.token_address == token_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_2) + .filter(IDXPosition.token_address == token_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_2 assert _position.balance == 10 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).filter(IDXPosition.token_address == token_address_2).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .filter(IDXPosition.token_address == token_address_2) + .first() + ) assert _position.token_address == token_address_2 assert _position.account_address == issuer_address assert _position.balance == 0 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).filter(IDXPosition.token_address == token_address_2).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .filter(IDXPosition.token_address == token_address_2) + .first() + ) assert _position.token_address == token_address_2 assert _position.account_address == user_address_1 assert _position.balance == 40 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_2).filter(IDXPosition.token_address == token_address_2).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_2) + .filter(IDXPosition.token_address == token_address_2) + .first() + ) assert _position.token_address == token_address_2 assert _position.account_address == user_address_2 assert _position.balance == 60 @@ -2631,7 +3548,9 @@ def test_normal_4(self, processor: Processor, db: Session, personal_info_contrac # If block number processed in batch is equal or greater than current block number, # batch logs "skip process". @mock.patch("web3.eth.Eth.block_number", 100) - def test_normal_5(self, processor: Processor, db: Session, caplog: pytest.LogCaptureFixture): + def test_normal_5( + self, processor: Processor, db: Session, caplog: pytest.LogCaptureFixture + ): _idx_position_bond_block_number = IDXPositionBondBlockNumber() _idx_position_bond_block_number.id = 1 _idx_position_bond_block_number.latest_block_number = 1000 @@ -2639,15 +3558,25 @@ def test_normal_5(self, processor: Processor, db: Session, caplog: pytest.LogCap db.commit() processor.sync_new_logs() - assert 1 == caplog.record_tuples.count((LOG.name, logging.DEBUG, "skip process")) + assert 1 == caplog.record_tuples.count( + (LOG.name, logging.DEBUG, "skip process") + ) # # Newly tokens added - def test_normal_6(self, processor: Processor, db: Session, personal_info_contract, ibet_security_token_escrow_contract): + def test_normal_6( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_security_token_escrow_contract, + ): escrow_contract = ibet_security_token_escrow_contract user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues bond token. token_contract1 = deploy_bond_token_contract( @@ -2708,18 +3637,23 @@ def test_normal_6(self, processor: Processor, db: Session, personal_info_contrac # # If exception occurs out of Processor except-catch, batch outputs logs in mainloop. - def test_error_1(self, main_func, db:Session, personal_info_contract, caplog: pytest.LogCaptureFixture): + def test_error_1( + self, + main_func, + db: Session, + personal_info_contract, + caplog: pytest.LogCaptureFixture, + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_bond_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -2732,25 +3666,45 @@ def test_error_1(self, main_func, db:Session, personal_info_contract, caplog: py db.commit() # Run mainloop once and fail with web3 utils error - with patch("batch.indexer_position_bond.INDEXER_SYNC_INTERVAL", None),\ - patch.object(web3.eth, "contract", side_effect=ServiceUnavailableError()), \ - pytest.raises(TypeError): + with patch( + "batch.indexer_position_bond.INDEXER_SYNC_INTERVAL", None + ), patch.object( + web3.eth, "contract", side_effect=ServiceUnavailableError() + ), pytest.raises( + TypeError + ): main_func() - assert 1 == caplog.record_tuples.count((LOG.name, logging.WARNING, "An external service was unavailable")) + assert 1 == caplog.record_tuples.count( + (LOG.name, logging.WARNING, "An external service was unavailable") + ) caplog.clear() # Run mainloop once and fail with sqlalchemy InvalidRequestError - with patch("batch.indexer_position_bond.INDEXER_SYNC_INTERVAL", None),\ - patch.object(Session, "query", side_effect=InvalidRequestError()), \ - pytest.raises(TypeError): + with patch( + "batch.indexer_position_bond.INDEXER_SYNC_INTERVAL", None + ), patch.object( + Session, "query", side_effect=InvalidRequestError() + ), pytest.raises( + TypeError + ): main_func() assert 1 == caplog.text.count("A database error has occurred") caplog.clear() # Run mainloop once and fail with connection to blockchain - with patch("batch.indexer_position_bond.INDEXER_SYNC_INTERVAL", None),\ - patch.object(ContractUtils, "call_function", side_effect=ConnectionError()), \ - pytest.raises(TypeError): + with patch( + "batch.indexer_position_bond.INDEXER_SYNC_INTERVAL", None + ), patch.object( + ContractUtils, "call_function", side_effect=ConnectionError() + ), pytest.raises( + TypeError + ): main_func() - assert 1 == caplog.record_tuples.count((LOG.name, logging.ERROR, "An exception occurred during event synchronization")) + assert 1 == caplog.record_tuples.count( + ( + LOG.name, + logging.ERROR, + "An exception occurred during event synchronization", + ) + ) caplog.clear() diff --git a/tests/test_batch_indexer_position_share.py b/tests/test_batch_indexer_position_share.py index ecc349ae..41afd5c2 100644 --- a/tests/test_batch_indexer_position_share.py +++ b/tests/test_batch_indexer_position_share.py @@ -16,39 +16,44 @@ SPDX-License-Identifier: Apache-2.0 """ -from eth_keyfile import decode_keyfile_json import logging +from unittest import mock +from unittest.mock import patch + import pytest +from eth_keyfile import decode_keyfile_json from sqlalchemy.exc import InvalidRequestError from sqlalchemy.orm import Session -from unittest import mock -from unittest.mock import patch from app.exceptions import ServiceUnavailableError +from app.model.blockchain import IbetShareContract +from app.model.blockchain.tx_params.ibet_share import ( + UpdateParams as IbetShareUpdateParams, +) from app.model.db import ( - Token, - TokenType, - IDXPosition, + IDXLock, IDXLockedPosition, + IDXPosition, IDXPositionShareBlockNumber, - IDXLock, IDXUnlock, Notification, - NotificationType + NotificationType, + Token, + TokenType, ) -from app.model.blockchain import IbetShareContract -from app.model.blockchain.tx_params.ibet_share import UpdateParams as IbetShareUpdateParams -from app.utils.web3_utils import Web3Wrapper from app.utils.contract_utils import ContractUtils -from batch.indexer_position_share import Processor, LOG, main +from app.utils.web3_utils import Web3Wrapper +from batch.indexer_position_share import LOG, Processor, main from config import CHAIN_ID, TX_GAS_LIMIT, ZERO_ADDRESS from tests.account_config import config_eth_account +from tests.utils.contract_utils import IbetExchangeContractTestUtils from tests.utils.contract_utils import ( IbetSecurityTokenContractTestUtils as STContractUtils, - IbetExchangeContractTestUtils, - PersonalInfoContractTestUtils, +) +from tests.utils.contract_utils import ( IbetSecurityTokenEscrowContractTestUtils as STEscrowContractUtils, ) +from tests.utils.contract_utils import PersonalInfoContractTestUtils web3 = Web3Wrapper() @@ -75,11 +80,13 @@ def processor(db, caplog: pytest.LogCaptureFixture): LOG.setLevel(default_log_level) -def deploy_share_token_contract(address, - private_key, - personal_info_contract_address, - tradable_exchange_contract_address=None, - transfer_approval_required=None): +def deploy_share_token_contract( + address, + private_key, + personal_info_contract_address, + tradable_exchange_contract_address=None, + transfer_approval_required=None, +): arguments = [ "token.name", "token.symbol", @@ -89,7 +96,7 @@ def deploy_share_token_contract(address, "token.dividend_record_date", "token.dividend_payment_date", "token.cancellation_date", - 30 + 30, ] share_contract = IbetShareContract() token_address, _, _ = share_contract.create(arguments, address, private_key) @@ -98,17 +105,16 @@ def deploy_share_token_contract(address, transferable=True, personal_info_contract_address=personal_info_contract_address, tradable_exchange_contract_address=tradable_exchange_contract_address, - transfer_approval_required=transfer_approval_required + transfer_approval_required=transfer_approval_required, ), tx_from=address, - private_key=private_key + private_key=private_key, ) return ContractUtils.get_contract("IbetShare", token_address) class TestProcessor: - ########################################################################### # Normal Case ########################################################################### @@ -117,7 +123,9 @@ class TestProcessor: # Single Token # No event logs # not issue token - def test_normal_1_1(self, processor: Processor, db: Session, personal_info_contract): + def test_normal_1_1( + self, processor: Processor, db: Session, personal_info_contract + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] @@ -157,18 +165,19 @@ def test_normal_1_1(self, processor: Processor, db: Session, personal_info_contr # Single Token # No event logs # issued token - def test_normal_1_2(self, processor: Processor, db: Session, personal_info_contract): + def test_normal_1_2( + self, processor: Processor, db: Session, personal_info_contract + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract_1 = deploy_share_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_share_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_SHARE.value @@ -211,7 +220,11 @@ def test_normal_1_2(self, processor: Processor, db: Session, personal_info_contr # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 1 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 @@ -226,20 +239,21 @@ def test_normal_1_2(self, processor: Processor, db: Session, personal_info_contr # Single Token # Single event logs # - Issue - def test_normal_2_1(self, processor: Processor, db: Session, personal_info_contract): + def test_normal_2_1( + self, processor: Processor, db: Session, personal_info_contract + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] # Prepare data : Token - token_contract_1 = deploy_share_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_share_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_SHARE.value @@ -271,12 +285,16 @@ def test_normal_2_1(self, processor: Processor, db: Session, personal_info_contr db.commit() # Issue - tx = token_contract_1.functions.issueFrom(user_address_1, ZERO_ADDRESS, 40).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = token_contract_1.functions.issueFrom( + user_address_1, ZERO_ADDRESS, 40 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -286,14 +304,22 @@ def test_normal_2_1(self, processor: Processor, db: Session, personal_info_contr # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 2 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 40 @@ -308,20 +334,21 @@ def test_normal_2_1(self, processor: Processor, db: Session, personal_info_contr # Single Token # Single event logs # - Transfer(to account) - def test_normal_2_2_1(self, processor: Processor, db: Session, personal_info_contract): + def test_normal_2_2_1( + self, processor: Processor, db: Session, personal_info_contract + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] # Prepare data : Token - token_contract_1 = deploy_share_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_share_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_SHARE.value @@ -353,12 +380,16 @@ def test_normal_2_2_1(self, processor: Processor, db: Session, personal_info_con db.commit() # Transfer - tx = token_contract_1.functions.transferFrom(issuer_address, user_address_1, 40).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = token_contract_1.functions.transferFrom( + issuer_address, user_address_1, 40 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -368,14 +399,22 @@ def test_normal_2_2_1(self, processor: Processor, db: Session, personal_info_con # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 2 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 40 @@ -390,19 +429,26 @@ def test_normal_2_2_1(self, processor: Processor, db: Session, personal_info_con # Single Token # Single event logs # - Transfer(to DEX) - def test_normal_2_2_2(self, processor: Processor, db: Session, personal_info_contract, ibet_escrow_contract): + def test_normal_2_2_2( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_escrow_contract, + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract_1 = deploy_share_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address, - ibet_escrow_contract.address) + token_contract_1 = deploy_share_token_contract( + issuer_address, + issuer_private_key, + personal_info_contract.address, + ibet_escrow_contract.address, + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_SHARE.value @@ -436,12 +482,14 @@ def test_normal_2_2_2(self, processor: Processor, db: Session, personal_info_con # Deposit tx = token_contract_1.functions.transferFrom( issuer_address, ibet_escrow_contract.address, 40 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -451,7 +499,11 @@ def test_normal_2_2_2(self, processor: Processor, db: Session, personal_info_con # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 1 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 @@ -466,21 +518,28 @@ def test_normal_2_2_2(self, processor: Processor, db: Session, personal_info_con # Single Token # Single event logs # - Transfer(HolderChanged in DEX) - def test_normal_2_2_3(self, processor: Processor, db: Session, personal_info_contract, ibet_escrow_contract): + def test_normal_2_2_3( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_escrow_contract, + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] # Prepare data : Token - token_contract_1 = deploy_share_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address, - ibet_escrow_contract.address) + token_contract_1 = deploy_share_token_contract( + issuer_address, + issuer_private_key, + personal_info_contract.address, + ibet_escrow_contract.address, + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_SHARE.value @@ -514,19 +573,25 @@ def test_normal_2_2_3(self, processor: Processor, db: Session, personal_info_con # Deposit tx = token_contract_1.functions.transferFrom( issuer_address, ibet_escrow_contract.address, 40 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Before run(consume accumulated events) processor.sync_new_logs() _position_list = db.query(IDXPosition).all() assert len(_position_list) == 1 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 @@ -537,21 +602,26 @@ def test_normal_2_2_3(self, processor: Processor, db: Session, personal_info_con # Holder Change tx = ibet_escrow_contract.functions.createEscrow( token_contract_1.address, user_address_1, 30, issuer_address, "" - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) escrow_id = ContractUtils.call_function( - ibet_escrow_contract, "latestEscrowId", ()) - tx = ibet_escrow_contract.functions.finishEscrow(escrow_id).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ibet_escrow_contract, "latestEscrowId", () + ) + tx = ibet_escrow_contract.functions.finishEscrow(escrow_id).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -565,14 +635,22 @@ def test_normal_2_2_3(self, processor: Processor, db: Session, personal_info_con # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 2 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 assert _position.exchange_balance == 40 - 30 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 0 @@ -587,18 +665,19 @@ def test_normal_2_2_3(self, processor: Processor, db: Session, personal_info_con # Single Token # Single event logs # - Lock - def test_normal_2_3(self, processor: Processor, db: Session, personal_info_contract): + def test_normal_2_3( + self, processor: Processor, db: Session, personal_info_contract + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract_1 = deploy_share_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_share_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_SHARE.value @@ -631,15 +710,15 @@ def test_normal_2_3(self, processor: Processor, db: Session, personal_info_contr # Lock tx = token_contract_1.functions.lock( - issuer_address, - 40, - '{"message": "locked1"}' - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + issuer_address, 40, '{"message": "locked1"}' + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -650,9 +729,11 @@ def test_normal_2_3(self, processor: Processor, db: Session, personal_info_contr _position_list = db.query(IDXPosition).all() assert len(_position_list) == 1 - _position = db.query(IDXPosition).\ - filter(IDXPosition.account_address == issuer_address).\ - first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 @@ -660,10 +741,12 @@ def test_normal_2_3(self, processor: Processor, db: Session, personal_info_contr assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _locked_position = db.query(IDXLockedPosition).\ - filter(IDXLockedPosition.token_address == token_address_1).\ - filter(IDXLockedPosition.account_address == issuer_address).\ - first() + _locked_position = ( + db.query(IDXLockedPosition) + .filter(IDXLockedPosition.token_address == token_address_1) + .filter(IDXLockedPosition.account_address == issuer_address) + .first() + ) assert _locked_position.token_address == token_address_1 assert _locked_position.lock_address == issuer_address assert _locked_position.account_address == issuer_address @@ -694,9 +777,7 @@ def test_normal_2_3(self, processor: Processor, db: Session, personal_info_contr "account_address": issuer_address, "lock_address": issuer_address, "value": 40, - "data": { - "message": "locked1" - } + "data": {"message": "locked1"}, } _idx_position_share_block_number = db.query(IDXPositionShareBlockNumber).first() @@ -707,18 +788,19 @@ def test_normal_2_3(self, processor: Processor, db: Session, personal_info_contr # Single Token # Single event logs # - Unlock - def test_normal_2_4(self, processor: Processor, db: Session, personal_info_contract): + def test_normal_2_4( + self, processor: Processor, db: Session, personal_info_contract + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract_1 = deploy_share_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_share_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_SHARE.value @@ -751,15 +833,15 @@ def test_normal_2_4(self, processor: Processor, db: Session, personal_info_contr # Lock tx = token_contract_1.functions.lock( - issuer_address, - 40, - '{"message": "locked1"}' - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + issuer_address, 40, '{"message": "locked1"}' + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Before run(consume accumulated events) @@ -768,9 +850,11 @@ def test_normal_2_4(self, processor: Processor, db: Session, personal_info_contr _position_list = db.query(IDXPosition).all() assert len(_position_list) == 1 - _position = db.query(IDXPosition).\ - filter(IDXPosition.account_address == issuer_address).\ - first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 @@ -780,16 +864,15 @@ def test_normal_2_4(self, processor: Processor, db: Session, personal_info_contr # Unlock tx = token_contract_1.functions.unlock( - issuer_address, - issuer_address, - 30, - '{"message": "unlocked1"}' - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + issuer_address, issuer_address, 30, '{"message": "unlocked1"}' + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -804,9 +887,11 @@ def test_normal_2_4(self, processor: Processor, db: Session, personal_info_contr _position_list = db.query(IDXPosition).all() assert len(_position_list) == 1 - _position = db.query(IDXPosition).\ - filter(IDXPosition.account_address == issuer_address).\ - first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 + 30 @@ -814,10 +899,12 @@ def test_normal_2_4(self, processor: Processor, db: Session, personal_info_contr assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _locked_position = db.query(IDXLockedPosition).\ - filter(IDXLockedPosition.token_address == token_address_1).\ - filter(IDXLockedPosition.account_address == issuer_address).\ - first() + _locked_position = ( + db.query(IDXLockedPosition) + .filter(IDXLockedPosition.token_address == token_address_1) + .filter(IDXLockedPosition.account_address == issuer_address) + .first() + ) assert _locked_position.token_address == token_address_1 assert _locked_position.lock_address == issuer_address assert _locked_position.account_address == issuer_address @@ -844,9 +931,7 @@ def test_normal_2_4(self, processor: Processor, db: Session, personal_info_contr assert _unlock1.account_address == issuer_address assert _unlock1.recipient_address == issuer_address assert _unlock1.value == 30 - assert _unlock1.data == { - "message": "unlocked1" - } + assert _unlock1.data == {"message": "unlocked1"} _notification_list = db.query(Notification).order_by(Notification.created).all() assert len(_notification_list) == 2 @@ -862,9 +947,7 @@ def test_normal_2_4(self, processor: Processor, db: Session, personal_info_contr "account_address": issuer_address, "lock_address": issuer_address, "value": 40, - "data": { - "message": "locked1" - } + "data": {"message": "locked1"}, } _notification1 = _notification_list[1] @@ -879,9 +962,7 @@ def test_normal_2_4(self, processor: Processor, db: Session, personal_info_contr "lock_address": issuer_address, "recipient_address": issuer_address, "value": 30, - "data": { - "message": "unlocked1" - } + "data": {"message": "unlocked1"}, } _idx_position_share_block_number = db.query(IDXPositionShareBlockNumber).first() @@ -892,18 +973,19 @@ def test_normal_2_4(self, processor: Processor, db: Session, personal_info_contr # Single Token # Single event logs # - Redeem - def test_normal_2_5(self, processor: Processor, db: Session, personal_info_contract): + def test_normal_2_5( + self, processor: Processor, db: Session, personal_info_contract + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract_1 = deploy_share_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_share_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_SHARE.value @@ -935,12 +1017,16 @@ def test_normal_2_5(self, processor: Processor, db: Session, personal_info_contr db.commit() # Redeem - tx = token_contract_1.functions.redeemFrom(issuer_address, ZERO_ADDRESS, 40).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = token_contract_1.functions.redeemFrom( + issuer_address, ZERO_ADDRESS, 40 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -950,7 +1036,11 @@ def test_normal_2_5(self, processor: Processor, db: Session, personal_info_contr # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 1 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 @@ -965,25 +1055,27 @@ def test_normal_2_5(self, processor: Processor, db: Session, personal_info_contr # Single Token # Single event logs # - ApplyForTransfer - def test_normal_2_6(self, processor: Processor, db: Session, personal_info_contract): + def test_normal_2_6( + self, processor: Processor, db: Session, personal_info_contract + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract_1 = deploy_share_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address, - transfer_approval_required=True) + token_contract_1 = deploy_share_token_contract( + issuer_address, + issuer_private_key, + personal_info_contract.address, + transfer_approval_required=True, + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_SHARE.value @@ -1015,16 +1107,22 @@ def test_normal_2_6(self, processor: Processor, db: Session, personal_info_contr db.commit() # ApplyForTransfer - PersonalInfoContractTestUtils.register(personal_info_contract.address, - user_address_1, - user_private_key_1, - [issuer_address, "test"]) - tx = token_contract_1.functions.applyForTransfer(user_address_1, 40, "").build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_private_key_1, + [issuer_address, "test"], + ) + tx = token_contract_1.functions.applyForTransfer( + user_address_1, 40, "" + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -1034,7 +1132,11 @@ def test_normal_2_6(self, processor: Processor, db: Session, personal_info_contr # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 1 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 @@ -1049,25 +1151,27 @@ def test_normal_2_6(self, processor: Processor, db: Session, personal_info_contr # Single Token # Single event logs # - CancelTransfer - def test_normal_2_7(self, processor: Processor, db: Session, personal_info_contract): + def test_normal_2_7( + self, processor: Processor, db: Session, personal_info_contract + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract_1 = deploy_share_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address, - transfer_approval_required=True) + token_contract_1 = deploy_share_token_contract( + issuer_address, + issuer_private_key, + personal_info_contract.address, + transfer_approval_required=True, + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_SHARE.value @@ -1099,23 +1203,33 @@ def test_normal_2_7(self, processor: Processor, db: Session, personal_info_contr db.commit() # ApplyForTransfer - PersonalInfoContractTestUtils.register(personal_info_contract.address, - user_address_1, - user_private_key_1, - [issuer_address, "test"]) - tx = token_contract_1.functions.applyForTransfer(user_address_1, 40, "").build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_private_key_1, + [issuer_address, "test"], + ) + tx = token_contract_1.functions.applyForTransfer( + user_address_1, 40, "" + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Before run(consume accumulated events) processor.sync_new_logs() _position_list = db.query(IDXPosition).all() assert len(_position_list) == 1 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 @@ -1124,12 +1238,14 @@ def test_normal_2_7(self, processor: Processor, db: Session, personal_info_contr assert _position.pending_transfer == 40 # CancelTransfer - tx = token_contract_1.functions.cancelTransfer(0, "").build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = token_contract_1.functions.cancelTransfer(0, "").build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -1143,7 +1259,11 @@ def test_normal_2_7(self, processor: Processor, db: Session, personal_info_contr # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 1 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 @@ -1158,25 +1278,27 @@ def test_normal_2_7(self, processor: Processor, db: Session, personal_info_contr # Single Token # Single event logs # - ApproveTransfer - def test_normal_2_8(self, processor: Processor, db: Session, personal_info_contract): + def test_normal_2_8( + self, processor: Processor, db: Session, personal_info_contract + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract_1 = deploy_share_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address, - transfer_approval_required=True) + token_contract_1 = deploy_share_token_contract( + issuer_address, + issuer_private_key, + personal_info_contract.address, + transfer_approval_required=True, + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_SHARE.value @@ -1208,23 +1330,33 @@ def test_normal_2_8(self, processor: Processor, db: Session, personal_info_contr db.commit() # ApplyForTransfer - PersonalInfoContractTestUtils.register(personal_info_contract.address, - user_address_1, - user_private_key_1, - [issuer_address, "test"]) - tx = token_contract_1.functions.applyForTransfer(user_address_1, 40, "").build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_private_key_1, + [issuer_address, "test"], + ) + tx = token_contract_1.functions.applyForTransfer( + user_address_1, 40, "" + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Before run(consume accumulated events) processor.sync_new_logs() _position_list = db.query(IDXPosition).all() assert len(_position_list) == 1 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 @@ -1233,12 +1365,14 @@ def test_normal_2_8(self, processor: Processor, db: Session, personal_info_contr assert _position.pending_transfer == 40 # ApproveTransfer - tx = token_contract_1.functions.approveTransfer(0, "").build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = token_contract_1.functions.approveTransfer(0, "").build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -1252,14 +1386,22 @@ def test_normal_2_8(self, processor: Processor, db: Session, personal_info_contr # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 2 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 40 @@ -1274,19 +1416,26 @@ def test_normal_2_8(self, processor: Processor, db: Session, personal_info_contr # Single Token # Single event logs # - IbetExchange: NewOrder - def test_normal_2_9_1(self, processor: Processor, db: Session, personal_info_contract, ibet_exchange_contract): + def test_normal_2_9_1( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_exchange_contract, + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract_1 = deploy_share_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address, - tradable_exchange_contract_address=ibet_exchange_contract.address) + token_contract_1 = deploy_share_token_contract( + issuer_address, + issuer_private_key, + personal_info_contract.address, + tradable_exchange_contract_address=ibet_exchange_contract.address, + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_SHARE.value @@ -1320,19 +1469,25 @@ def test_normal_2_9_1(self, processor: Processor, db: Session, personal_info_con # Deposit tx = token_contract_1.functions.transferFrom( issuer_address, ibet_exchange_contract.address, 40 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Before run(consume accumulated events) processor.sync_new_logs() _position_list = db.query(IDXPosition).all() assert len(_position_list) == 1 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 @@ -1343,12 +1498,14 @@ def test_normal_2_9_1(self, processor: Processor, db: Session, personal_info_con # NewOrder(Sell) tx = ibet_exchange_contract.functions.createOrder( token_address_1, 30, 10000, False, issuer_address - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -1362,7 +1519,11 @@ def test_normal_2_9_1(self, processor: Processor, db: Session, personal_info_con # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 1 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 @@ -1377,17 +1538,29 @@ def test_normal_2_9_1(self, processor: Processor, db: Session, personal_info_con # Single Token # Single event logs # - IbetExchange: CancelOrder - def test_normal_2_9_2(self, processor: Processor, db: Session, personal_info_contract, ibet_exchange_contract): + def test_normal_2_9_2( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_exchange_contract, + ): exchange_contract = ibet_exchange_contract user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues share token. token_contract = deploy_share_token_contract( @@ -1411,20 +1584,57 @@ def test_normal_2_9_2(self, processor: Processor, db: Session, personal_info_con # Before run(consume accumulated events) processor.sync_new_logs() - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 30]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_2, 10]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 30], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, 10], + ) # NewOrder(Sell) & CancelOrder - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [exchange_contract.address, 10]) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [exchange_contract.address, 10], + ) IbetExchangeContractTestUtils.create_order( - exchange_contract.address, user_address_1, user_pk_1, [token_contract.address, 10, 100, False, issuer_address] + exchange_contract.address, + user_address_1, + user_pk_1, + [token_contract.address, 10, 100, False, issuer_address], + ) + latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id( + exchange_contract.address + ) + IbetExchangeContractTestUtils.cancel_order( + exchange_contract.address, user_address_1, user_pk_1, [latest_order_id] ) - latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id(exchange_contract.address) - IbetExchangeContractTestUtils.cancel_order(exchange_contract.address, user_address_1, user_pk_1, [latest_order_id]) # Run target process block_number = web3.eth.block_number @@ -1433,21 +1643,33 @@ def test_normal_2_9_2(self, processor: Processor, db: Session, personal_info_con # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 3 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 30 - 10 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 30 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_2).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_2) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_2 assert _position.balance == 10 @@ -1462,17 +1684,29 @@ def test_normal_2_9_2(self, processor: Processor, db: Session, personal_info_con # Single Token # Single event logs # - IbetExchange: ForceCancelOrder - def test_normal_2_9_3(self, processor: Processor, db: Session, personal_info_contract, ibet_exchange_contract): + def test_normal_2_9_3( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_exchange_contract, + ): exchange_contract = ibet_exchange_contract user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues share token. token_contract = deploy_share_token_contract( @@ -1496,20 +1730,60 @@ def test_normal_2_9_3(self, processor: Processor, db: Session, personal_info_con # Before run(consume accumulated events) processor.sync_new_logs() - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 30]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_2, 10]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 30], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, 10], + ) # NewOrder(Sell) & ForceCancelOrder - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [exchange_contract.address, 10]) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [exchange_contract.address, 10], + ) IbetExchangeContractTestUtils.create_order( - exchange_contract.address, user_address_1, user_pk_1, [token_contract.address, 10, 100, False, issuer_address] + exchange_contract.address, + user_address_1, + user_pk_1, + [token_contract.address, 10, 100, False, issuer_address], + ) + latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id( + exchange_contract.address + ) + IbetExchangeContractTestUtils.force_cancel_order( + exchange_contract.address, + issuer_address, + issuer_private_key, + [latest_order_id], ) - latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id(exchange_contract.address) - IbetExchangeContractTestUtils.force_cancel_order(exchange_contract.address, issuer_address, issuer_private_key, [latest_order_id]) # Run target process block_number = web3.eth.block_number @@ -1518,21 +1792,33 @@ def test_normal_2_9_3(self, processor: Processor, db: Session, personal_info_con # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 3 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 30 - 10 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 30 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_2).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_2) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_2 assert _position.balance == 10 @@ -1547,17 +1833,29 @@ def test_normal_2_9_3(self, processor: Processor, db: Session, personal_info_con # Single Token # Single event logs # - IbetExchange: Agree - def test_normal_2_9_4(self, processor: Processor, db: Session, personal_info_contract, ibet_exchange_contract): + def test_normal_2_9_4( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_exchange_contract, + ): exchange_contract = ibet_exchange_contract user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues share token. token_contract = deploy_share_token_contract( @@ -1581,20 +1879,60 @@ def test_normal_2_9_4(self, processor: Processor, db: Session, personal_info_con # Before run(consume accumulated events) processor.sync_new_logs() - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 30]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_2, 10]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 30], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, 10], + ) # NewOrder(Sell) & ExecuteOrder - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [exchange_contract.address, 10]) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [exchange_contract.address, 10], + ) IbetExchangeContractTestUtils.create_order( - exchange_contract.address, user_address_1, user_pk_1, [token_contract.address, 10, 100, False, issuer_address] + exchange_contract.address, + user_address_1, + user_pk_1, + [token_contract.address, 10, 100, False, issuer_address], + ) + latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id( + exchange_contract.address + ) + IbetExchangeContractTestUtils.execute_order( + exchange_contract.address, + user_address_2, + user_pk_2, + [latest_order_id, 10, True], ) - latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id(exchange_contract.address) - IbetExchangeContractTestUtils.execute_order(exchange_contract.address, user_address_2, user_pk_2, [latest_order_id, 10, True]) # Run target process block_number = web3.eth.block_number @@ -1603,21 +1941,33 @@ def test_normal_2_9_4(self, processor: Processor, db: Session, personal_info_con # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 3 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 30 - 10 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 20 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 10 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_2).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_2) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_2 assert _position.balance == 10 @@ -1632,17 +1982,29 @@ def test_normal_2_9_4(self, processor: Processor, db: Session, personal_info_con # Single Token # Single event logs # - IbetExchange: SettlementOK - def test_normal_2_9_5(self, processor: Processor, db: Session, personal_info_contract, ibet_exchange_contract): + def test_normal_2_9_5( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_exchange_contract, + ): exchange_contract = ibet_exchange_contract user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues share token. token_contract = deploy_share_token_contract( @@ -1666,23 +2028,68 @@ def test_normal_2_9_5(self, processor: Processor, db: Session, personal_info_con # Before run(consume accumulated events) processor.sync_new_logs() - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 30]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_2, 10]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 30], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, 10], + ) # NewOrder(Sell) & ExecuteOrder & ConfirmAgreement - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [exchange_contract.address, 10]) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [exchange_contract.address, 10], + ) IbetExchangeContractTestUtils.create_order( - exchange_contract.address, user_address_1, user_pk_1, [token_contract.address, 10, 100, False, issuer_address] + exchange_contract.address, + user_address_1, + user_pk_1, + [token_contract.address, 10, 100, False, issuer_address], + ) + latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id( + exchange_contract.address + ) + IbetExchangeContractTestUtils.execute_order( + exchange_contract.address, + user_address_2, + user_pk_2, + [latest_order_id, 10, True], + ) + latest_agreement_id = IbetExchangeContractTestUtils.get_latest_agreementid( + exchange_contract.address, latest_order_id ) - latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id(exchange_contract.address) - IbetExchangeContractTestUtils.execute_order(exchange_contract.address, user_address_2, user_pk_2, [latest_order_id, 10, True]) - latest_agreement_id = IbetExchangeContractTestUtils.get_latest_agreementid(exchange_contract.address, latest_order_id) IbetExchangeContractTestUtils.confirm_agreement( - exchange_contract.address, issuer_address, issuer_private_key, [latest_order_id, latest_agreement_id] + exchange_contract.address, + issuer_address, + issuer_private_key, + [latest_order_id, latest_agreement_id], ) # Run target process @@ -1692,21 +2099,33 @@ def test_normal_2_9_5(self, processor: Processor, db: Session, personal_info_con # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 3 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 30 - 10 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 20 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_2).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_2) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_2 assert _position.balance == 20 @@ -1721,17 +2140,29 @@ def test_normal_2_9_5(self, processor: Processor, db: Session, personal_info_con # Single Token # Single event logs # - IbetExchange: SettlementNG - def test_normal_2_9_6(self, processor: Processor, db: Session, personal_info_contract, ibet_exchange_contract): + def test_normal_2_9_6( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_exchange_contract, + ): exchange_contract = ibet_exchange_contract user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues share token. token_contract = deploy_share_token_contract( @@ -1755,23 +2186,68 @@ def test_normal_2_9_6(self, processor: Processor, db: Session, personal_info_con # Before run(consume accumulated events) processor.sync_new_logs() - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 30]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_2, 10]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 30], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, 10], + ) # NewOrder(Sell) & ExecuteOrder & CancelAgreement - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [exchange_contract.address, 10]) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [exchange_contract.address, 10], + ) IbetExchangeContractTestUtils.create_order( - exchange_contract.address, user_address_1, user_pk_1, [token_contract.address, 10, 100, False, issuer_address] + exchange_contract.address, + user_address_1, + user_pk_1, + [token_contract.address, 10, 100, False, issuer_address], + ) + latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id( + exchange_contract.address + ) + IbetExchangeContractTestUtils.execute_order( + exchange_contract.address, + user_address_2, + user_pk_2, + [latest_order_id, 10, True], + ) + latest_agreement_id = IbetExchangeContractTestUtils.get_latest_agreementid( + exchange_contract.address, latest_order_id ) - latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id(exchange_contract.address) - IbetExchangeContractTestUtils.execute_order(exchange_contract.address, user_address_2, user_pk_2, [latest_order_id, 10, True]) - latest_agreement_id = IbetExchangeContractTestUtils.get_latest_agreementid(exchange_contract.address, latest_order_id) IbetExchangeContractTestUtils.cancel_agreement( - exchange_contract.address, issuer_address, issuer_private_key, [latest_order_id, latest_agreement_id] + exchange_contract.address, + issuer_address, + issuer_private_key, + [latest_order_id, latest_agreement_id], ) # Run target process @@ -1781,21 +2257,33 @@ def test_normal_2_9_6(self, processor: Processor, db: Session, personal_info_con # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 3 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 30 - 10 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 20 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 10 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_2).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_2) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_2 assert _position.balance == 10 @@ -1810,21 +2298,28 @@ def test_normal_2_9_6(self, processor: Processor, db: Session, personal_info_con # Single Token # Single event logs # - IbetSecurityTokenEscrow: EscrowCreated - def test_normal_2_10_1(self, processor: Processor, db: Session, personal_info_contract, ibet_security_token_escrow_contract): + def test_normal_2_10_1( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_security_token_escrow_contract, + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] # Prepare data : Token - token_contract_1 = deploy_share_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address, - ibet_security_token_escrow_contract.address) + token_contract_1 = deploy_share_token_contract( + issuer_address, + issuer_private_key, + personal_info_contract.address, + ibet_security_token_escrow_contract.address, + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_SHARE.value @@ -1858,19 +2353,25 @@ def test_normal_2_10_1(self, processor: Processor, db: Session, personal_info_co # Deposit tx = token_contract_1.functions.transferFrom( issuer_address, ibet_security_token_escrow_contract.address, 40 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Before run(consume accumulated events) processor.sync_new_logs() _position_list = db.query(IDXPosition).all() assert len(_position_list) == 1 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 @@ -1881,12 +2382,14 @@ def test_normal_2_10_1(self, processor: Processor, db: Session, personal_info_co # EscrowCreated tx = ibet_security_token_escrow_contract.functions.createEscrow( token_contract_1.address, user_address_1, 30, issuer_address, "", "" - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -1900,7 +2403,11 @@ def test_normal_2_10_1(self, processor: Processor, db: Session, personal_info_co # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 1 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 @@ -1915,17 +2422,29 @@ def test_normal_2_10_1(self, processor: Processor, db: Session, personal_info_co # Single Token # Single event logs # - IbetSecurityTokenEscrow: EscrowCanceled - def test_normal_2_10_2(self, processor: Processor, db: Session, personal_info_contract, ibet_security_token_escrow_contract): + def test_normal_2_10_2( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_security_token_escrow_contract, + ): escrow_contract = ibet_security_token_escrow_contract user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues share token. token_contract = deploy_share_token_contract( @@ -1949,21 +2468,58 @@ def test_normal_2_10_2(self, processor: Processor, db: Session, personal_info_co # Before run(consume accumulated events) processor.sync_new_logs() - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 30]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_2, 10]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 30], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, 10], + ) # CreateEscrow & CancelEscrow - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [escrow_contract.address, 30]) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [escrow_contract.address, 30], + ) STEscrowContractUtils.create_escrow( - escrow_contract.address, user_address_1, user_pk_1, [token_contract.address, user_address_2, 10, issuer_address, "", ""] + escrow_contract.address, + user_address_1, + user_pk_1, + [token_contract.address, user_address_2, 10, issuer_address, "", ""], + ) + latest_escrow_id = STEscrowContractUtils.get_latest_escrow_id( + escrow_contract.address + ) + STEscrowContractUtils.cancel_escrow( + escrow_contract.address, user_address_1, user_pk_1, [latest_escrow_id] ) - latest_escrow_id = STEscrowContractUtils.get_latest_escrow_id(escrow_contract.address) - STEscrowContractUtils.cancel_escrow(escrow_contract.address, user_address_1, user_pk_1, [latest_escrow_id]) # Run target process block_number = web3.eth.block_number @@ -1972,21 +2528,33 @@ def test_normal_2_10_2(self, processor: Processor, db: Session, personal_info_co # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 3 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 30 - 10 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 0 assert _position.exchange_balance == 30 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_2).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_2) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_2 assert _position.balance == 10 @@ -2001,17 +2569,29 @@ def test_normal_2_10_2(self, processor: Processor, db: Session, personal_info_co # Single Token # Single event logs # - IbetSecurityTokenEscrow: EscrowFinished - def test_normal_2_10_3(self, processor: Processor, db: Session, personal_info_contract, ibet_security_token_escrow_contract): + def test_normal_2_10_3( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_security_token_escrow_contract, + ): escrow_contract = ibet_security_token_escrow_contract user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues share token. token_contract = deploy_share_token_contract( @@ -2035,22 +2615,60 @@ def test_normal_2_10_3(self, processor: Processor, db: Session, personal_info_co # Before run(consume accumulated events) processor.sync_new_logs() - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 30]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_2, 10]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 30], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, 10], + ) # CreateEscrow & CancelEscrow - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [escrow_contract.address, 30]) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [escrow_contract.address, 30], + ) STEscrowContractUtils.create_escrow( - escrow_contract.address, user_address_1, user_pk_1, [token_contract.address, user_address_2, 10, issuer_address, "", ""] + escrow_contract.address, + user_address_1, + user_pk_1, + [token_contract.address, user_address_2, 10, issuer_address, "", ""], + ) + latest_escrow_id = STEscrowContractUtils.get_latest_escrow_id( + escrow_contract.address ) - latest_escrow_id = STEscrowContractUtils.get_latest_escrow_id(escrow_contract.address) STEscrowContractUtils.finish_escrow( - ibet_security_token_escrow_contract.address, issuer_address, issuer_private_key, [latest_escrow_id] + ibet_security_token_escrow_contract.address, + issuer_address, + issuer_private_key, + [latest_escrow_id], ) # Run target process block_number = web3.eth.block_number @@ -2059,21 +2677,33 @@ def test_normal_2_10_3(self, processor: Processor, db: Session, personal_info_co # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 3 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 30 - 10 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 0 assert _position.exchange_balance == 20 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_2).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_2) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_2 assert _position.balance == 10 @@ -2088,30 +2718,29 @@ def test_normal_2_10_3(self, processor: Processor, db: Session, personal_info_co # Single Token # Multi event logs # - Transfer(twice) - def test_normal_3_1(self, processor: Processor, db: Session, personal_info_contract): + def test_normal_3_1( + self, processor: Processor, db: Session, personal_info_contract + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] user_private_key_2 = decode_keyfile_json( - raw_keyfile_json=user_3["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract_1 = deploy_share_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_share_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_SHARE.value @@ -2146,29 +2775,39 @@ def test_normal_3_1(self, processor: Processor, db: Session, personal_info_contr processor.sync_new_logs() # Transfer: 1st - tx = token_contract_1.functions.transferFrom(issuer_address, user_address_1, 40).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = token_contract_1.functions.transferFrom( + issuer_address, user_address_1, 40 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # Transfer: 2nd - PersonalInfoContractTestUtils.register(personal_info_contract.address, - user_address_1, - user_private_key_1, - [issuer_address, "test"]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, - user_address_2, - user_private_key_2, - [issuer_address, "test"]) - tx = token_contract_1.functions.transfer(user_address_2, 10).build_transaction({ - "chainId": CHAIN_ID, - "from": user_address_1, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_private_key_1, + [issuer_address, "test"], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_private_key_2, + [issuer_address, "test"], + ) + tx = token_contract_1.functions.transfer(user_address_2, 10).build_transaction( + { + "chainId": CHAIN_ID, + "from": user_address_1, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, user_private_key_1) # Run target process @@ -2178,21 +2817,33 @@ def test_normal_3_1(self, processor: Processor, db: Session, personal_info_contr # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 3 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 40 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 40 - 10 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_2).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_2) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_2 assert _position.balance == 10 @@ -2207,30 +2858,39 @@ def test_normal_3_1(self, processor: Processor, db: Session, personal_info_contr # Single Token # Multi event logs # - Transfer(BulkTransfer) - def test_normal_3_2(self, processor: Processor, db: Session, personal_info_contract): + def test_normal_3_2( + self, processor: Processor, db: Session, personal_info_contract + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) user_4 = config_eth_account("user4") user_address_3 = user_4["address"] - user_pk_3 = decode_keyfile_json(raw_keyfile_json=user_4["keyfile_json"], password="password".encode("utf-8")) + user_pk_3 = decode_keyfile_json( + raw_keyfile_json=user_4["keyfile_json"], password="password".encode("utf-8") + ) user_5 = config_eth_account("user5") user_address_4 = user_5["address"] - user_pk_4 = decode_keyfile_json(raw_keyfile_json=user_5["keyfile_json"], password="password".encode("utf-8")) + user_pk_4 = decode_keyfile_json( + raw_keyfile_json=user_5["keyfile_json"], password="password".encode("utf-8") + ) # Prepare data : Token - token_contract_1 = deploy_share_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_share_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_SHARE.value @@ -2254,32 +2914,65 @@ def test_normal_3_2(self, processor: Processor, db: Session, personal_info_contr # Before run(consume accumulated events) processor.sync_new_logs() - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_3, user_pk_3, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_4, user_pk_4, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_3, + user_pk_3, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_4, + user_pk_4, + [issuer_address, ""], + ) # BulkTransfer: 1st address_list1 = [user_address_1, user_address_2, user_address_3] value_list1 = [10, 20, 30] - tx = token_contract_1.functions.bulkTransfer(address_list1, value_list1).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = token_contract_1.functions.bulkTransfer( + address_list1, value_list1 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) _, _ = ContractUtils.send_transaction(tx, issuer_private_key) # BulkTransfer: 2nd address_list2 = [user_address_1, user_address_2, user_address_3, user_address_4] value_list2 = [1, 2, 3, 4] - tx = token_contract_1.functions.bulkTransfer(address_list2, value_list2).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = token_contract_1.functions.bulkTransfer( + address_list2, value_list2 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) _, _ = ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -2288,35 +2981,55 @@ def test_normal_3_2(self, processor: Processor, db: Session, personal_info_contr _position_list = db.query(IDXPosition).all() assert len(_position_list) == 5 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 60 - 10 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 11 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_2).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_2) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_2 assert _position.balance == 22 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_3).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_3) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_3 assert _position.balance == 33 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_4).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_4) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_4 assert _position.balance == 4 @@ -2336,17 +3049,29 @@ def test_normal_3_2(self, processor: Processor, db: Session, personal_info_contr # Multi event logs # - IbetExchange: NewOrder # - IbetExchange: CancelOrder - def test_normal_3_3(self, processor: Processor, db: Session, personal_info_contract, ibet_exchange_contract): + def test_normal_3_3( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_exchange_contract, + ): exchange_contract = ibet_exchange_contract user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues share token. token_contract = deploy_share_token_contract( @@ -2370,27 +3095,71 @@ def test_normal_3_3(self, processor: Processor, db: Session, personal_info_contr # Before run(consume accumulated events) processor.sync_new_logs() - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 30]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_2, 10]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 30], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, 10], + ) # NewOrder(Sell) & CancelOrder - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [exchange_contract.address, 10]) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [exchange_contract.address, 10], + ) IbetExchangeContractTestUtils.create_order( - exchange_contract.address, user_address_1, user_pk_1, [token_contract.address, 10, 100, False, issuer_address] + exchange_contract.address, + user_address_1, + user_pk_1, + [token_contract.address, 10, 100, False, issuer_address], + ) + latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id( + exchange_contract.address + ) + IbetExchangeContractTestUtils.cancel_order( + exchange_contract.address, user_address_1, user_pk_1, [latest_order_id] ) - latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id(exchange_contract.address) - IbetExchangeContractTestUtils.cancel_order(exchange_contract.address, user_address_1, user_pk_1, [latest_order_id]) # NewOrder(Buy) & CancelOrder IbetExchangeContractTestUtils.create_order( - exchange_contract.address, user_address_1, user_pk_1, [token_contract.address, 10, 100, True, issuer_address] + exchange_contract.address, + user_address_1, + user_pk_1, + [token_contract.address, 10, 100, True, issuer_address], + ) + latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id( + exchange_contract.address + ) + IbetExchangeContractTestUtils.cancel_order( + exchange_contract.address, user_address_1, user_pk_1, [latest_order_id] ) - latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id(exchange_contract.address) - IbetExchangeContractTestUtils.cancel_order(exchange_contract.address, user_address_1, user_pk_1, [latest_order_id]) # Run target process block_number = web3.eth.block_number @@ -2399,21 +3168,33 @@ def test_normal_3_3(self, processor: Processor, db: Session, personal_info_contr # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 3 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 30 - 10 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 30 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_2).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_2) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_2 assert _position.balance == 10 @@ -2429,17 +3210,29 @@ def test_normal_3_3(self, processor: Processor, db: Session, personal_info_contr # Multi event logs # - IbetSecurityTokenEscrow: EscrowCreated # - IbetSecurityTokenEscrow: EscrowCanceled - def test_normal_3_4(self, processor: Processor, db: Session, personal_info_contract, ibet_security_token_escrow_contract): + def test_normal_3_4( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_security_token_escrow_contract, + ): escrow_contract = ibet_security_token_escrow_contract user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues share token. token_contract = deploy_share_token_contract( @@ -2463,21 +3256,58 @@ def test_normal_3_4(self, processor: Processor, db: Session, personal_info_contr # Before run(consume accumulated events) processor.sync_new_logs() - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 30]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_2, 10]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 30], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, 10], + ) # CreateEscrow & CancelEscrow - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [escrow_contract.address, 30]) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [escrow_contract.address, 30], + ) for _ in range(3): STEscrowContractUtils.create_escrow( - escrow_contract.address, user_address_1, user_pk_1, [token_contract.address, user_address_2, 10, issuer_address, "", ""] + escrow_contract.address, + user_address_1, + user_pk_1, + [token_contract.address, user_address_2, 10, issuer_address, "", ""], + ) + latest_escrow_id = STEscrowContractUtils.get_latest_escrow_id( + escrow_contract.address + ) + STEscrowContractUtils.cancel_escrow( + escrow_contract.address, user_address_1, user_pk_1, [latest_escrow_id] ) - latest_escrow_id = STEscrowContractUtils.get_latest_escrow_id(escrow_contract.address) - STEscrowContractUtils.cancel_escrow(escrow_contract.address, user_address_1, user_pk_1, [latest_escrow_id]) # Run target process block_number = web3.eth.block_number @@ -2486,21 +3316,33 @@ def test_normal_3_4(self, processor: Processor, db: Session, personal_info_contr # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 3 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 30 - 10 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 0 assert _position.exchange_balance == 30 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_2).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_2) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_2 assert _position.balance == 10 @@ -2513,17 +3355,29 @@ def test_normal_3_4(self, processor: Processor, db: Session, personal_info_contr # # Multi Token - def test_normal_4(self, processor: Processor, db: Session, personal_info_contract, ibet_security_token_escrow_contract): + def test_normal_4( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_security_token_escrow_contract, + ): escrow_contract = ibet_security_token_escrow_contract user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues share token. token_contract1 = deploy_share_token_contract( @@ -2564,15 +3418,50 @@ def test_normal_4(self, processor: Processor, db: Session, personal_info_contrac # Before run(consume accumulated events) processor.sync_new_logs() - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_contract1.address, issuer_address, issuer_private_key, [user_address_1, 30]) - STContractUtils.transfer(token_contract1.address, issuer_address, issuer_private_key, [user_address_2, 10]) + STContractUtils.transfer( + token_contract1.address, + issuer_address, + issuer_private_key, + [user_address_1, 30], + ) + STContractUtils.transfer( + token_contract1.address, + issuer_address, + issuer_private_key, + [user_address_2, 10], + ) - STContractUtils.transfer(token_contract2.address, issuer_address, issuer_private_key, [user_address_1, 40]) - STContractUtils.transfer(token_contract2.address, issuer_address, issuer_private_key, [user_address_2, 60]) + STContractUtils.transfer( + token_contract2.address, + issuer_address, + issuer_private_key, + [user_address_1, 40], + ) + STContractUtils.transfer( + token_contract2.address, + issuer_address, + issuer_private_key, + [user_address_2, 60], + ) # Run target process block_number = web3.eth.block_number @@ -2581,42 +3470,72 @@ def test_normal_4(self, processor: Processor, db: Session, personal_info_contrac # Assertion _position_list = db.query(IDXPosition).all() assert len(_position_list) == 6 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).filter(IDXPosition.token_address == token_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .filter(IDXPosition.token_address == token_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == issuer_address assert _position.balance == 100 - 30 - 10 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).filter(IDXPosition.token_address == token_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .filter(IDXPosition.token_address == token_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_1 assert _position.balance == 30 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_2).filter(IDXPosition.token_address == token_address_1).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_2) + .filter(IDXPosition.token_address == token_address_1) + .first() + ) assert _position.token_address == token_address_1 assert _position.account_address == user_address_2 assert _position.balance == 10 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == issuer_address).filter(IDXPosition.token_address == token_address_2).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == issuer_address) + .filter(IDXPosition.token_address == token_address_2) + .first() + ) assert _position.token_address == token_address_2 assert _position.account_address == issuer_address assert _position.balance == 0 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_1).filter(IDXPosition.token_address == token_address_2).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_1) + .filter(IDXPosition.token_address == token_address_2) + .first() + ) assert _position.token_address == token_address_2 assert _position.account_address == user_address_1 assert _position.balance == 40 assert _position.exchange_balance == 0 assert _position.exchange_commitment == 0 assert _position.pending_transfer == 0 - _position = db.query(IDXPosition).filter(IDXPosition.account_address == user_address_2).filter(IDXPosition.token_address == token_address_2).first() + _position = ( + db.query(IDXPosition) + .filter(IDXPosition.account_address == user_address_2) + .filter(IDXPosition.token_address == token_address_2) + .first() + ) assert _position.token_address == token_address_2 assert _position.account_address == user_address_2 assert _position.balance == 60 @@ -2631,7 +3550,9 @@ def test_normal_4(self, processor: Processor, db: Session, personal_info_contrac # If block number processed in batch is equal or greater than current block number, # batch logs "skip process". @mock.patch("web3.eth.Eth.block_number", 100) - def test_normal_5(self, processor: Processor, db: Session, caplog: pytest.LogCaptureFixture): + def test_normal_5( + self, processor: Processor, db: Session, caplog: pytest.LogCaptureFixture + ): _idx_position_share_block_number = IDXPositionShareBlockNumber() _idx_position_share_block_number.id = 1 _idx_position_share_block_number.latest_block_number = 1000 @@ -2639,15 +3560,25 @@ def test_normal_5(self, processor: Processor, db: Session, caplog: pytest.LogCap db.commit() processor.sync_new_logs() - assert 1 == caplog.record_tuples.count((LOG.name, logging.DEBUG, "skip process")) + assert 1 == caplog.record_tuples.count( + (LOG.name, logging.DEBUG, "skip process") + ) # # Newly tokens added - def test_normal_6(self, processor: Processor, db: Session, personal_info_contract, ibet_security_token_escrow_contract): + def test_normal_6( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_security_token_escrow_contract, + ): escrow_contract = ibet_security_token_escrow_contract user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues bond token. token_contract1 = deploy_share_token_contract( @@ -2708,18 +3639,23 @@ def test_normal_6(self, processor: Processor, db: Session, personal_info_contrac # # If exception occurs out of Processor except-catch, batch outputs logs in mainloop. - def test_error_1(self, main_func, db :Session, personal_info_contract, caplog: pytest.LogCaptureFixture): + def test_error_1( + self, + main_func, + db: Session, + personal_info_contract, + caplog: pytest.LogCaptureFixture, + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract_1 = deploy_share_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_share_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_SHARE.value @@ -2732,25 +3668,45 @@ def test_error_1(self, main_func, db :Session, personal_info_contract, caplog: p db.commit() # Run mainloop once and fail with web3 utils error - with patch("batch.indexer_position_share.INDEXER_SYNC_INTERVAL", None),\ - patch.object(web3.eth, "contract", side_effect=ServiceUnavailableError()), \ - pytest.raises(TypeError): + with patch( + "batch.indexer_position_share.INDEXER_SYNC_INTERVAL", None + ), patch.object( + web3.eth, "contract", side_effect=ServiceUnavailableError() + ), pytest.raises( + TypeError + ): main_func() - assert 1 == caplog.record_tuples.count((LOG.name, logging.WARNING, "An external service was unavailable")) + assert 1 == caplog.record_tuples.count( + (LOG.name, logging.WARNING, "An external service was unavailable") + ) caplog.clear() # Run mainloop once and fail with sqlalchemy InvalidRequestError - with patch("batch.indexer_position_share.INDEXER_SYNC_INTERVAL", None),\ - patch.object(Session, "query", side_effect=InvalidRequestError()), \ - pytest.raises(TypeError): + with patch( + "batch.indexer_position_share.INDEXER_SYNC_INTERVAL", None + ), patch.object( + Session, "query", side_effect=InvalidRequestError() + ), pytest.raises( + TypeError + ): main_func() assert 1 == caplog.text.count("A database error has occurred") caplog.clear() # Run mainloop once and fail with connection to blockchain - with patch("batch.indexer_position_share.INDEXER_SYNC_INTERVAL", None),\ - patch.object(ContractUtils, "call_function", side_effect=ConnectionError()), \ - pytest.raises(TypeError): + with patch( + "batch.indexer_position_share.INDEXER_SYNC_INTERVAL", None + ), patch.object( + ContractUtils, "call_function", side_effect=ConnectionError() + ), pytest.raises( + TypeError + ): main_func() - assert 1 == caplog.record_tuples.count((LOG.name, logging.ERROR, "An exception occurred during event synchronization")) - caplog.clear() \ No newline at end of file + assert 1 == caplog.record_tuples.count( + ( + LOG.name, + logging.ERROR, + "An exception occurred during event synchronization", + ) + ) + caplog.clear() diff --git a/tests/test_batch_indexer_token_holders.py b/tests/test_batch_indexer_token_holders.py index 9e2f3fde..cb202ff2 100644 --- a/tests/test_batch_indexer_token_holders.py +++ b/tests/test_batch_indexer_token_holders.py @@ -16,33 +16,43 @@ SPDX-License-Identifier: Apache-2.0 """ -from eth_keyfile import decode_keyfile_json import logging +import uuid +from typing import List +from unittest.mock import MagicMock, patch + import pytest +from eth_keyfile import decode_keyfile_json from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.orm import Session -from typing import List -from unittest.mock import patch, MagicMock -import uuid -from app.model.db import Token, TokenType, TokenHoldersList, TokenHolderBatchStatus, TokenHolder -from app.model.blockchain import ( - IbetStraightBondContract, - IbetShareContract, +from app.model.blockchain import IbetShareContract, IbetStraightBondContract +from app.model.blockchain.tx_params.ibet_share import ( + UpdateParams as IbetShareUpdateParams, +) +from app.model.blockchain.tx_params.ibet_straight_bond import ( + UpdateParams as IbetStraightBondUpdateParams, +) +from app.model.db import ( + Token, + TokenHolder, + TokenHolderBatchStatus, + TokenHoldersList, + TokenType, ) -from app.model.blockchain.tx_params.ibet_straight_bond import UpdateParams as IbetStraightBondUpdateParams -from app.model.blockchain.tx_params.ibet_share import UpdateParams as IbetShareUpdateParams -from app.utils.web3_utils import Web3Wrapper from app.utils.contract_utils import ContractUtils -from batch.indexer_token_holders import Processor, LOG, main +from app.utils.web3_utils import Web3Wrapper +from batch.indexer_token_holders import LOG, Processor, main from config import ZERO_ADDRESS from tests.account_config import config_eth_account +from tests.utils.contract_utils import IbetExchangeContractTestUtils from tests.utils.contract_utils import ( IbetSecurityTokenContractTestUtils as STContractUtils, - IbetExchangeContractTestUtils, - PersonalInfoContractTestUtils, +) +from tests.utils.contract_utils import ( IbetSecurityTokenEscrowContractTestUtils as STEscrowContractUtils, ) +from tests.utils.contract_utils import PersonalInfoContractTestUtils web3 = Web3Wrapper() @@ -74,8 +84,12 @@ def deploy_personal_info_contract(issuer_user): keyfile = issuer_user["keyfile_json"] eoa_password = "password" - private_key = decode_keyfile_json(raw_keyfile_json=keyfile, password=eoa_password.encode("utf-8")) - contract_address, _, _ = ContractUtils.deploy_contract("PersonalInfo", [], address, private_key) + private_key = decode_keyfile_json( + raw_keyfile_json=keyfile, password=eoa_password.encode("utf-8") + ) + contract_address, _, _ = ContractUtils.deploy_contract( + "PersonalInfo", [], address, private_key + ) return contract_address @@ -147,7 +161,12 @@ def deploy_share_token_contract( return ContractUtils.get_contract("IbetShare", token_address) -def token_holders_list(token_address: str, block_number: int, list_id: str, status: TokenHolderBatchStatus = TokenHolderBatchStatus.PENDING) -> TokenHoldersList: +def token_holders_list( + token_address: str, + block_number: int, + list_id: str, + status: TokenHolderBatchStatus = TokenHolderBatchStatus.PENDING, +) -> TokenHoldersList: target_token_holders_list = TokenHoldersList() target_token_holders_list.list_id = list_id target_token_holders_list.token_address = token_address @@ -191,22 +210,24 @@ class TestProcessor: # - RedeemFrom # - Lock def test_normal_1( - self, - processor, - db, - personal_info_contract, - ibet_exchange_contract + self, processor, db, personal_info_contract, ibet_exchange_contract ): exchange_contract = ibet_exchange_contract user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues bond token. token_contract = deploy_bond_token_contract( @@ -225,76 +246,218 @@ def test_normal_1( token_1.tx_hash = "tx_hash" db.add(token_1) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 30000]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_2, 10000]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [exchange_contract.address, 10000]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 30000], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, 10000], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [exchange_contract.address, 10000], + ) # user1: 30000 user2: 10000 - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [exchange_contract.address, 10000]) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [exchange_contract.address, 10000], + ) IbetExchangeContractTestUtils.create_order( - exchange_contract.address, user_address_1, user_pk_1, [token_contract.address, 10000, 100, False, issuer_address] + exchange_contract.address, + user_address_1, + user_pk_1, + [token_contract.address, 10000, 100, False, issuer_address], + ) + latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id( + exchange_contract.address + ) + IbetExchangeContractTestUtils.cancel_order( + exchange_contract.address, user_address_1, user_pk_1, [latest_order_id] ) - latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id(exchange_contract.address) - IbetExchangeContractTestUtils.cancel_order(exchange_contract.address, user_address_1, user_pk_1, [latest_order_id]) # user1: 30000 user2: 10000 - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [exchange_contract.address, 10000]) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [exchange_contract.address, 10000], + ) IbetExchangeContractTestUtils.create_order( - exchange_contract.address, user_address_1, user_pk_1, [token_contract.address, 10000, 100, False, issuer_address] + exchange_contract.address, + user_address_1, + user_pk_1, + [token_contract.address, 10000, 100, False, issuer_address], + ) + latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id( + exchange_contract.address + ) + IbetExchangeContractTestUtils.force_cancel_order( + exchange_contract.address, + issuer_address, + issuer_private_key, + [latest_order_id], ) - latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id(exchange_contract.address) - IbetExchangeContractTestUtils.force_cancel_order(exchange_contract.address, issuer_address, issuer_private_key, [latest_order_id]) # user1: 30000 user2: 10000 - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [exchange_contract.address, 10000]) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [exchange_contract.address, 10000], + ) IbetExchangeContractTestUtils.create_order( - exchange_contract.address, user_address_1, user_pk_1, [token_contract.address, 10000, 100, False, issuer_address] + exchange_contract.address, + user_address_1, + user_pk_1, + [token_contract.address, 10000, 100, False, issuer_address], + ) + latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id( + exchange_contract.address + ) + IbetExchangeContractTestUtils.execute_order( + exchange_contract.address, + user_address_2, + user_pk_2, + [latest_order_id, 10000, True], + ) + latest_agreement_id = IbetExchangeContractTestUtils.get_latest_agreementid( + exchange_contract.address, latest_order_id ) - latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id(exchange_contract.address) - IbetExchangeContractTestUtils.execute_order(exchange_contract.address, user_address_2, user_pk_2, [latest_order_id, 10000, True]) - latest_agreement_id = IbetExchangeContractTestUtils.get_latest_agreementid(exchange_contract.address, latest_order_id) IbetExchangeContractTestUtils.confirm_agreement( - exchange_contract.address, issuer_address, issuer_private_key, [latest_order_id, latest_agreement_id] + exchange_contract.address, + issuer_address, + issuer_private_key, + [latest_order_id, latest_agreement_id], ) # user1: 20000 user2: 20000 - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [exchange_contract.address, 4000]) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [exchange_contract.address, 4000], + ) IbetExchangeContractTestUtils.create_order( - exchange_contract.address, user_address_2, user_pk_2, [token_contract.address, 4000, 100, True, issuer_address] + exchange_contract.address, + user_address_2, + user_pk_2, + [token_contract.address, 4000, 100, True, issuer_address], + ) + latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id( + exchange_contract.address + ) + IbetExchangeContractTestUtils.execute_order( + exchange_contract.address, + user_address_1, + user_pk_1, + [latest_order_id, 4000, False], + ) + latest_agreement_id = IbetExchangeContractTestUtils.get_latest_agreementid( + exchange_contract.address, latest_order_id ) - latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id(exchange_contract.address) - IbetExchangeContractTestUtils.execute_order(exchange_contract.address, user_address_1, user_pk_1, [latest_order_id, 4000, False]) - latest_agreement_id = IbetExchangeContractTestUtils.get_latest_agreementid(exchange_contract.address, latest_order_id) IbetExchangeContractTestUtils.cancel_agreement( - exchange_contract.address, issuer_address, issuer_private_key, [latest_order_id, latest_agreement_id] + exchange_contract.address, + issuer_address, + issuer_private_key, + [latest_order_id, latest_agreement_id], ) # user1: 20000 user2: 20000 - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [exchange_contract.address, 4000]) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [exchange_contract.address, 4000], + ) IbetExchangeContractTestUtils.create_order( - exchange_contract.address, user_address_2, user_pk_2, [token_contract.address, 4000, 100, True, issuer_address] + exchange_contract.address, + user_address_2, + user_pk_2, + [token_contract.address, 4000, 100, True, issuer_address], + ) + latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id( + exchange_contract.address + ) + IbetExchangeContractTestUtils.execute_order( + exchange_contract.address, + user_address_1, + user_pk_1, + [latest_order_id, 4000, False], + ) + latest_agreement_id = IbetExchangeContractTestUtils.get_latest_agreementid( + exchange_contract.address, latest_order_id ) - latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id(exchange_contract.address) - IbetExchangeContractTestUtils.execute_order(exchange_contract.address, user_address_1, user_pk_1, [latest_order_id, 4000, False]) - latest_agreement_id = IbetExchangeContractTestUtils.get_latest_agreementid(exchange_contract.address, latest_order_id) IbetExchangeContractTestUtils.confirm_agreement( - exchange_contract.address, issuer_address, issuer_private_key, [latest_order_id, latest_agreement_id] + exchange_contract.address, + issuer_address, + issuer_private_key, + [latest_order_id, latest_agreement_id], ) # user1: 16000 user2: 24000 - STContractUtils.issue_from(token_contract.address, issuer_address, issuer_private_key, [issuer_address, ZERO_ADDRESS, 40000]) - STContractUtils.redeem_from(token_contract.address, issuer_address, issuer_private_key, [user_address_2, ZERO_ADDRESS, 10000]) + STContractUtils.issue_from( + token_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ZERO_ADDRESS, 40000], + ) + STContractUtils.redeem_from( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, ZERO_ADDRESS, 10000], + ) # user1: 16000 user2: 14000 - STContractUtils.issue_from(token_contract.address, issuer_address, issuer_private_key, [user_address_2, ZERO_ADDRESS, 30000]) - STContractUtils.redeem_from(token_contract.address, issuer_address, issuer_private_key, [issuer_address, ZERO_ADDRESS, 10000]) + STContractUtils.issue_from( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, ZERO_ADDRESS, 30000], + ) + STContractUtils.redeem_from( + token_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ZERO_ADDRESS, 10000], + ) # user1: 16000 user2: 44000 - STContractUtils.lock(token_contract.address, user_address_1, user_pk_1, [issuer_address, 3000, ""]) + STContractUtils.lock( + token_contract.address, + user_address_1, + user_pk_1, + [issuer_address, 3000, ""], + ) # user1: (hold: 13000, locked: 3000) user2: 44000 # Issuer issues other token to create exchange event @@ -305,29 +468,66 @@ def test_normal_1( tradable_exchange_contract_address=exchange_contract.address, transfer_approval_required=False, ) - STContractUtils.transfer(other_token_contract.address, issuer_address, issuer_private_key, [user_address_1, 10000]) - STContractUtils.transfer(other_token_contract.address, user_address_1, user_pk_1, [exchange_contract.address, 10000]) - STContractUtils.transfer(other_token_contract.address, issuer_address, issuer_private_key, [exchange_contract.address, 10000]) + STContractUtils.transfer( + other_token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 10000], + ) + STContractUtils.transfer( + other_token_contract.address, + user_address_1, + user_pk_1, + [exchange_contract.address, 10000], + ) + STContractUtils.transfer( + other_token_contract.address, + issuer_address, + issuer_private_key, + [exchange_contract.address, 10000], + ) IbetExchangeContractTestUtils.create_order( - exchange_contract.address, user_address_1, user_pk_1, [other_token_contract.address, 10000, 100, False, issuer_address] + exchange_contract.address, + user_address_1, + user_pk_1, + [other_token_contract.address, 10000, 100, False, issuer_address], + ) + latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id( + exchange_contract.address + ) + IbetExchangeContractTestUtils.execute_order( + exchange_contract.address, + user_address_2, + user_pk_2, + [latest_order_id, 10000, True], + ) + latest_agreement_id = IbetExchangeContractTestUtils.get_latest_agreementid( + exchange_contract.address, latest_order_id ) - latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id(exchange_contract.address) - IbetExchangeContractTestUtils.execute_order(exchange_contract.address, user_address_2, user_pk_2, [latest_order_id, 10000, True]) - latest_agreement_id = IbetExchangeContractTestUtils.get_latest_agreementid(exchange_contract.address, latest_order_id) IbetExchangeContractTestUtils.confirm_agreement( - exchange_contract.address, issuer_address, issuer_private_key, [latest_order_id, latest_agreement_id] + exchange_contract.address, + issuer_address, + issuer_private_key, + [latest_order_id, latest_agreement_id], ) # Insert collection record with above token and current block number list_id = str(uuid.uuid4()) block_number = web3.eth.block_number - _token_holders_list = token_holders_list(token_contract.address, block_number, list_id) + _token_holders_list = token_holders_list( + token_contract.address, block_number, list_id + ) db.add(_token_holders_list) db.commit() # Issuer transfers issued token to user1 again to proceed block_number on chain. - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 20000]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 20000], + ) # Then execute processor. processor.collect() @@ -350,7 +550,16 @@ def test_normal_1( assert user2_record.hold_balance == 44000 assert user2_record.locked_balance == 0 - assert len(list(db.query(TokenHolder).filter(TokenHolder.holder_list_id == _token_holders_list.id))) == 2 + assert ( + len( + list( + db.query(TokenHolder).filter( + TokenHolder.holder_list_id == _token_holders_list.id + ) + ) + ) + == 2 + ) # # StraightBond @@ -365,21 +574,23 @@ def test_normal_1( # - Lock # - Unlock def test_normal_2( - self, - processor, - db, - personal_info_contract, - ibet_security_token_escrow_contract + self, processor, db, personal_info_contract, ibet_security_token_escrow_contract ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues bond token. token_contract = deploy_bond_token_contract( @@ -398,20 +609,67 @@ def test_normal_2( token_1.tx_hash = "tx_hash" db.add(token_1) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 20000]) - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [ibet_security_token_escrow_contract.address, 10000]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 20000], + ) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [ibet_security_token_escrow_contract.address, 10000], + ) # user1: 20000 user2: 0 - STContractUtils.set_transfer_approve_required(token_contract.address, issuer_address, issuer_private_key, [True]) - STContractUtils.apply_for_transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 10000, "to user1#1"]) - STContractUtils.apply_for_transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_2, 10000, "to user2#1"]) + STContractUtils.set_transfer_approve_required( + token_contract.address, issuer_address, issuer_private_key, [True] + ) + STContractUtils.apply_for_transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 10000, "to user1#1"], + ) + STContractUtils.apply_for_transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, 10000, "to user2#1"], + ) - STContractUtils.cancel_transfer(token_contract.address, issuer_address, issuer_private_key, [0, "to user1#1"]) - STContractUtils.approve_transfer(token_contract.address, issuer_address, issuer_private_key, [1, "to user2#1"]) + STContractUtils.cancel_transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [0, "to user1#1"], + ) + STContractUtils.approve_transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [1, "to user2#1"], + ) # user1: 20000 user2: 10000 STEscrowContractUtils.create_escrow( @@ -420,12 +678,20 @@ def test_normal_2( user_pk_1, [token_contract.address, user_address_2, 7000, issuer_address, "", ""], ) - latest_security_escrow_id = STEscrowContractUtils.get_latest_escrow_id(ibet_security_token_escrow_contract.address) + latest_security_escrow_id = STEscrowContractUtils.get_latest_escrow_id( + ibet_security_token_escrow_contract.address + ) STEscrowContractUtils.finish_escrow( - ibet_security_token_escrow_contract.address, issuer_address, issuer_private_key, [latest_security_escrow_id] + ibet_security_token_escrow_contract.address, + issuer_address, + issuer_private_key, + [latest_security_escrow_id], ) STEscrowContractUtils.approve_transfer( - ibet_security_token_escrow_contract.address, issuer_address, issuer_private_key, [latest_security_escrow_id, ""] + ibet_security_token_escrow_contract.address, + issuer_address, + issuer_private_key, + [latest_security_escrow_id, ""], ) # user1: 13000 user2: 17000 @@ -435,26 +701,50 @@ def test_normal_2( user_pk_1, [token_contract.address, user_address_2, 2000, issuer_address, "", ""], ) - latest_security_escrow_id = STEscrowContractUtils.get_latest_escrow_id(ibet_security_token_escrow_contract.address) + latest_security_escrow_id = STEscrowContractUtils.get_latest_escrow_id( + ibet_security_token_escrow_contract.address + ) STEscrowContractUtils.finish_escrow( - ibet_security_token_escrow_contract.address, issuer_address, issuer_private_key, [latest_security_escrow_id] + ibet_security_token_escrow_contract.address, + issuer_address, + issuer_private_key, + [latest_security_escrow_id], ) # user1: 13000 user2: 17000 - STContractUtils.lock(token_contract.address, user_address_1, user_pk_1, [issuer_address, 3000, ""]) - STContractUtils.unlock(token_contract.address, issuer_address, issuer_private_key, [user_address_1, user_address_2, 3000, ""]) + STContractUtils.lock( + token_contract.address, + user_address_1, + user_pk_1, + [issuer_address, 3000, ""], + ) + STContractUtils.unlock( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, user_address_2, 3000, ""], + ) # user1: 10000 user2: 20000 # Insert collection record with above token and current block number list_id = str(uuid.uuid4()) block_number = web3.eth.block_number - _token_holders_list = token_holders_list(token_contract.address, block_number, list_id) + _token_holders_list = token_holders_list( + token_contract.address, block_number, list_id + ) db.add(_token_holders_list) db.commit() # Issuer transfers issued token to user1 again to proceed block_number on chain. - STContractUtils.set_transfer_approve_required(token_contract.address, issuer_address, issuer_private_key, [False]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 20000]) + STContractUtils.set_transfer_approve_required( + token_contract.address, issuer_address, issuer_private_key, [False] + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 20000], + ) # Then execute processor. processor.collect() @@ -477,7 +767,16 @@ def test_normal_2( assert user2_record.hold_balance == 20000 assert user2_record.locked_balance == 0 - assert len(list(db.query(TokenHolder).filter(TokenHolder.holder_list_id == _token_holders_list.id))) == 2 + assert ( + len( + list( + db.query(TokenHolder).filter( + TokenHolder.holder_list_id == _token_holders_list.id + ) + ) + ) + == 2 + ) # # StraightBond @@ -485,21 +784,23 @@ def test_normal_2( # - ApplyForTransfer - pending # - Escrow - pending def test_normal_3( - self, - processor, - db, - personal_info_contract, - ibet_security_token_escrow_contract + self, processor, db, personal_info_contract, ibet_security_token_escrow_contract ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues bond token. token_contract = deploy_bond_token_contract( @@ -518,17 +819,54 @@ def test_normal_3( token_1.tx_hash = "tx_hash" db.add(token_1) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 20000]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_2, 10000]) - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [ibet_security_token_escrow_contract.address, 10000]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 20000], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, 10000], + ) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [ibet_security_token_escrow_contract.address, 10000], + ) # user1: 20000 user2: 10000 - STContractUtils.set_transfer_approve_required(token_contract.address, issuer_address, issuer_private_key, [True]) - STContractUtils.apply_for_transfer(token_contract.address, user_address_1, user_pk_1, [user_address_2, 10000, "to user2#1"]) + STContractUtils.set_transfer_approve_required( + token_contract.address, issuer_address, issuer_private_key, [True] + ) + STContractUtils.apply_for_transfer( + token_contract.address, + user_address_1, + user_pk_1, + [user_address_2, 10000, "to user2#1"], + ) # user1: 20000 user2: 10000 STEscrowContractUtils.create_escrow( @@ -543,26 +881,43 @@ def test_normal_3( user_pk_1, [token_contract.address, user_address_2, 3000, issuer_address, "", ""], ) - latest_security_escrow_id = STEscrowContractUtils.get_latest_escrow_id(ibet_security_token_escrow_contract.address) + latest_security_escrow_id = STEscrowContractUtils.get_latest_escrow_id( + ibet_security_token_escrow_contract.address + ) STEscrowContractUtils.finish_escrow( - ibet_security_token_escrow_contract.address, issuer_address, issuer_private_key, [latest_security_escrow_id] + ibet_security_token_escrow_contract.address, + issuer_address, + issuer_private_key, + [latest_security_escrow_id], ) STEscrowContractUtils.approve_transfer( - ibet_security_token_escrow_contract.address, issuer_address, issuer_private_key, [latest_security_escrow_id, ""] + ibet_security_token_escrow_contract.address, + issuer_address, + issuer_private_key, + [latest_security_escrow_id, ""], ) # user1: 17000 user2: 13000 # Insert collection record with above token and current block number list_id = str(uuid.uuid4()) block_number = web3.eth.block_number - _token_holders_list = token_holders_list(token_contract.address, block_number, list_id) + _token_holders_list = token_holders_list( + token_contract.address, block_number, list_id + ) db.add(_token_holders_list) db.commit() # Issuer transfers issued token to user1 again to proceed block_number on chain. - STContractUtils.set_transfer_approve_required(token_contract.address, issuer_address, issuer_private_key, [False]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 20000]) + STContractUtils.set_transfer_approve_required( + token_contract.address, issuer_address, issuer_private_key, [False] + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 20000], + ) # Then execute processor. processor.collect() @@ -583,7 +938,16 @@ def test_normal_3( assert user1_record.hold_balance == 17000 assert user2_record.hold_balance == 13000 - assert len(list(db.query(TokenHolder).filter(TokenHolder.holder_list_id == _token_holders_list.id))) == 2 + assert ( + len( + list( + db.query(TokenHolder).filter( + TokenHolder.holder_list_id == _token_holders_list.id + ) + ) + ) + == 2 + ) # # Share @@ -596,22 +960,24 @@ def test_normal_3( # - RedeemFrom # - Lock def test_normal_4( - self, - processor, - db, - personal_info_contract, - ibet_exchange_contract + self, processor, db, personal_info_contract, ibet_exchange_contract ): exchange_contract = ibet_exchange_contract user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues share token. token_contract = deploy_share_token_contract( @@ -630,76 +996,218 @@ def test_normal_4( token_1.tx_hash = "tx_hash" db.add(token_1) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 20000]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_2, 10000]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [exchange_contract.address, 10000]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 20000], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, 10000], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [exchange_contract.address, 10000], + ) # user1: 20000 user2: 10000 - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [exchange_contract.address, 10000]) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [exchange_contract.address, 10000], + ) IbetExchangeContractTestUtils.create_order( - exchange_contract.address, user_address_1, user_pk_1, [token_contract.address, 10000, 100, False, issuer_address] + exchange_contract.address, + user_address_1, + user_pk_1, + [token_contract.address, 10000, 100, False, issuer_address], + ) + latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id( + exchange_contract.address + ) + IbetExchangeContractTestUtils.cancel_order( + exchange_contract.address, user_address_1, user_pk_1, [latest_order_id] ) - latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id(exchange_contract.address) - IbetExchangeContractTestUtils.cancel_order(exchange_contract.address, user_address_1, user_pk_1, [latest_order_id]) # user1: 20000 user2: 10000 - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [exchange_contract.address, 10000]) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [exchange_contract.address, 10000], + ) IbetExchangeContractTestUtils.create_order( - exchange_contract.address, user_address_1, user_pk_1, [token_contract.address, 10000, 100, False, issuer_address] + exchange_contract.address, + user_address_1, + user_pk_1, + [token_contract.address, 10000, 100, False, issuer_address], + ) + latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id( + exchange_contract.address + ) + IbetExchangeContractTestUtils.force_cancel_order( + exchange_contract.address, + issuer_address, + issuer_private_key, + [latest_order_id], ) - latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id(exchange_contract.address) - IbetExchangeContractTestUtils.force_cancel_order(exchange_contract.address, issuer_address, issuer_private_key, [latest_order_id]) # user1: 20000 user2: 10000 - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [exchange_contract.address, 10000]) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [exchange_contract.address, 10000], + ) IbetExchangeContractTestUtils.create_order( - exchange_contract.address, user_address_1, user_pk_1, [token_contract.address, 10000, 100, False, issuer_address] + exchange_contract.address, + user_address_1, + user_pk_1, + [token_contract.address, 10000, 100, False, issuer_address], + ) + latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id( + exchange_contract.address + ) + IbetExchangeContractTestUtils.execute_order( + exchange_contract.address, + user_address_2, + user_pk_2, + [latest_order_id, 10000, True], + ) + latest_agreement_id = IbetExchangeContractTestUtils.get_latest_agreementid( + exchange_contract.address, latest_order_id ) - latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id(exchange_contract.address) - IbetExchangeContractTestUtils.execute_order(exchange_contract.address, user_address_2, user_pk_2, [latest_order_id, 10000, True]) - latest_agreement_id = IbetExchangeContractTestUtils.get_latest_agreementid(exchange_contract.address, latest_order_id) IbetExchangeContractTestUtils.confirm_agreement( - exchange_contract.address, issuer_address, issuer_private_key, [latest_order_id, latest_agreement_id] + exchange_contract.address, + issuer_address, + issuer_private_key, + [latest_order_id, latest_agreement_id], ) # user1: 10000 user2: 20000 - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [exchange_contract.address, 4000]) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [exchange_contract.address, 4000], + ) IbetExchangeContractTestUtils.create_order( - exchange_contract.address, user_address_2, user_pk_2, [token_contract.address, 4000, 100, True, issuer_address] + exchange_contract.address, + user_address_2, + user_pk_2, + [token_contract.address, 4000, 100, True, issuer_address], + ) + latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id( + exchange_contract.address + ) + IbetExchangeContractTestUtils.execute_order( + exchange_contract.address, + user_address_1, + user_pk_1, + [latest_order_id, 4000, False], + ) + latest_agreement_id = IbetExchangeContractTestUtils.get_latest_agreementid( + exchange_contract.address, latest_order_id ) - latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id(exchange_contract.address) - IbetExchangeContractTestUtils.execute_order(exchange_contract.address, user_address_1, user_pk_1, [latest_order_id, 4000, False]) - latest_agreement_id = IbetExchangeContractTestUtils.get_latest_agreementid(exchange_contract.address, latest_order_id) IbetExchangeContractTestUtils.cancel_agreement( - exchange_contract.address, issuer_address, issuer_private_key, [latest_order_id, latest_agreement_id] + exchange_contract.address, + issuer_address, + issuer_private_key, + [latest_order_id, latest_agreement_id], ) # user1: 10000 user2: 20000 - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [exchange_contract.address, 4000]) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [exchange_contract.address, 4000], + ) IbetExchangeContractTestUtils.create_order( - exchange_contract.address, user_address_2, user_pk_2, [token_contract.address, 4000, 100, True, issuer_address] + exchange_contract.address, + user_address_2, + user_pk_2, + [token_contract.address, 4000, 100, True, issuer_address], + ) + latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id( + exchange_contract.address + ) + IbetExchangeContractTestUtils.execute_order( + exchange_contract.address, + user_address_1, + user_pk_1, + [latest_order_id, 4000, False], + ) + latest_agreement_id = IbetExchangeContractTestUtils.get_latest_agreementid( + exchange_contract.address, latest_order_id ) - latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id(exchange_contract.address) - IbetExchangeContractTestUtils.execute_order(exchange_contract.address, user_address_1, user_pk_1, [latest_order_id, 4000, False]) - latest_agreement_id = IbetExchangeContractTestUtils.get_latest_agreementid(exchange_contract.address, latest_order_id) IbetExchangeContractTestUtils.confirm_agreement( - exchange_contract.address, issuer_address, issuer_private_key, [latest_order_id, latest_agreement_id] + exchange_contract.address, + issuer_address, + issuer_private_key, + [latest_order_id, latest_agreement_id], ) # user1: 6000 user2: 24000 - STContractUtils.issue_from(token_contract.address, issuer_address, issuer_private_key, [issuer_address, ZERO_ADDRESS, 40000]) - STContractUtils.redeem_from(token_contract.address, issuer_address, issuer_private_key, [user_address_2, ZERO_ADDRESS, 10000]) + STContractUtils.issue_from( + token_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ZERO_ADDRESS, 40000], + ) + STContractUtils.redeem_from( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, ZERO_ADDRESS, 10000], + ) # user1: 6000 user2: 14000 - STContractUtils.issue_from(token_contract.address, issuer_address, issuer_private_key, [user_address_2, ZERO_ADDRESS, 30000]) - STContractUtils.redeem_from(token_contract.address, issuer_address, issuer_private_key, [issuer_address, ZERO_ADDRESS, 10000]) + STContractUtils.issue_from( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, ZERO_ADDRESS, 30000], + ) + STContractUtils.redeem_from( + token_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ZERO_ADDRESS, 10000], + ) # user1: 6000 user2: 44000 - STContractUtils.lock(token_contract.address, user_address_1, user_pk_1, [issuer_address, 3000, ""]) + STContractUtils.lock( + token_contract.address, + user_address_1, + user_pk_1, + [issuer_address, 3000, ""], + ) # user1: (hold: 3000, locked: 3000) user2: 44000 # Issuer issues other token to create exchange event @@ -711,32 +1219,79 @@ def test_normal_4( transfer_approval_required=False, ) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(other_token_contract.address, issuer_address, issuer_private_key, [user_address_1, 10000]) - STContractUtils.transfer(other_token_contract.address, user_address_1, user_pk_1, [exchange_contract.address, 10000]) - STContractUtils.transfer(other_token_contract.address, issuer_address, issuer_private_key, [exchange_contract.address, 10000]) + STContractUtils.transfer( + other_token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 10000], + ) + STContractUtils.transfer( + other_token_contract.address, + user_address_1, + user_pk_1, + [exchange_contract.address, 10000], + ) + STContractUtils.transfer( + other_token_contract.address, + issuer_address, + issuer_private_key, + [exchange_contract.address, 10000], + ) IbetExchangeContractTestUtils.create_order( - exchange_contract.address, user_address_1, user_pk_1, [other_token_contract.address, 10000, 100, False, issuer_address] + exchange_contract.address, + user_address_1, + user_pk_1, + [other_token_contract.address, 10000, 100, False, issuer_address], + ) + latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id( + exchange_contract.address + ) + IbetExchangeContractTestUtils.execute_order( + exchange_contract.address, + user_address_2, + user_pk_2, + [latest_order_id, 10000, True], + ) + latest_agreement_id = IbetExchangeContractTestUtils.get_latest_agreementid( + exchange_contract.address, latest_order_id ) - latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id(exchange_contract.address) - IbetExchangeContractTestUtils.execute_order(exchange_contract.address, user_address_2, user_pk_2, [latest_order_id, 10000, True]) - latest_agreement_id = IbetExchangeContractTestUtils.get_latest_agreementid(exchange_contract.address, latest_order_id) IbetExchangeContractTestUtils.confirm_agreement( - exchange_contract.address, issuer_address, issuer_private_key, [latest_order_id, latest_agreement_id] + exchange_contract.address, + issuer_address, + issuer_private_key, + [latest_order_id, latest_agreement_id], ) # Insert collection record with above token and current block number list_id = str(uuid.uuid4()) block_number = web3.eth.block_number - _token_holders_list = token_holders_list(token_contract.address, block_number, list_id) + _token_holders_list = token_holders_list( + token_contract.address, block_number, list_id + ) db.add(_token_holders_list) db.commit() # Issuer transfers issued token to user1 again to proceed block_number on chain. - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 20000]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 20000], + ) # Then execute processor. processor.collect() @@ -759,7 +1314,16 @@ def test_normal_4( assert user2_record.hold_balance == 44000 assert user2_record.locked_balance == 0 - assert len(list(db.query(TokenHolder).filter(TokenHolder.holder_list_id == _token_holders_list.id))) == 2 + assert ( + len( + list( + db.query(TokenHolder).filter( + TokenHolder.holder_list_id == _token_holders_list.id + ) + ) + ) + == 2 + ) # # Share @@ -773,22 +1337,24 @@ def test_normal_4( # - ApproveTransfer # - Lock # - Unlock - def test_normal_5( - self, - processor, - db, - personal_info_contract, - ibet_security_token_escrow_contract + def test_normal_5( + self, processor, db, personal_info_contract, ibet_security_token_escrow_contract ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues share token. token_contract = deploy_share_token_contract( @@ -807,20 +1373,67 @@ def test_normal_5( token_1.tx_hash = "tx_hash" db.add(token_1) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 20000]) - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [ibet_security_token_escrow_contract.address, 10000]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 20000], + ) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [ibet_security_token_escrow_contract.address, 10000], + ) # user1: 20000 user2: 0 - STContractUtils.set_transfer_approve_required(token_contract.address, issuer_address, issuer_private_key, [True]) - STContractUtils.apply_for_transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 10000, "to user1#1"]) - STContractUtils.apply_for_transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_2, 10000, "to user2#1"]) + STContractUtils.set_transfer_approve_required( + token_contract.address, issuer_address, issuer_private_key, [True] + ) + STContractUtils.apply_for_transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 10000, "to user1#1"], + ) + STContractUtils.apply_for_transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, 10000, "to user2#1"], + ) - STContractUtils.cancel_transfer(token_contract.address, issuer_address, issuer_private_key, [0, "to user1#1"]) - STContractUtils.approve_transfer(token_contract.address, issuer_address, issuer_private_key, [1, "to user2#1"]) + STContractUtils.cancel_transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [0, "to user1#1"], + ) + STContractUtils.approve_transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [1, "to user2#1"], + ) # user1: 20000 user2: 10000 STEscrowContractUtils.create_escrow( @@ -829,12 +1442,20 @@ def test_normal_5( user_pk_1, [token_contract.address, user_address_2, 7000, issuer_address, "", ""], ) - latest_security_escrow_id = STEscrowContractUtils.get_latest_escrow_id(ibet_security_token_escrow_contract.address) + latest_security_escrow_id = STEscrowContractUtils.get_latest_escrow_id( + ibet_security_token_escrow_contract.address + ) STEscrowContractUtils.finish_escrow( - ibet_security_token_escrow_contract.address, issuer_address, issuer_private_key, [latest_security_escrow_id] + ibet_security_token_escrow_contract.address, + issuer_address, + issuer_private_key, + [latest_security_escrow_id], ) STEscrowContractUtils.approve_transfer( - ibet_security_token_escrow_contract.address, issuer_address, issuer_private_key, [latest_security_escrow_id, ""] + ibet_security_token_escrow_contract.address, + issuer_address, + issuer_private_key, + [latest_security_escrow_id, ""], ) # user1: 13000 user2: 17000 @@ -844,26 +1465,50 @@ def test_normal_5( user_pk_1, [token_contract.address, user_address_2, 2000, issuer_address, "", ""], ) - latest_security_escrow_id = STEscrowContractUtils.get_latest_escrow_id(ibet_security_token_escrow_contract.address) + latest_security_escrow_id = STEscrowContractUtils.get_latest_escrow_id( + ibet_security_token_escrow_contract.address + ) STEscrowContractUtils.finish_escrow( - ibet_security_token_escrow_contract.address, issuer_address, issuer_private_key, [latest_security_escrow_id] + ibet_security_token_escrow_contract.address, + issuer_address, + issuer_private_key, + [latest_security_escrow_id], ) # user1: 13000 user2: 17000 - STContractUtils.lock(token_contract.address, user_address_1, user_pk_1, [issuer_address, 3000, ""]) - STContractUtils.unlock(token_contract.address, issuer_address, issuer_private_key, [user_address_1, user_address_2, 3000, ""]) + STContractUtils.lock( + token_contract.address, + user_address_1, + user_pk_1, + [issuer_address, 3000, ""], + ) + STContractUtils.unlock( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, user_address_2, 3000, ""], + ) # user1: 10000 user2: 20000 # Insert collection record with above token and current block number list_id = str(uuid.uuid4()) block_number = web3.eth.block_number - _token_holders_list = token_holders_list(token_contract.address, block_number, list_id) + _token_holders_list = token_holders_list( + token_contract.address, block_number, list_id + ) db.add(_token_holders_list) db.commit() # Issuer transfers issued token to user1 again to proceed block_number on chain. - STContractUtils.set_transfer_approve_required(token_contract.address, issuer_address, issuer_private_key, [False]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 20000]) + STContractUtils.set_transfer_approve_required( + token_contract.address, issuer_address, issuer_private_key, [False] + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 20000], + ) # Then execute processor. processor.collect() @@ -886,7 +1531,16 @@ def test_normal_5( assert user2_record.hold_balance == 20000 assert user2_record.locked_balance == 0 - assert len(list(db.query(TokenHolder).filter(TokenHolder.holder_list_id == _token_holders_list.id))) == 2 + assert ( + len( + list( + db.query(TokenHolder).filter( + TokenHolder.holder_list_id == _token_holders_list.id + ) + ) + ) + == 2 + ) # # Share @@ -894,21 +1548,23 @@ def test_normal_5( # - ApplyForTransfer - pending # - Escrow - pending def test_normal_6( - self, - processor, - db, - personal_info_contract, - ibet_security_token_escrow_contract + self, processor, db, personal_info_contract, ibet_security_token_escrow_contract ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues share token. token_contract = deploy_share_token_contract( @@ -927,17 +1583,54 @@ def test_normal_6( token_1.tx_hash = "tx_hash" db.add(token_1) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 20000]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_2, 10000]) - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [ibet_security_token_escrow_contract.address, 10000]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 20000], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, 10000], + ) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [ibet_security_token_escrow_contract.address, 10000], + ) # user1: 20000 user2: 10000 - STContractUtils.set_transfer_approve_required(token_contract.address, issuer_address, issuer_private_key, [True]) - STContractUtils.apply_for_transfer(token_contract.address, user_address_1, user_pk_1, [user_address_2, 10000, "to user2#1"]) + STContractUtils.set_transfer_approve_required( + token_contract.address, issuer_address, issuer_private_key, [True] + ) + STContractUtils.apply_for_transfer( + token_contract.address, + user_address_1, + user_pk_1, + [user_address_2, 10000, "to user2#1"], + ) # user1: 20000 user2: 10000 STEscrowContractUtils.create_escrow( @@ -953,26 +1646,43 @@ def test_normal_6( user_pk_1, [token_contract.address, user_address_2, 3000, issuer_address, "", ""], ) - latest_security_escrow_id = STEscrowContractUtils.get_latest_escrow_id(ibet_security_token_escrow_contract.address) + latest_security_escrow_id = STEscrowContractUtils.get_latest_escrow_id( + ibet_security_token_escrow_contract.address + ) STEscrowContractUtils.finish_escrow( - ibet_security_token_escrow_contract.address, issuer_address, issuer_private_key, [latest_security_escrow_id] + ibet_security_token_escrow_contract.address, + issuer_address, + issuer_private_key, + [latest_security_escrow_id], ) STEscrowContractUtils.approve_transfer( - ibet_security_token_escrow_contract.address, issuer_address, issuer_private_key, [latest_security_escrow_id, ""] + ibet_security_token_escrow_contract.address, + issuer_address, + issuer_private_key, + [latest_security_escrow_id, ""], ) # user1: 17000 user2: 13000 # Insert collection record with above token and current block number list_id = str(uuid.uuid4()) block_number = web3.eth.block_number - _token_holders_list = token_holders_list(token_contract.address, block_number, list_id) + _token_holders_list = token_holders_list( + token_contract.address, block_number, list_id + ) db.add(_token_holders_list) db.commit() # Issuer transfers issued token to user1 again to proceed block_number on chain. - STContractUtils.set_transfer_approve_required(token_contract.address, issuer_address, issuer_private_key, [False]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 20000]) + STContractUtils.set_transfer_approve_required( + token_contract.address, issuer_address, issuer_private_key, [False] + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 20000], + ) # Then execute processor. processor.collect() @@ -993,7 +1703,16 @@ def test_normal_6( assert user1_record.hold_balance == 17000 assert user2_record.hold_balance == 13000 - assert len(list(db.query(TokenHolder).filter(TokenHolder.holder_list_id == _token_holders_list.id))) == 2 + assert ( + len( + list( + db.query(TokenHolder).filter( + TokenHolder.holder_list_id == _token_holders_list.id + ) + ) + ) + == 2 + ) # # StraightBond @@ -1004,21 +1723,29 @@ def test_normal_7( db, personal_info_contract, ibet_exchange_contract, - caplog: pytest.LogCaptureFixture + caplog: pytest.LogCaptureFixture, ): exchange_contract = ibet_exchange_contract processor.collect() - assert 1 == caplog.record_tuples.count((LOG.name, logging.DEBUG, "There are no pending collect batch")) + assert 1 == caplog.record_tuples.count( + (LOG.name, logging.DEBUG, "There are no pending collect batch") + ) user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues bond token. token_contract = deploy_bond_token_contract( @@ -1037,32 +1764,74 @@ def test_normal_7( token_1.tx_hash = "tx_hash" db.add(token_1) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) # Insert collection record with above token and current block number list_id = str(uuid.uuid4()) block_number = web3.eth.block_number - _token_holders_list1 = token_holders_list(token_contract.address, block_number, list_id) + _token_holders_list1 = token_holders_list( + token_contract.address, block_number, list_id + ) db.add(_token_holders_list1) db.commit() - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 20000]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_2, 10000]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [exchange_contract.address, 10000]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 20000], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, 10000], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [exchange_contract.address, 10000], + ) # Insert collection record with above token and current block number list_id = str(uuid.uuid4()) block_number = web3.eth.block_number - _token_holders_list2 = token_holders_list(token_contract.address, block_number, list_id) + _token_holders_list2 = token_holders_list( + token_contract.address, block_number, list_id + ) db.add(_token_holders_list2) db.commit() processor.collect() - assert 1 == caplog.record_tuples.count((LOG.name, logging.INFO, f"Token holder list({_token_holders_list1.list_id}) status changes to be done.")) - assert 1 == caplog.record_tuples.count((LOG.name, logging.INFO, "Collect job has been completed")) + assert 1 == caplog.record_tuples.count( + ( + LOG.name, + logging.INFO, + f"Token holder list({_token_holders_list1.list_id}) status changes to be done.", + ) + ) + assert 1 == caplog.record_tuples.count( + (LOG.name, logging.INFO, "Collect job has been completed") + ) # # StraightBond @@ -1073,19 +1842,25 @@ def test_normal_8( db, personal_info_contract, ibet_exchange_contract, - caplog: pytest.LogCaptureFixture + caplog: pytest.LogCaptureFixture, ): exchange_contract = ibet_exchange_contract user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues bond token. token_contract = deploy_bond_token_contract( @@ -1104,30 +1879,79 @@ def test_normal_8( token_1.tx_hash = "tx_hash" db.add(token_1) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 20000]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_2, 10000]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [exchange_contract.address, 10000]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 20000], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, 10000], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [exchange_contract.address, 10000], + ) # Insert collection record with above token and current block number list_id = str(uuid.uuid4()) block_number = web3.eth.block_number - _token_holders_list1 = token_holders_list(token_contract.address, block_number, list_id) + _token_holders_list1 = token_holders_list( + token_contract.address, block_number, list_id + ) db.add(_token_holders_list1) db.commit() processor.collect() - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 20000]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_2, 10000]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [exchange_contract.address, 10000]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 20000], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, 10000], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [exchange_contract.address, 10000], + ) # Insert collection record with above token and current block number list_id = str(uuid.uuid4()) block_number = web3.eth.block_number - _token_holders_list2 = token_holders_list(token_contract.address, block_number, list_id) + _token_holders_list2 = token_holders_list( + token_contract.address, block_number, list_id + ) db.add(_token_holders_list2) db.commit() processor.collect() @@ -1148,29 +1972,52 @@ def test_normal_8( assert user1_record.hold_balance == 40000 assert user2_record.hold_balance == 20000 - assert len(list(db.query(TokenHolder).filter(TokenHolder.holder_list_id == _token_holders_list1.id))) == 2 - assert len(list(db.query(TokenHolder).filter(TokenHolder.holder_list_id == _token_holders_list2.id))) == 2 + assert ( + len( + list( + db.query(TokenHolder).filter( + TokenHolder.holder_list_id == _token_holders_list1.id + ) + ) + ) + == 2 + ) + assert ( + len( + list( + db.query(TokenHolder).filter( + TokenHolder.holder_list_id == _token_holders_list2.id + ) + ) + ) + == 2 + ) # # StraightBond # Batch does not index former holder who has no balance at the target block number. def test_normal_9( - self, - processor, - db, - personal_info_contract, - ibet_exchange_contract + self, processor, db, personal_info_contract, ibet_exchange_contract ): exchange_contract = ibet_exchange_contract _user_1 = config_eth_account("user1") issuer_address = _user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=_user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=_user_1["keyfile_json"], + password="password".encode("utf-8"), + ) _user_2 = config_eth_account("user2") user_address_1 = _user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=_user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=_user_2["keyfile_json"], + password="password".encode("utf-8"), + ) _user_3 = config_eth_account("user3") user_address_2 = _user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=_user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=_user_3["keyfile_json"], + password="password".encode("utf-8"), + ) # Issuer issues bond token. token_contract = deploy_bond_token_contract( @@ -1189,21 +2036,52 @@ def test_normal_9( token_1.tx_hash = "tx_hash" db.add(token_1) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 30000]) - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [issuer_address, 30000]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 30000], + ) + STContractUtils.transfer( + token_contract.address, user_address_1, user_pk_1, [issuer_address, 30000] + ) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_2, 30000]) - STContractUtils.transfer(token_contract.address, user_address_2, user_pk_2, [issuer_address, 30000]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, 30000], + ) + STContractUtils.transfer( + token_contract.address, user_address_2, user_pk_2, [issuer_address, 30000] + ) # user1: 0 user2: 0 # Insert collection record with above token and current block number list_id = str(uuid.uuid4()) block_number = web3.eth.block_number - _token_holders_list = token_holders_list(token_contract.address, block_number, list_id) + _token_holders_list = token_holders_list( + token_contract.address, block_number, list_id + ) db.add(_token_holders_list) db.flush() @@ -1217,8 +2095,18 @@ def test_normal_9( db.commit() # Issuer transfers issued token to user1 again to proceed block_number on chain. - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 20000]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_2, 20000]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 20000], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, 20000], + ) # Then execute processor. processor.collect() @@ -1239,7 +2127,16 @@ def test_normal_9( assert user1_record is None assert user2_record is None - assert len(list(db.query(TokenHolder).filter(TokenHolder.holder_list_id == _token_holders_list.id))) == 0 + assert ( + len( + list( + db.query(TokenHolder).filter( + TokenHolder.holder_list_id == _token_holders_list.id + ) + ) + ) + == 0 + ) # # When stored checkpoint is 9,999,999 and current block number is 19,999,999, @@ -1250,7 +2147,7 @@ def test_normal_10( db, personal_info_contract, ibet_exchange_contract, - caplog: pytest.LogCaptureFixture + caplog: pytest.LogCaptureFixture, ): exchange_contract = ibet_exchange_contract current_block_number = 20000000 - 1 @@ -1258,7 +2155,10 @@ def test_normal_10( _user_1 = config_eth_account("user1") issuer_address = _user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=_user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=_user_1["keyfile_json"], + password="password".encode("utf-8"), + ) # Issuer issues bond token. token_contract = deploy_bond_token_contract( @@ -1279,29 +2179,60 @@ def test_normal_10( # Insert collection record with above token and checkpoint block number target_list_id = str(uuid.uuid4()) - target_holders_list = token_holders_list(token_contract.address, current_block_number, target_list_id) + target_holders_list = token_holders_list( + token_contract.address, current_block_number, target_list_id + ) db.add(target_holders_list) completed_list_id = str(uuid.uuid4()) - completed_holders_list = token_holders_list(token_contract.address, checkpoint_block_number, completed_list_id, status=TokenHolderBatchStatus.DONE) + completed_holders_list = token_holders_list( + token_contract.address, + checkpoint_block_number, + completed_list_id, + status=TokenHolderBatchStatus.DONE, + ) db.add(completed_holders_list) db.commit() # Setting stored index to 9,999,999 processor.collect() # Then processor call "__process_all" method 10 times. - assert 1 == caplog.record_tuples.count((LOG.name, logging.INFO, f"syncing from=10000000, to=10999999")) - assert 1 == caplog.record_tuples.count((LOG.name, logging.INFO, f"syncing from=11000000, to=11999999")) - assert 1 == caplog.record_tuples.count((LOG.name, logging.INFO, f"syncing from=12000000, to=12999999")) - assert 1 == caplog.record_tuples.count((LOG.name, logging.INFO, f"syncing from=13000000, to=13999999")) - assert 1 == caplog.record_tuples.count((LOG.name, logging.INFO, f"syncing from=14000000, to=14999999")) - assert 1 == caplog.record_tuples.count((LOG.name, logging.INFO, f"syncing from=15000000, to=15999999")) - assert 1 == caplog.record_tuples.count((LOG.name, logging.INFO, f"syncing from=16000000, to=16999999")) - assert 1 == caplog.record_tuples.count((LOG.name, logging.INFO, f"syncing from=17000000, to=17999999")) - assert 1 == caplog.record_tuples.count((LOG.name, logging.INFO, f"syncing from=18000000, to=18999999")) - assert 1 == caplog.record_tuples.count((LOG.name, logging.INFO, f"syncing from=19000000, to=19999999")) + assert 1 == caplog.record_tuples.count( + (LOG.name, logging.INFO, f"syncing from=10000000, to=10999999") + ) + assert 1 == caplog.record_tuples.count( + (LOG.name, logging.INFO, f"syncing from=11000000, to=11999999") + ) + assert 1 == caplog.record_tuples.count( + (LOG.name, logging.INFO, f"syncing from=12000000, to=12999999") + ) + assert 1 == caplog.record_tuples.count( + (LOG.name, logging.INFO, f"syncing from=13000000, to=13999999") + ) + assert 1 == caplog.record_tuples.count( + (LOG.name, logging.INFO, f"syncing from=14000000, to=14999999") + ) + assert 1 == caplog.record_tuples.count( + (LOG.name, logging.INFO, f"syncing from=15000000, to=15999999") + ) + assert 1 == caplog.record_tuples.count( + (LOG.name, logging.INFO, f"syncing from=16000000, to=16999999") + ) + assert 1 == caplog.record_tuples.count( + (LOG.name, logging.INFO, f"syncing from=17000000, to=17999999") + ) + assert 1 == caplog.record_tuples.count( + (LOG.name, logging.INFO, f"syncing from=18000000, to=18999999") + ) + assert 1 == caplog.record_tuples.count( + (LOG.name, logging.INFO, f"syncing from=19000000, to=19999999") + ) db.rollback() - processed_list = db.query(TokenHoldersList).filter(TokenHoldersList.id == target_holders_list.id).first() + processed_list = ( + db.query(TokenHoldersList) + .filter(TokenHoldersList.id == target_holders_list.id) + .first() + ) assert processed_list.block_number == 19999999 assert processed_list.batch_status == TokenHolderBatchStatus.DONE.value @@ -1317,12 +2248,13 @@ def test_error_1( db, personal_info_contract, ibet_exchange_contract, - caplog: pytest.LogCaptureFixture + caplog: pytest.LogCaptureFixture, ): - processor.collect() - assert 1 == caplog.record_tuples.count((LOG.name, logging.DEBUG, "There are no pending collect batch")) + assert 1 == caplog.record_tuples.count( + (LOG.name, logging.DEBUG, "There are no pending collect batch") + ) # # There is target token holders list id with batch_status PENDING. @@ -1333,7 +2265,7 @@ def test_error_2( db, personal_info_contract, ibet_exchange_contract, - caplog: pytest.LogCaptureFixture + caplog: pytest.LogCaptureFixture, ): # Insert collection definition with token address Zero target_token_holders_list = TokenHoldersList() @@ -1346,11 +2278,29 @@ def test_error_2( # Debug message should be shown that points out token contract must be listed. processor.collect() - assert 1 == caplog.record_tuples.count((LOG.name, logging.DEBUG, "Token contract must be listed to TokenList contract.")) - assert 1 == caplog.record_tuples.count((LOG.name, logging.INFO, f"Token holder list({target_token_holders_list.list_id}) status changes to be failed.")) + assert 1 == caplog.record_tuples.count( + ( + LOG.name, + logging.DEBUG, + "Token contract must be listed to TokenList contract.", + ) + ) + assert 1 == caplog.record_tuples.count( + ( + LOG.name, + logging.INFO, + f"Token holder list({target_token_holders_list.list_id}) status changes to be failed.", + ) + ) # Batch status of token holders list expects to be "ERROR" - error_record_num = len(list(db.query(TokenHoldersList).filter(TokenHoldersList.batch_status == TokenHolderBatchStatus.FAILED.value))) + error_record_num = len( + list( + db.query(TokenHoldersList).filter( + TokenHoldersList.batch_status == TokenHolderBatchStatus.FAILED.value + ) + ) + ) assert error_record_num == 1 # @@ -1361,18 +2311,24 @@ def test_error_3( db, personal_info_contract, ibet_exchange_contract, - caplog: pytest.LogCaptureFixture + caplog: pytest.LogCaptureFixture, ): exchange_contract = ibet_exchange_contract user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues bond token. token_contract = deploy_bond_token_contract( @@ -1391,40 +2347,86 @@ def test_error_3( token_1.tx_hash = "tx_hash" db.add(token_1) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 20000]) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [exchange_contract.address, 10000]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 20000], + ) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [exchange_contract.address, 10000], + ) # Insert collection record with above token and current block number list_id = str(uuid.uuid4()) block_number = web3.eth.block_number - _token_holders_list = token_holders_list(token_contract.address, block_number, list_id) + _token_holders_list = token_holders_list( + token_contract.address, block_number, list_id + ) db.add(_token_holders_list) db.commit() mock_lib = MagicMock() - with patch.object(Processor, "_Processor__process_all", return_value=mock_lib) as __sync_all_mock: + with patch.object( + Processor, "_Processor__process_all", return_value=mock_lib + ) as __sync_all_mock: # Then execute processor. __sync_all_mock.return_value = None processor.collect() - _records: List[TokenHolder] = db.query(TokenHolder).filter(TokenHolder.holder_list_id == _token_holders_list.id).all() + _records: List[TokenHolder] = ( + db.query(TokenHolder) + .filter(TokenHolder.holder_list_id == _token_holders_list.id) + .all() + ) assert len(_records) == 0 # # If DB session fails in phase sinking events, batch logs exception message. - def test_error_4(self, main_func, db: Session, ibet_security_token_escrow_contract, personal_info_contract, caplog: pytest.LogCaptureFixture): + def test_error_4( + self, + main_func, + db: Session, + ibet_security_token_escrow_contract, + personal_info_contract, + caplog: pytest.LogCaptureFixture, + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues share token. token_contract = deploy_share_token_contract( @@ -1443,23 +2445,52 @@ def test_error_4(self, main_func, db: Session, ibet_security_token_escrow_contra token_1.tx_hash = "tx_hash" db.add(token_1) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 20000]) - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [ibet_security_token_escrow_contract.address, 10000]) + STContractUtils.transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 20000], + ) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [ibet_security_token_escrow_contract.address, 10000], + ) # Insert collection record with above token and current block number list_id = str(uuid.uuid4()) block_number = web3.eth.block_number - _token_holders_list = token_holders_list(token_contract.address, block_number, list_id) + _token_holders_list = token_holders_list( + token_contract.address, block_number, list_id + ) db.add(_token_holders_list) db.commit() - with patch("batch.indexer_token_holders.INDEXER_SYNC_INTERVAL", None),\ - patch.object(Session, "close", side_effect=SQLAlchemyError()), \ - pytest.raises(TypeError): + with patch( + "batch.indexer_token_holders.INDEXER_SYNC_INTERVAL", None + ), patch.object(Session, "close", side_effect=SQLAlchemyError()), pytest.raises( + TypeError + ): main_func() assert 1 == caplog.text.count("A database error has occurred") caplog.clear() diff --git a/tests/test_batch_indexer_transfer.py b/tests/test_batch_indexer_transfer.py index 0dee2550..ccb55c9e 100644 --- a/tests/test_batch_indexer_transfer.py +++ b/tests/test_batch_indexer_transfer.py @@ -17,44 +17,38 @@ SPDX-License-Identifier: Apache-2.0 """ import json -from datetime import datetime -from eth_keyfile import decode_keyfile_json import logging +from datetime import datetime +from unittest import mock +from unittest.mock import patch + import pytest +from eth_keyfile import decode_keyfile_json from sqlalchemy.exc import InvalidRequestError from sqlalchemy.orm import Session -from unittest import mock -from unittest.mock import patch from app.exceptions import ServiceUnavailableError +from app.model.blockchain import IbetShareContract, IbetStraightBondContract +from app.model.blockchain.tx_params.ibet_share import ( + UpdateParams as IbetShareUpdateParams, +) +from app.model.blockchain.tx_params.ibet_straight_bond import ( + UpdateParams as IbetStraightBondUpdateParams, +) from app.model.db import ( - Token, - TokenType, IDXTransfer, IDXTransferBlockNumber, - IDXTransferSourceEventType -) -from app.model.blockchain import ( - IbetStraightBondContract, - IbetShareContract + IDXTransferSourceEventType, + Token, + TokenType, ) -from app.model.blockchain.tx_params.ibet_straight_bond import UpdateParams as IbetStraightBondUpdateParams -from app.model.blockchain.tx_params.ibet_share import UpdateParams as IbetShareUpdateParams -from app.utils.web3_utils import Web3Wrapper from app.utils.contract_utils import ContractUtils -from batch.indexer_transfer import ( - Processor, - LOG, - main -) -from config import ( - CHAIN_ID, - TX_GAS_LIMIT -) +from app.utils.web3_utils import Web3Wrapper +from batch.indexer_transfer import LOG, Processor, main +from config import CHAIN_ID, TX_GAS_LIMIT from tests.account_config import config_eth_account from tests.utils.contract_utils import PersonalInfoContractTestUtils - web3 = Web3Wrapper() @@ -80,11 +74,13 @@ def processor(db, caplog: pytest.LogCaptureFixture): LOG.setLevel(default_log_level) -def deploy_bond_token_contract(address, - private_key, - personal_info_contract_address, - tradable_exchange_contract_address=None, - transfer_approval_required=None): +def deploy_bond_token_contract( + address, + private_key, + personal_info_contract_address, + tradable_exchange_contract_address=None, + transfer_approval_required=None, +): arguments = [ "token.name", "token.symbol", @@ -94,7 +90,7 @@ def deploy_bond_token_contract(address, 30, "token.return_date", "token.return_amount", - "token.purpose" + "token.purpose", ] bond_contrat = IbetStraightBondContract() token_address, _, _ = bond_contrat.create(arguments, address, private_key) @@ -103,20 +99,22 @@ def deploy_bond_token_contract(address, transferable=True, personal_info_contract_address=personal_info_contract_address, tradable_exchange_contract_address=tradable_exchange_contract_address, - transfer_approval_required=transfer_approval_required + transfer_approval_required=transfer_approval_required, ), tx_from=address, - private_key=private_key + private_key=private_key, ) return ContractUtils.get_contract("IbetStraightBond", token_address) -def deploy_share_token_contract(address, - private_key, - personal_info_contract_address, - tradable_exchange_contract_address=None, - transfer_approval_required=None): +def deploy_share_token_contract( + address, + private_key, + personal_info_contract_address, + tradable_exchange_contract_address=None, + transfer_approval_required=None, +): arguments = [ "token.name", "token.symbol", @@ -126,7 +124,7 @@ def deploy_share_token_contract(address, "token.dividend_record_date", "token.dividend_payment_date", "token.cancellation_date", - 30 + 30, ] share_contract = IbetShareContract() token_address, _, _ = share_contract.create(arguments, address, private_key) @@ -138,14 +136,13 @@ def deploy_share_token_contract(address, transfer_approval_required=transfer_approval_required, ), tx_from=address, - private_key=private_key + private_key=private_key, ) return ContractUtils.get_contract("IbetShare", token_address) class TestProcessor: - ########################################################################### # Normal Case ########################################################################### @@ -189,14 +186,13 @@ def test_normal_1_2(self, processor, db, personal_info_contract): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_bond_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -243,8 +239,7 @@ def test_normal_2_1(self, processor, db, personal_info_contract): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") @@ -253,13 +248,13 @@ def test_normal_2_1(self, processor, db, personal_info_contract): lock_account = config_eth_account("user3") lock_account_pk = decode_keyfile_json( raw_keyfile_json=lock_account["keyfile_json"], - password=lock_account["password"].encode("utf-8") + password=lock_account["password"].encode("utf-8"), ) # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_bond_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -283,42 +278,45 @@ def test_normal_2_1(self, processor, db, personal_info_contract): # Transfer tx_1 = token_contract_1.functions.transferFrom( - issuer_address, - user_address_1, - 40 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) - tx_hash_1, tx_receipt_1 = ContractUtils.send_transaction(tx_1, issuer_private_key) + issuer_address, user_address_1, 40 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) + tx_hash_1, tx_receipt_1 = ContractUtils.send_transaction( + tx_1, issuer_private_key + ) # Unlock (lock -> unlock) tx_2_1 = token_contract_1.functions.lock( - lock_account["address"], - 10, - "" - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + lock_account["address"], 10, "" + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) _, _ = ContractUtils.send_transaction(tx_2_1, issuer_private_key) tx_2_2 = token_contract_1.functions.unlock( - issuer_address, - user_address_1, - 10, - json.dumps({"message": "unlock"}) - ).build_transaction({ - "chainId": CHAIN_ID, - "from": lock_account["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) - tx_hash_2, tx_receipt_2 = ContractUtils.send_transaction(tx_2_2, lock_account_pk) + issuer_address, user_address_1, 10, json.dumps({"message": "unlock"}) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": lock_account["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) + tx_hash_2, tx_receipt_2 = ContractUtils.send_transaction( + tx_2_2, lock_account_pk + ) # Run target process block_number = web3.eth.block_number @@ -338,7 +336,9 @@ def test_normal_2_1(self, processor, db, personal_info_contract): assert _transfer.source_event == IDXTransferSourceEventType.TRANSFER.value assert _transfer.data is None block = web3.eth.get_block(tx_receipt_1["blockNumber"]) - assert _transfer.block_timestamp == datetime.utcfromtimestamp(block["timestamp"]) + assert _transfer.block_timestamp == datetime.utcfromtimestamp( + block["timestamp"] + ) _transfer = _transfer_list[1] assert _transfer.id == 2 @@ -350,7 +350,9 @@ def test_normal_2_1(self, processor, db, personal_info_contract): assert _transfer.source_event == IDXTransferSourceEventType.UNLOCK.value assert _transfer.data == {"message": "unlock"} block = web3.eth.get_block(tx_receipt_2["blockNumber"]) - assert _transfer.block_timestamp == datetime.utcfromtimestamp(block["timestamp"]) + assert _transfer.block_timestamp == datetime.utcfromtimestamp( + block["timestamp"] + ) _idx_transfer_block_number = db.query(IDXTransferBlockNumber).first() assert _idx_transfer_block_number.id == 1 @@ -364,20 +366,19 @@ def test_normal_2_2(self, processor, db, personal_info_contract): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) lock_account = config_eth_account("user3") lock_account_pk = decode_keyfile_json( raw_keyfile_json=lock_account["keyfile_json"], - password=lock_account["password"].encode("utf-8") + password=lock_account["password"].encode("utf-8"), ) # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_bond_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -401,28 +402,27 @@ def test_normal_2_2(self, processor, db, personal_info_contract): # Unlock (lock -> unlock) tx_1_1 = token_contract_1.functions.lock( - lock_account["address"], - 10, - "" - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + lock_account["address"], 10, "" + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) _, _ = ContractUtils.send_transaction(tx_1_1, issuer_private_key) tx_1_2 = token_contract_1.functions.unlock( - issuer_address, - issuer_address, - 10, - json.dumps({"message": "unlock"}) - ).build_transaction({ - "chainId": CHAIN_ID, - "from": lock_account["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + issuer_address, issuer_address, 10, json.dumps({"message": "unlock"}) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": lock_account["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) _, _ = ContractUtils.send_transaction(tx_1_2, lock_account_pk) # Run target process @@ -446,8 +446,7 @@ def test_normal_3_1(self, processor, db, personal_info_contract): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") @@ -459,13 +458,13 @@ def test_normal_3_1(self, processor, db, personal_info_contract): lock_account = config_eth_account("user4") lock_account_pk = decode_keyfile_json( raw_keyfile_json=lock_account["keyfile_json"], - password=lock_account["password"].encode("utf-8") + password=lock_account["password"].encode("utf-8"), ) # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_bond_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -489,79 +488,85 @@ def test_normal_3_1(self, processor, db, personal_info_contract): # Transfer tx_1 = token_contract_1.functions.transferFrom( - issuer_address, - user_address_1, - 40 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) - tx_hash_1, tx_receipt_1 = ContractUtils.send_transaction(tx_1, issuer_private_key) + issuer_address, user_address_1, 40 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) + tx_hash_1, tx_receipt_1 = ContractUtils.send_transaction( + tx_1, issuer_private_key + ) tx_2 = token_contract_1.functions.transferFrom( - issuer_address, - user_address_2, - 30 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) - tx_hash_2, tx_receipt_2 = ContractUtils.send_transaction(tx_2, issuer_private_key) + issuer_address, user_address_2, 30 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) + tx_hash_2, tx_receipt_2 = ContractUtils.send_transaction( + tx_2, issuer_private_key + ) # Unlock (lock -> unlock) tx_3_1 = token_contract_1.functions.lock( - lock_account["address"], - 10, - "" - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + lock_account["address"], 10, "" + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) _, _ = ContractUtils.send_transaction(tx_3_1, issuer_private_key) tx_3_2 = token_contract_1.functions.unlock( - issuer_address, - user_address_1, - 10, - json.dumps({"message": "unlock"}) - ).build_transaction({ - "chainId": CHAIN_ID, - "from": lock_account["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) - tx_hash_3, tx_receipt_3 = ContractUtils.send_transaction(tx_3_2, lock_account_pk) + issuer_address, user_address_1, 10, json.dumps({"message": "unlock"}) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": lock_account["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) + tx_hash_3, tx_receipt_3 = ContractUtils.send_transaction( + tx_3_2, lock_account_pk + ) tx_4_1 = token_contract_1.functions.lock( - lock_account["address"], - 10, - "" - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + lock_account["address"], 10, "" + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) _, _ = ContractUtils.send_transaction(tx_4_1, issuer_private_key) tx_4_2 = token_contract_1.functions.unlock( - issuer_address, - user_address_1, - 10, - json.dumps({"message": "unlock"}) - ).build_transaction({ - "chainId": CHAIN_ID, - "from": lock_account["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) - tx_hash_4, tx_receipt_4 = ContractUtils.send_transaction(tx_4_2, lock_account_pk) + issuer_address, user_address_1, 10, json.dumps({"message": "unlock"}) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": lock_account["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) + tx_hash_4, tx_receipt_4 = ContractUtils.send_transaction( + tx_4_2, lock_account_pk + ) # Run target process block_number = web3.eth.block_number @@ -581,7 +586,9 @@ def test_normal_3_1(self, processor, db, personal_info_contract): assert _transfer.source_event == IDXTransferSourceEventType.TRANSFER.value assert _transfer.data is None block = web3.eth.get_block(tx_receipt_1["blockNumber"]) - assert _transfer.block_timestamp == datetime.utcfromtimestamp(block["timestamp"]) + assert _transfer.block_timestamp == datetime.utcfromtimestamp( + block["timestamp"] + ) _transfer = _transfer_list[1] assert _transfer.id == 2 @@ -593,7 +600,9 @@ def test_normal_3_1(self, processor, db, personal_info_contract): assert _transfer.source_event == IDXTransferSourceEventType.TRANSFER.value assert _transfer.data is None block = web3.eth.get_block(tx_receipt_2["blockNumber"]) - assert _transfer.block_timestamp == datetime.utcfromtimestamp(block["timestamp"]) + assert _transfer.block_timestamp == datetime.utcfromtimestamp( + block["timestamp"] + ) _transfer = _transfer_list[2] assert _transfer.id == 3 @@ -605,7 +614,9 @@ def test_normal_3_1(self, processor, db, personal_info_contract): assert _transfer.source_event == IDXTransferSourceEventType.UNLOCK.value assert _transfer.data == {"message": "unlock"} block = web3.eth.get_block(tx_receipt_3["blockNumber"]) - assert _transfer.block_timestamp == datetime.utcfromtimestamp(block["timestamp"]) + assert _transfer.block_timestamp == datetime.utcfromtimestamp( + block["timestamp"] + ) _transfer = _transfer_list[3] assert _transfer.id == 4 @@ -617,7 +628,9 @@ def test_normal_3_1(self, processor, db, personal_info_contract): assert _transfer.source_event == IDXTransferSourceEventType.UNLOCK.value assert _transfer.data == {"message": "unlock"} block = web3.eth.get_block(tx_receipt_4["blockNumber"]) - assert _transfer.block_timestamp == datetime.utcfromtimestamp(block["timestamp"]) + assert _transfer.block_timestamp == datetime.utcfromtimestamp( + block["timestamp"] + ) _idx_transfer_block_number = db.query(IDXTransferBlockNumber).first() assert _idx_transfer_block_number.id == 1 @@ -631,26 +644,33 @@ def test_normal_3_2(self, processor, db, personal_info_contract): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) user_4 = config_eth_account("user3") user_address_3 = user_4["address"] - user_pk_3 = decode_keyfile_json(raw_keyfile_json=user_4["keyfile_json"], password="password".encode("utf-8")) + user_pk_3 = decode_keyfile_json( + raw_keyfile_json=user_4["keyfile_json"], password="password".encode("utf-8") + ) user_5 = config_eth_account("user3") user_address_4 = user_5["address"] - user_pk_4 = decode_keyfile_json(raw_keyfile_json=user_5["keyfile_json"], password="password".encode("utf-8")) + user_pk_4 = decode_keyfile_json( + raw_keyfile_json=user_5["keyfile_json"], password="password".encode("utf-8") + ) # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_bond_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -665,32 +685,65 @@ def test_normal_3_2(self, processor, db, personal_info_contract): # Before run(consume accumulated events) processor.sync_new_logs() - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_3, user_pk_3, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_4, user_pk_4, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_3, + user_pk_3, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_4, + user_pk_4, + [issuer_address, ""], + ) # Bulk Transfer address_list1 = [user_address_1, user_address_2, user_address_3] value_list1 = [10, 20, 30] - tx = token_contract_1.functions.bulkTransfer(address_list1, value_list1).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = token_contract_1.functions.bulkTransfer( + address_list1, value_list1 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) # BulkTransfer: 2nd tx_hash_1, tx_receipt_1 = ContractUtils.send_transaction(tx, issuer_private_key) address_list2 = [user_address_1, user_address_2, user_address_3, user_address_4] value_list2 = [1, 2, 3, 4] - tx = token_contract_1.functions.bulkTransfer(address_list2, value_list2).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = token_contract_1.functions.bulkTransfer( + address_list2, value_list2 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) tx_hash_2, tx_receipt_2 = ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -704,7 +757,7 @@ def test_normal_3_2(self, processor, db, personal_info_contract): block = web3.eth.get_block(tx_receipt_1["blockNumber"]) for i in range(0, 3): _transfer = _transfer_list[i] - assert _transfer.id == i+1 + assert _transfer.id == i + 1 assert _transfer.transaction_hash == tx_hash_1 assert _transfer.token_address == token_address_1 assert _transfer.from_address == issuer_address @@ -712,12 +765,14 @@ def test_normal_3_2(self, processor, db, personal_info_contract): assert _transfer.amount == value_list1[i] assert _transfer.source_event == IDXTransferSourceEventType.TRANSFER.value assert _transfer.data is None - assert _transfer.block_timestamp == datetime.utcfromtimestamp(block["timestamp"]) + assert _transfer.block_timestamp == datetime.utcfromtimestamp( + block["timestamp"] + ) block = web3.eth.get_block(tx_receipt_2["blockNumber"]) for i in range(0, 4): - _transfer = _transfer_list[i+3] - assert _transfer.id == i+1+3 + _transfer = _transfer_list[i + 3] + assert _transfer.id == i + 1 + 3 assert _transfer.transaction_hash == tx_hash_2 assert _transfer.token_address == token_address_1 assert _transfer.from_address == issuer_address @@ -725,7 +780,9 @@ def test_normal_3_2(self, processor, db, personal_info_contract): assert _transfer.amount == value_list2[i] assert _transfer.source_event == IDXTransferSourceEventType.TRANSFER.value assert _transfer.data is None - assert _transfer.block_timestamp == datetime.utcfromtimestamp(block["timestamp"]) + assert _transfer.block_timestamp == datetime.utcfromtimestamp( + block["timestamp"] + ) _idx_transfer_block_number = db.query(IDXTransferBlockNumber).first() assert _idx_transfer_block_number.id == 1 @@ -737,8 +794,7 @@ def test_normal_4(self, processor, db, personal_info_contract): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] @@ -746,9 +802,9 @@ def test_normal_4(self, processor, db, personal_info_contract): user_address_2 = user_3["address"] # Prepare data : Token1 - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_bond_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -759,9 +815,9 @@ def test_normal_4(self, processor, db, personal_info_contract): db.add(token_1) # Prepare data : Token2 - token_contract_2 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_2 = deploy_bond_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_2 = token_contract_2.address token_2 = Token() @@ -775,35 +831,51 @@ def test_normal_4(self, processor, db, personal_info_contract): db.commit() # Transfer(Token1) - tx = token_contract_1.functions.transferFrom(issuer_address, user_address_1, 40).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = token_contract_1.functions.transferFrom( + issuer_address, user_address_1, 40 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) tx_hash_1, tx_receipt_1 = ContractUtils.send_transaction(tx, issuer_private_key) - tx = token_contract_1.functions.transferFrom(issuer_address, user_address_2, 30).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = token_contract_1.functions.transferFrom( + issuer_address, user_address_2, 30 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) tx_hash_2, tx_receipt_2 = ContractUtils.send_transaction(tx, issuer_private_key) # Transfer(Token2) - tx = token_contract_2.functions.transferFrom(issuer_address, user_address_1, 40).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = token_contract_2.functions.transferFrom( + issuer_address, user_address_1, 40 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) tx_hash_3, tx_receipt_3 = ContractUtils.send_transaction(tx, issuer_private_key) - tx = token_contract_2.functions.transferFrom(issuer_address, user_address_2, 30).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = token_contract_2.functions.transferFrom( + issuer_address, user_address_2, 30 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) tx_hash_4, tx_receipt_4 = ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -823,7 +895,9 @@ def test_normal_4(self, processor, db, personal_info_contract): assert _transfer.source_event == IDXTransferSourceEventType.TRANSFER.value assert _transfer.data is None block = web3.eth.get_block(tx_receipt_1["blockNumber"]) - assert _transfer.block_timestamp == datetime.utcfromtimestamp(block["timestamp"]) + assert _transfer.block_timestamp == datetime.utcfromtimestamp( + block["timestamp"] + ) _transfer = _transfer_list[1] assert _transfer.id == 2 assert _transfer.transaction_hash == tx_hash_2 @@ -834,7 +908,9 @@ def test_normal_4(self, processor, db, personal_info_contract): assert _transfer.source_event == IDXTransferSourceEventType.TRANSFER.value assert _transfer.data is None block = web3.eth.get_block(tx_receipt_2["blockNumber"]) - assert _transfer.block_timestamp == datetime.utcfromtimestamp(block["timestamp"]) + assert _transfer.block_timestamp == datetime.utcfromtimestamp( + block["timestamp"] + ) _transfer = _transfer_list[2] assert _transfer.id == 3 @@ -846,7 +922,9 @@ def test_normal_4(self, processor, db, personal_info_contract): assert _transfer.source_event == IDXTransferSourceEventType.TRANSFER.value assert _transfer.data is None block = web3.eth.get_block(tx_receipt_3["blockNumber"]) - assert _transfer.block_timestamp == datetime.utcfromtimestamp(block["timestamp"]) + assert _transfer.block_timestamp == datetime.utcfromtimestamp( + block["timestamp"] + ) _transfer = _transfer_list[3] assert _transfer.id == 4 @@ -858,7 +936,9 @@ def test_normal_4(self, processor, db, personal_info_contract): assert _transfer.source_event == IDXTransferSourceEventType.TRANSFER.value assert _transfer.data is None block = web3.eth.get_block(tx_receipt_4["blockNumber"]) - assert _transfer.block_timestamp == datetime.utcfromtimestamp(block["timestamp"]) + assert _transfer.block_timestamp == datetime.utcfromtimestamp( + block["timestamp"] + ) _idx_transfer_block_number = db.query(IDXTransferBlockNumber).first() assert _idx_transfer_block_number.id == 1 @@ -868,7 +948,9 @@ def test_normal_4(self, processor, db, personal_info_contract): # If block number processed in batch is equal or greater than current block number, # batch logs "skip process". @mock.patch("web3.eth.Eth.block_number", 100) - def test_normal_5(self, processor: Processor, db: Session, caplog: pytest.LogCaptureFixture): + def test_normal_5( + self, processor: Processor, db: Session, caplog: pytest.LogCaptureFixture + ): _idx_position_bond_block_number = IDXTransferBlockNumber() _idx_position_bond_block_number.id = 1 _idx_position_bond_block_number.latest_block_number = 1000 @@ -876,15 +958,25 @@ def test_normal_5(self, processor: Processor, db: Session, caplog: pytest.LogCap db.commit() processor.sync_new_logs() - assert 1 == caplog.record_tuples.count((LOG.name, logging.DEBUG, "skip process")) + assert 1 == caplog.record_tuples.count( + (LOG.name, logging.DEBUG, "skip process") + ) # # Newly tokens added - def test_normal_6(self, processor: Processor, db: Session, personal_info_contract, ibet_security_token_escrow_contract): + def test_normal_6( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_security_token_escrow_contract, + ): escrow_contract = ibet_security_token_escrow_contract user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues bond token. token_contract1 = deploy_bond_token_contract( @@ -943,17 +1035,22 @@ def test_normal_6(self, processor: Processor, db: Session, personal_info_contrac # # If each error occurs, batch will output logs and continue next sync. - def test_error_1(self, main_func, db:Session, personal_info_contract, caplog: pytest.LogCaptureFixture): + def test_error_1( + self, + main_func, + db: Session, + personal_info_contract, + caplog: pytest.LogCaptureFixture, + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract_1 = deploy_bond_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -966,17 +1063,19 @@ def test_error_1(self, main_func, db:Session, personal_info_contract, caplog: py db.commit() # Run mainloop once and fail with web3 utils error - with patch("batch.indexer_transfer.INDEXER_SYNC_INTERVAL", None),\ - patch.object(web3.eth, "contract", side_effect=ServiceUnavailableError()), \ - pytest.raises(TypeError): + with patch("batch.indexer_transfer.INDEXER_SYNC_INTERVAL", None), patch.object( + web3.eth, "contract", side_effect=ServiceUnavailableError() + ), pytest.raises(TypeError): main_func() - assert 1 == caplog.record_tuples.count((LOG.name, logging.WARNING, "An external service was unavailable")) + assert 1 == caplog.record_tuples.count( + (LOG.name, logging.WARNING, "An external service was unavailable") + ) caplog.clear() # Run mainloop once and fail with sqlalchemy InvalidRequestError - with patch("batch.indexer_transfer.INDEXER_SYNC_INTERVAL", None),\ - patch.object(Session, "query", side_effect=InvalidRequestError()), \ - pytest.raises(TypeError): + with patch("batch.indexer_transfer.INDEXER_SYNC_INTERVAL", None), patch.object( + Session, "query", side_effect=InvalidRequestError() + ), pytest.raises(TypeError): main_func() assert 1 == caplog.text.count("A database error has occurred") caplog.clear() diff --git a/tests/test_batch_indexer_transfer_approval.py b/tests/test_batch_indexer_transfer_approval.py index b908e9a6..8711d397 100644 --- a/tests/test_batch_indexer_transfer_approval.py +++ b/tests/test_batch_indexer_transfer_approval.py @@ -16,39 +16,46 @@ SPDX-License-Identifier: Apache-2.0 """ -from datetime import datetime -from eth_keyfile import decode_keyfile_json import logging -import pytest -from sqlalchemy.exc import SQLAlchemyError -from sqlalchemy.orm import Session +from datetime import datetime from unittest import mock from unittest.mock import patch from uuid import UUID +import pytest +from eth_keyfile import decode_keyfile_json +from sqlalchemy.exc import SQLAlchemyError +from sqlalchemy.orm import Session + import config from app.exceptions import ServiceUnavailableError +from app.model.blockchain import IbetShareContract, IbetStraightBondContract +from app.model.blockchain.tx_params.ibet_share import ( + UpdateParams as IbetShareUpdateParams, +) +from app.model.blockchain.tx_params.ibet_straight_bond import ( + UpdateParams as IbetStraightBondUpdateParams, +) from app.model.db import ( - Token, - TokenType, IDXTransferApproval, IDXTransferApprovalBlockNumber, Notification, - NotificationType + NotificationType, + Token, + TokenType, ) -from app.model.blockchain import IbetStraightBondContract, IbetShareContract -from app.model.blockchain.tx_params.ibet_straight_bond import UpdateParams as IbetStraightBondUpdateParams -from app.model.blockchain.tx_params.ibet_share import UpdateParams as IbetShareUpdateParams -from app.utils.web3_utils import Web3Wrapper from app.utils.contract_utils import ContractUtils -from batch.indexer_transfer_approval import Processor, LOG, main +from app.utils.web3_utils import Web3Wrapper +from batch.indexer_transfer_approval import LOG, Processor, main from config import CHAIN_ID, TX_GAS_LIMIT from tests.account_config import config_eth_account from tests.utils.contract_utils import ( IbetSecurityTokenContractTestUtils as STContractUtils, - PersonalInfoContractTestUtils, +) +from tests.utils.contract_utils import ( IbetSecurityTokenEscrowContractTestUtils as STEscrowContractUtils, ) +from tests.utils.contract_utils import PersonalInfoContractTestUtils web3 = Web3Wrapper() @@ -75,11 +82,13 @@ def processor(db, caplog: pytest.LogCaptureFixture): LOG.setLevel(default_log_level) -def deploy_bond_token_contract(address, - private_key, - personal_info_contract_address, - tradable_exchange_contract_address=None, - transfer_approval_required=None): +def deploy_bond_token_contract( + address, + private_key, + personal_info_contract_address, + tradable_exchange_contract_address=None, + transfer_approval_required=None, +): arguments = [ "token.name", "token.symbol", @@ -89,7 +98,7 @@ def deploy_bond_token_contract(address, 30, "token.return_date", "token.return_amount", - "token.purpose" + "token.purpose", ] bond_contrat = IbetStraightBondContract() token_address, _, _ = bond_contrat.create(arguments, address, private_key) @@ -107,11 +116,13 @@ def deploy_bond_token_contract(address, return ContractUtils.get_contract("IbetStraightBond", token_address) -def deploy_share_token_contract(address, - private_key, - personal_info_contract_address, - tradable_exchange_contract_address=None, - transfer_approval_required=None): +def deploy_share_token_contract( + address, + private_key, + personal_info_contract_address, + tradable_exchange_contract_address=None, + transfer_approval_required=None, +): arguments = [ "token.name", "token.symbol", @@ -121,7 +132,7 @@ def deploy_share_token_contract(address, "token.dividend_record_date", "token.dividend_payment_date", "token.cancellation_date", - 30 + 30, ] share_contract = IbetShareContract() token_address, _, _ = share_contract.create(arguments, address, private_key) @@ -140,7 +151,6 @@ def deploy_share_token_contract(address, class TestProcessor: - ########################################################################### # Normal Case ########################################################################### @@ -175,7 +185,9 @@ def test_normal_1_1(self, processor, db, personal_info_contract): _notification_list = db.query(Notification).all() assert len(_notification_list) == 0 - _idx_transfer_approval_block_number = db.query(IDXTransferApprovalBlockNumber).first() + _idx_transfer_approval_block_number = db.query( + IDXTransferApprovalBlockNumber + ).first() assert _idx_transfer_approval_block_number.id == 1 assert _idx_transfer_approval_block_number.latest_block_number == block_number @@ -186,15 +198,16 @@ def test_normal_1_2(self, processor, db, personal_info_contract): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address, - transfer_approval_required=True) + token_contract_1 = deploy_bond_token_contract( + issuer_address, + issuer_private_key, + personal_info_contract.address, + transfer_approval_required=True, + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -232,7 +245,9 @@ def test_normal_1_2(self, processor, db, personal_info_contract): _notification_list = db.query(Notification).all() assert len(_notification_list) == 0 - _idx_transfer_approval_block_number = db.query(IDXTransferApprovalBlockNumber).first() + _idx_transfer_approval_block_number = db.query( + IDXTransferApprovalBlockNumber + ).first() assert _idx_transfer_approval_block_number.id == 1 assert _idx_transfer_approval_block_number.latest_block_number == block_number @@ -244,21 +259,21 @@ def test_normal_2_1(self, processor, db, personal_info_contract): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address, - transfer_approval_required=True) + token_contract_1 = deploy_bond_token_contract( + issuer_address, + issuer_private_key, + personal_info_contract.address, + transfer_approval_required=True, + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -287,28 +302,28 @@ def test_normal_2_1(self, processor, db, personal_info_contract): # Transfer tx = token_contract_1.functions.transferFrom( - issuer_address, - user_address_1, - 40 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + issuer_address, user_address_1, 40 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # ApplyForTransfer tx = token_contract_1.functions.applyForTransfer( - issuer_address, - 30, - "" - ).build_transaction({ - "chainId": CHAIN_ID, - "from": user_address_1, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + issuer_address, 30, "" + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": user_address_1, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) _, tx_receipt_1 = ContractUtils.send_transaction(tx, user_private_key_1) # Run target process @@ -328,7 +343,10 @@ def test_normal_2_1(self, processor, db, personal_info_contract): assert _transfer_approval.amount == 30 assert _transfer_approval.application_datetime is None block = web3.eth.get_block(tx_receipt_1["blockNumber"]) - assert _transfer_approval.application_blocktimestamp == datetime.utcfromtimestamp(block["timestamp"]) + assert ( + _transfer_approval.application_blocktimestamp + == datetime.utcfromtimestamp(block["timestamp"]) + ) assert _transfer_approval.approval_datetime is None assert _transfer_approval.approval_blocktimestamp is None assert _transfer_approval.cancelled is None @@ -346,10 +364,12 @@ def test_normal_2_1(self, processor, db, personal_info_contract): assert _notification.metainfo == { "token_type": token_1.type, "token_address": token_address_1, - "id": 1 + "id": 1, } - _idx_transfer_approval_block_number = db.query(IDXTransferApprovalBlockNumber).first() + _idx_transfer_approval_block_number = db.query( + IDXTransferApprovalBlockNumber + ).first() assert _idx_transfer_approval_block_number.id == 1 assert _idx_transfer_approval_block_number.latest_block_number == block_number @@ -362,21 +382,21 @@ def test_normal_2_2_1(self, processor, db, personal_info_contract): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address, - transfer_approval_required=True) + token_contract_1 = deploy_bond_token_contract( + issuer_address, + issuer_private_key, + personal_info_contract.address, + transfer_approval_required=True, + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -395,40 +415,39 @@ def test_normal_2_2_1(self, processor, db, personal_info_contract): # Transfer: issuer -> user tx_1 = token_contract_1.functions.transferFrom( - issuer_address, - user_address_1, - 40 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + issuer_address, user_address_1, 40 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx_1, issuer_private_key) # ApplyForTransfer from user tx_2 = token_contract_1.functions.applyForTransfer( - issuer_address, - 30, - "" - ).build_transaction({ - "chainId": CHAIN_ID, - "from": user_address_1, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + issuer_address, 30, "" + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": user_address_1, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) _, tx_receipt_2 = ContractUtils.send_transaction(tx_2, user_private_key_1) # CancelTransfer from issuer - tx_3 = token_contract_1.functions.cancelTransfer( - 0, - "" - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx_3 = token_contract_1.functions.cancelTransfer(0, "").build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) _, tx_receipt_3 = ContractUtils.send_transaction(tx_3, issuer_private_key) # Run target process @@ -450,7 +469,10 @@ def test_normal_2_2_1(self, processor, db, personal_info_contract): assert _transfer_approval.to_address == issuer_address assert _transfer_approval.amount == 30 assert _transfer_approval.application_datetime is None - assert _transfer_approval.application_blocktimestamp == datetime.utcfromtimestamp(block["timestamp"]) + assert ( + _transfer_approval.application_blocktimestamp + == datetime.utcfromtimestamp(block["timestamp"]) + ) assert _transfer_approval.approval_datetime is None assert _transfer_approval.approval_blocktimestamp is None assert _transfer_approval.cancelled is True @@ -468,10 +490,12 @@ def test_normal_2_2_1(self, processor, db, personal_info_contract): assert _notification.metainfo == { "token_type": token_1.type, "token_address": token_address_1, - "id": 1 + "id": 1, } - _idx_transfer_approval_block_number = db.query(IDXTransferApprovalBlockNumber).first() + _idx_transfer_approval_block_number = db.query( + IDXTransferApprovalBlockNumber + ).first() assert _idx_transfer_approval_block_number.id == 1 assert _idx_transfer_approval_block_number.latest_block_number == block_number @@ -484,21 +508,21 @@ def test_normal_2_2_2(self, processor, db, personal_info_contract): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address, - transfer_approval_required=True) + token_contract_1 = deploy_bond_token_contract( + issuer_address, + issuer_private_key, + personal_info_contract.address, + transfer_approval_required=True, + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -517,40 +541,39 @@ def test_normal_2_2_2(self, processor, db, personal_info_contract): # Transfer: issuer -> user tx_1 = token_contract_1.functions.transferFrom( - issuer_address, - user_address_1, - 40 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + issuer_address, user_address_1, 40 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx_1, issuer_private_key) # ApplyForTransfer from user tx_2 = token_contract_1.functions.applyForTransfer( - issuer_address, - 30, - "" - ).build_transaction({ - "chainId": CHAIN_ID, - "from": user_address_1, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + issuer_address, 30, "" + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": user_address_1, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) _, tx_receipt_2 = ContractUtils.send_transaction(tx_2, user_private_key_1) # CancelTransfer from applicant - tx_3 = token_contract_1.functions.cancelTransfer( - 0, - "" - ).build_transaction({ - "chainId": CHAIN_ID, - "from": user_address_1, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx_3 = token_contract_1.functions.cancelTransfer(0, "").build_transaction( + { + "chainId": CHAIN_ID, + "from": user_address_1, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) _, tx_receipt_3 = ContractUtils.send_transaction(tx_3, user_private_key_1) # Run target process @@ -572,7 +595,10 @@ def test_normal_2_2_2(self, processor, db, personal_info_contract): assert _transfer_approval.to_address == issuer_address assert _transfer_approval.amount == 30 assert _transfer_approval.application_datetime is None - assert _transfer_approval.application_blocktimestamp == datetime.utcfromtimestamp(block["timestamp"]) + assert ( + _transfer_approval.application_blocktimestamp + == datetime.utcfromtimestamp(block["timestamp"]) + ) assert _transfer_approval.approval_datetime is None assert _transfer_approval.approval_blocktimestamp is None assert _transfer_approval.cancelled is True @@ -590,36 +616,38 @@ def test_normal_2_2_2(self, processor, db, personal_info_contract): assert _notification.metainfo == { "token_type": token_1.type, "token_address": token_address_1, - "id": 1 + "id": 1, } - _idx_transfer_approval_block_number = db.query(IDXTransferApprovalBlockNumber).first() + _idx_transfer_approval_block_number = db.query( + IDXTransferApprovalBlockNumber + ).first() assert _idx_transfer_approval_block_number.id == 1 assert _idx_transfer_approval_block_number.latest_block_number == block_number # # Event log # - ibetSecurityToken: ApproveTransfer (from issuer) - @pytest.mark.freeze_time('2021-04-27 12:34:56') + @pytest.mark.freeze_time("2021-04-27 12:34:56") def test_normal_2_3(self, processor, db, personal_info_contract): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address, - transfer_approval_required=True) + token_contract_1 = deploy_bond_token_contract( + issuer_address, + issuer_private_key, + personal_info_contract.address, + transfer_approval_required=True, + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -638,42 +666,43 @@ def test_normal_2_3(self, processor, db, personal_info_contract): # Transfer: issuer -> user tx = token_contract_1.functions.transferFrom( - issuer_address, - user_address_1, - 40 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + issuer_address, user_address_1, 40 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) # ApplyForTransfer from user tx = token_contract_1.functions.applyForTransfer( - issuer_address, - 30, - "" - ).build_transaction({ - "chainId": CHAIN_ID, - "from": user_address_1, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + issuer_address, 30, "" + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": user_address_1, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) _, tx_receipt_1 = ContractUtils.send_transaction(tx, user_private_key_1) block_1 = web3.eth.get_block(tx_receipt_1["blockNumber"]) # ApproveTransfer from issuer now = datetime.utcnow() tx = token_contract_1.functions.approveTransfer( - 0, - str(now.timestamp()) - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + 0, str(now.timestamp()) + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) _, tx_receipt_2 = ContractUtils.send_transaction(tx, issuer_private_key) # Run target process @@ -693,10 +722,15 @@ def test_normal_2_3(self, processor, db, personal_info_contract): assert _transfer_approval.to_address == issuer_address assert _transfer_approval.amount == 30 assert _transfer_approval.application_datetime is None - assert _transfer_approval.application_blocktimestamp == datetime.utcfromtimestamp(block_1["timestamp"]) + assert ( + _transfer_approval.application_blocktimestamp + == datetime.utcfromtimestamp(block_1["timestamp"]) + ) assert _transfer_approval.approval_datetime == now block_2 = web3.eth.get_block(tx_receipt_2["blockNumber"]) - assert _transfer_approval.approval_blocktimestamp == datetime.utcfromtimestamp(block_2["timestamp"]) + assert _transfer_approval.approval_blocktimestamp == datetime.utcfromtimestamp( + block_2["timestamp"] + ) assert _transfer_approval.cancelled is None assert _transfer_approval.transfer_approved is True @@ -712,39 +746,43 @@ def test_normal_2_3(self, processor, db, personal_info_contract): assert _notification.metainfo == { "token_type": token_1.type, "token_address": token_address_1, - "id": 1 + "id": 1, } - _idx_transfer_approval_block_number = db.query(IDXTransferApprovalBlockNumber).first() + _idx_transfer_approval_block_number = db.query( + IDXTransferApprovalBlockNumber + ).first() assert _idx_transfer_approval_block_number.id == 1 assert _idx_transfer_approval_block_number.latest_block_number == block_number # # Event log # - Exchange: ApplyForTransfer - @pytest.mark.freeze_time('2021-04-27 12:34:56') - def test_normal_2_4(self, processor, db, personal_info_contract, ibet_security_token_escrow_contract): + @pytest.mark.freeze_time("2021-04-27 12:34:56") + def test_normal_2_4( + self, processor, db, personal_info_contract, ibet_security_token_escrow_contract + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address, - tradable_exchange_contract_address=ibet_security_token_escrow_contract.address, - transfer_approval_required=True) + token_contract_1 = deploy_bond_token_contract( + issuer_address, + issuer_private_key, + personal_info_contract.address, + tradable_exchange_contract_address=ibet_security_token_escrow_contract.address, + transfer_approval_required=True, + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -763,26 +801,27 @@ def test_normal_2_4(self, processor, db, personal_info_contract, ibet_security_t # Deposit tx = token_contract_1.functions.transferFrom( - issuer_address, - user_address_1, - 40 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + issuer_address, user_address_1, 40 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) tx = token_contract_1.functions.transfer( - ibet_security_token_escrow_contract.address, - 40 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": user_address_1, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ibet_security_token_escrow_contract.address, 40 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": user_address_1, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, user_private_key_1) # ApplyForTransfer @@ -793,13 +832,15 @@ def test_normal_2_4(self, processor, db, personal_info_contract, ibet_security_t 30, user_address_1, str(now.timestamp()), - "" - ).build_transaction({ - "chainId": CHAIN_ID, - "from": user_address_1, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + "", + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": user_address_1, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) _, tx_receipt_1 = ContractUtils.send_transaction(tx, user_private_key_1) # Run target process @@ -812,14 +853,20 @@ def test_normal_2_4(self, processor, db, personal_info_contract, ibet_security_t _transfer_approval = _transfer_approval_list[0] assert _transfer_approval.id == 1 assert _transfer_approval.token_address == token_address_1 - assert _transfer_approval.exchange_address == ibet_security_token_escrow_contract.address + assert ( + _transfer_approval.exchange_address + == ibet_security_token_escrow_contract.address + ) assert _transfer_approval.application_id == 1 assert _transfer_approval.from_address == user_address_1 assert _transfer_approval.to_address == user_address_2 assert _transfer_approval.amount == 30 assert _transfer_approval.application_datetime == now block = web3.eth.get_block(tx_receipt_1["blockNumber"]) - assert _transfer_approval.application_blocktimestamp == datetime.utcfromtimestamp(block["timestamp"]) + assert ( + _transfer_approval.application_blocktimestamp + == datetime.utcfromtimestamp(block["timestamp"]) + ) assert _transfer_approval.approval_datetime is None assert _transfer_approval.approval_blocktimestamp is None assert _transfer_approval.cancelled is None @@ -837,10 +884,12 @@ def test_normal_2_4(self, processor, db, personal_info_contract, ibet_security_t assert _notification.metainfo == { "token_type": token_1.type, "token_address": token_address_1, - "id": 1 + "id": 1, } - _idx_transfer_approval_block_number = db.query(IDXTransferApprovalBlockNumber).first() + _idx_transfer_approval_block_number = db.query( + IDXTransferApprovalBlockNumber + ).first() assert _idx_transfer_approval_block_number.id == 1 assert _idx_transfer_approval_block_number.latest_block_number == block_number @@ -848,28 +897,30 @@ def test_normal_2_4(self, processor, db, personal_info_contract, ibet_security_t # Event log # - Exchange: CancelTransfer # Cancel from applicant - def test_normal_2_5(self, processor, db, personal_info_contract, ibet_security_token_escrow_contract): + def test_normal_2_5( + self, processor, db, personal_info_contract, ibet_security_token_escrow_contract + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address, - tradable_exchange_contract_address=ibet_security_token_escrow_contract.address, - transfer_approval_required=True) + token_contract_1 = deploy_bond_token_contract( + issuer_address, + issuer_private_key, + personal_info_contract.address, + tradable_exchange_contract_address=ibet_security_token_escrow_contract.address, + transfer_approval_required=True, + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -898,52 +949,54 @@ def test_normal_2_5(self, processor, db, personal_info_contract, ibet_security_t # Deposit tx = token_contract_1.functions.transferFrom( - issuer_address, - user_address_1, - 40 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + issuer_address, user_address_1, 40 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) tx = token_contract_1.functions.transfer( - ibet_security_token_escrow_contract.address, - 40 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": user_address_1, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ibet_security_token_escrow_contract.address, 40 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": user_address_1, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, user_private_key_1) # ApplyForTransfer tx = ibet_security_token_escrow_contract.functions.createEscrow( - token_address_1, - user_address_2, - 30, - user_address_1, - "", - "" - ).build_transaction({ - "chainId": CHAIN_ID, - "from": user_address_1, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + token_address_1, user_address_2, 30, user_address_1, "", "" + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": user_address_1, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) _, tx_receipt_1 = ContractUtils.send_transaction(tx, user_private_key_1) block = web3.eth.get_block(tx_receipt_1["blockNumber"]) # CancelTransfer from applicant - tx = ibet_security_token_escrow_contract.functions.cancelEscrow(1).build_transaction({ - "chainId": CHAIN_ID, - "from": user_address_1, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = ibet_security_token_escrow_contract.functions.cancelEscrow( + 1 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": user_address_1, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, user_private_key_1) # Run target process @@ -956,13 +1009,19 @@ def test_normal_2_5(self, processor, db, personal_info_contract, ibet_security_t _transfer_approval = _transfer_approval_list[0] assert _transfer_approval.id == 1 assert _transfer_approval.token_address == token_address_1 - assert _transfer_approval.exchange_address == ibet_security_token_escrow_contract.address + assert ( + _transfer_approval.exchange_address + == ibet_security_token_escrow_contract.address + ) assert _transfer_approval.application_id == 1 assert _transfer_approval.from_address == user_address_1 assert _transfer_approval.to_address == user_address_2 assert _transfer_approval.amount == 30 assert _transfer_approval.application_datetime is None - assert _transfer_approval.application_blocktimestamp == datetime.utcfromtimestamp(block["timestamp"]) + assert ( + _transfer_approval.application_blocktimestamp + == datetime.utcfromtimestamp(block["timestamp"]) + ) assert _transfer_approval.approval_datetime is None assert _transfer_approval.approval_blocktimestamp is None assert _transfer_approval.cancelled is True @@ -980,10 +1039,12 @@ def test_normal_2_5(self, processor, db, personal_info_contract, ibet_security_t assert _notification.metainfo == { "token_type": token_1.type, "token_address": token_address_1, - "id": 1 + "id": 1, } - _idx_transfer_approval_block_number = db.query(IDXTransferApprovalBlockNumber).first() + _idx_transfer_approval_block_number = db.query( + IDXTransferApprovalBlockNumber + ).first() assert _idx_transfer_approval_block_number.id == 1 assert _idx_transfer_approval_block_number.latest_block_number == block_number @@ -991,29 +1052,31 @@ def test_normal_2_5(self, processor, db, personal_info_contract, ibet_security_t # Single Token # Single event logs # - Exchange: EscrowFinished - @pytest.mark.freeze_time('2021-04-27 12:34:56') - def test_normal_2_6(self, processor, db, personal_info_contract, ibet_security_token_escrow_contract): + @pytest.mark.freeze_time("2021-04-27 12:34:56") + def test_normal_2_6( + self, processor, db, personal_info_contract, ibet_security_token_escrow_contract + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address, - tradable_exchange_contract_address=ibet_security_token_escrow_contract.address, - transfer_approval_required=True) + token_contract_1 = deploy_bond_token_contract( + issuer_address, + issuer_private_key, + personal_info_contract.address, + tradable_exchange_contract_address=ibet_security_token_escrow_contract.address, + transfer_approval_required=True, + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -1032,52 +1095,54 @@ def test_normal_2_6(self, processor, db, personal_info_contract, ibet_security_t # Deposit tx = token_contract_1.functions.transferFrom( - issuer_address, - user_address_1, - 40 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + issuer_address, user_address_1, 40 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) tx = token_contract_1.functions.transfer( - ibet_security_token_escrow_contract.address, - 40 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": user_address_1, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ibet_security_token_escrow_contract.address, 40 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": user_address_1, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, user_private_key_1) # ApplyForTransfer tx = ibet_security_token_escrow_contract.functions.createEscrow( - token_address_1, - user_address_2, - 30, - user_address_1, - "", - "" - ).build_transaction({ - "chainId": CHAIN_ID, - "from": user_address_1, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + token_address_1, user_address_2, 30, user_address_1, "", "" + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": user_address_1, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) _, tx_receipt_1 = ContractUtils.send_transaction(tx, user_private_key_1) block_1 = web3.eth.get_block(tx_receipt_1["blockNumber"]) # FinishTransfer - tx = ibet_security_token_escrow_contract.functions.finishEscrow(1).build_transaction({ - "chainId": CHAIN_ID, - "from": user_address_1, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = ibet_security_token_escrow_contract.functions.finishEscrow( + 1 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": user_address_1, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) _, tx_receipt_2 = ContractUtils.send_transaction(tx, user_private_key_1) # Run target process @@ -1090,13 +1155,19 @@ def test_normal_2_6(self, processor, db, personal_info_contract, ibet_security_t _transfer_approval = _transfer_approval_list[0] assert _transfer_approval.id == 1 assert _transfer_approval.token_address == token_address_1 - assert _transfer_approval.exchange_address == ibet_security_token_escrow_contract.address + assert ( + _transfer_approval.exchange_address + == ibet_security_token_escrow_contract.address + ) assert _transfer_approval.application_id == 1 assert _transfer_approval.from_address == user_address_1 assert _transfer_approval.to_address == user_address_2 assert _transfer_approval.amount == 30 assert _transfer_approval.application_datetime is None - assert _transfer_approval.application_blocktimestamp == datetime.utcfromtimestamp(block_1["timestamp"]) + assert ( + _transfer_approval.application_blocktimestamp + == datetime.utcfromtimestamp(block_1["timestamp"]) + ) assert _transfer_approval.approval_datetime is None assert _transfer_approval.approval_blocktimestamp is None assert _transfer_approval.cancelled is None @@ -1114,39 +1185,43 @@ def test_normal_2_6(self, processor, db, personal_info_contract, ibet_security_t assert _notification.metainfo == { "token_type": token_1.type, "token_address": token_address_1, - "id": 1 + "id": 1, } - _idx_transfer_approval_block_number = db.query(IDXTransferApprovalBlockNumber).first() + _idx_transfer_approval_block_number = db.query( + IDXTransferApprovalBlockNumber + ).first() assert _idx_transfer_approval_block_number.id == 1 assert _idx_transfer_approval_block_number.latest_block_number == block_number # # Event logs # - Exchange: ApproveTransfer - @pytest.mark.freeze_time('2021-04-27 12:34:56') - def test_normal_2_7(self, processor, db, personal_info_contract, ibet_security_token_escrow_contract): + @pytest.mark.freeze_time("2021-04-27 12:34:56") + def test_normal_2_7( + self, processor, db, personal_info_contract, ibet_security_token_escrow_contract + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] # Prepare data : Token - token_contract_1 = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address, - tradable_exchange_contract_address=ibet_security_token_escrow_contract.address, - transfer_approval_required=True) + token_contract_1 = deploy_bond_token_contract( + issuer_address, + issuer_private_key, + personal_info_contract.address, + tradable_exchange_contract_address=ibet_security_token_escrow_contract.address, + transfer_approval_required=True, + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -1165,64 +1240,67 @@ def test_normal_2_7(self, processor, db, personal_info_contract, ibet_security_t # Deposit tx = token_contract_1.functions.transferFrom( - issuer_address, - user_address_1, - 40 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + issuer_address, user_address_1, 40 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) tx = token_contract_1.functions.transfer( - ibet_security_token_escrow_contract.address, - 40 - ).build_transaction({ - "chainId": CHAIN_ID, - "from": user_address_1, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + ibet_security_token_escrow_contract.address, 40 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": user_address_1, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, user_private_key_1) # ApplyForTransfer tx = ibet_security_token_escrow_contract.functions.createEscrow( - token_address_1, - user_address_2, - 30, - user_address_1, - "", - "" - ).build_transaction({ - "chainId": CHAIN_ID, - "from": user_address_1, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + token_address_1, user_address_2, 30, user_address_1, "", "" + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": user_address_1, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) _, tx_receipt_1 = ContractUtils.send_transaction(tx, user_private_key_1) block = web3.eth.get_block(tx_receipt_1["blockNumber"]) # FinishTransfer - tx = ibet_security_token_escrow_contract.functions.finishEscrow(1).build_transaction({ - "chainId": CHAIN_ID, - "from": user_address_1, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = ibet_security_token_escrow_contract.functions.finishEscrow( + 1 + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": user_address_1, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, user_private_key_1) # ApproveTransfer tx = ibet_security_token_escrow_contract.functions.approveTransfer( - 1, - "" - ).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + 1, "" + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) _, tx_receipt_2 = ContractUtils.send_transaction(tx, issuer_private_key) block_2 = web3.eth.get_block(tx_receipt_2["blockNumber"]) @@ -1236,15 +1314,23 @@ def test_normal_2_7(self, processor, db, personal_info_contract, ibet_security_t _transfer_approval = _transfer_approval_list[0] assert _transfer_approval.id == 1 assert _transfer_approval.token_address == token_address_1 - assert _transfer_approval.exchange_address == ibet_security_token_escrow_contract.address + assert ( + _transfer_approval.exchange_address + == ibet_security_token_escrow_contract.address + ) assert _transfer_approval.application_id == 1 assert _transfer_approval.from_address == user_address_1 assert _transfer_approval.to_address == user_address_2 assert _transfer_approval.amount == 30 assert _transfer_approval.application_datetime is None - assert _transfer_approval.application_blocktimestamp == datetime.utcfromtimestamp(block["timestamp"]) + assert ( + _transfer_approval.application_blocktimestamp + == datetime.utcfromtimestamp(block["timestamp"]) + ) assert _transfer_approval.approval_datetime is None - assert _transfer_approval.approval_blocktimestamp == datetime.utcfromtimestamp(block_2["timestamp"]) + assert _transfer_approval.approval_blocktimestamp == datetime.utcfromtimestamp( + block_2["timestamp"] + ) assert _transfer_approval.cancelled is None assert _transfer_approval.transfer_approved is True @@ -1260,10 +1346,12 @@ def test_normal_2_7(self, processor, db, personal_info_contract, ibet_security_t assert _notification.metainfo == { "token_type": token_1.type, "token_address": token_address_1, - "id": 1 + "id": 1, } - _idx_transfer_approval_block_number = db.query(IDXTransferApprovalBlockNumber).first() + _idx_transfer_approval_block_number = db.query( + IDXTransferApprovalBlockNumber + ).first() assert _idx_transfer_approval_block_number.id == 1 assert _idx_transfer_approval_block_number.latest_block_number == block_number @@ -1271,7 +1359,9 @@ def test_normal_2_7(self, processor, db, personal_info_contract, ibet_security_t # If block number processed in batch is equal or greater than current block number, # batch will output a log "skip process". @mock.patch("web3.eth.Eth.block_number", 100) - def test_normal_3(self, processor: Processor, db: Session, caplog: pytest.LogCaptureFixture): + def test_normal_3( + self, processor: Processor, db: Session, caplog: pytest.LogCaptureFixture + ): _idx_transfer_approval_block_number = IDXTransferApprovalBlockNumber() _idx_transfer_approval_block_number.id = 1 _idx_transfer_approval_block_number.latest_block_number = 1000 @@ -1279,27 +1369,44 @@ def test_normal_3(self, processor: Processor, db: Session, caplog: pytest.LogCap db.commit() processor.sync_new_logs() - assert caplog.record_tuples.count((LOG.name, logging.DEBUG, "skip process")) == 1 + assert ( + caplog.record_tuples.count((LOG.name, logging.DEBUG, "skip process")) == 1 + ) # # If DB session fails in sinking phase each event, batch outputs a log "exception occurred". - def test_normal_4(self, processor, db, personal_info_contract, ibet_security_token_escrow_contract, caplog: pytest.LogCaptureFixture): + def test_normal_4( + self, + processor, + db, + personal_info_contract, + ibet_security_token_escrow_contract, + caplog: pytest.LogCaptureFixture, + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # Prepare data : Token - token_contract = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address, - tradable_exchange_contract_address=ibet_security_token_escrow_contract.address, - transfer_approval_required=True) + token_contract = deploy_bond_token_contract( + issuer_address, + issuer_private_key, + personal_info_contract.address, + tradable_exchange_contract_address=ibet_security_token_escrow_contract.address, + transfer_approval_required=True, + ) token_address = token_contract.address token = Token() token.type = TokenType.IBET_STRAIGHT_BOND.value @@ -1310,23 +1417,84 @@ def test_normal_4(self, processor, db, personal_info_contract, ibet_security_tok db.add(token) db.commit() - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [ibet_security_token_escrow_contract.address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [ibet_security_token_escrow_contract.address, ""], + ) - STContractUtils.set_transfer_approve_required(token_contract.address, issuer_address, issuer_private_key, [True]) - STContractUtils.apply_for_transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 10, "to user1#1"]) - STContractUtils.apply_for_transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_1, 20, "to user1#2"]) - STContractUtils.apply_for_transfer(token_contract.address, issuer_address, issuer_private_key, [user_address_2, 10, "to user2#1"]) + STContractUtils.set_transfer_approve_required( + token_contract.address, issuer_address, issuer_private_key, [True] + ) + STContractUtils.apply_for_transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 10, "to user1#1"], + ) + STContractUtils.apply_for_transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_1, 20, "to user1#2"], + ) + STContractUtils.apply_for_transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [user_address_2, 10, "to user2#1"], + ) - STContractUtils.cancel_transfer(token_contract.address, issuer_address, issuer_private_key, [0, "to user1#1"]) - STContractUtils.approve_transfer(token_contract.address, issuer_address, issuer_private_key, [1, "to user1#2"]) - STContractUtils.approve_transfer(token_contract.address, issuer_address, issuer_private_key, [2, "to user2#1"]) + STContractUtils.cancel_transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [0, "to user1#1"], + ) + STContractUtils.approve_transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [1, "to user1#2"], + ) + STContractUtils.approve_transfer( + token_contract.address, + issuer_address, + issuer_private_key, + [2, "to user2#1"], + ) - STContractUtils.set_transfer_approve_required(token_contract.address, issuer_address, issuer_private_key, [False]) - STContractUtils.transfer(token_contract.address, user_address_1, user_pk_1, [ibet_security_token_escrow_contract.address, 20]) - STContractUtils.set_transfer_approve_required(token_contract.address, issuer_address, issuer_private_key, [True]) + STContractUtils.set_transfer_approve_required( + token_contract.address, issuer_address, issuer_private_key, [False] + ) + STContractUtils.transfer( + token_contract.address, + user_address_1, + user_pk_1, + [ibet_security_token_escrow_contract.address, 20], + ) + STContractUtils.set_transfer_approve_required( + token_contract.address, issuer_address, issuer_private_key, [True] + ) STEscrowContractUtils.create_escrow( ibet_security_token_escrow_contract.address, @@ -1334,29 +1502,56 @@ def test_normal_4(self, processor, db, personal_info_contract, ibet_security_tok user_pk_1, [token_contract.address, user_address_2, 10, issuer_address, "", ""], ) - latest_security_escrow_id = STEscrowContractUtils.get_latest_escrow_id(ibet_security_token_escrow_contract.address) + latest_security_escrow_id = STEscrowContractUtils.get_latest_escrow_id( + ibet_security_token_escrow_contract.address + ) STEscrowContractUtils.finish_escrow( - ibet_security_token_escrow_contract.address, issuer_address, issuer_private_key, [latest_security_escrow_id] + ibet_security_token_escrow_contract.address, + issuer_address, + issuer_private_key, + [latest_security_escrow_id], ) STEscrowContractUtils.approve_transfer( - ibet_security_token_escrow_contract.address, issuer_address, issuer_private_key, [latest_security_escrow_id, ""] + ibet_security_token_escrow_contract.address, + issuer_address, + issuer_private_key, + [latest_security_escrow_id, ""], ) - with caplog.at_level(logging.ERROR, LOG.name), patch.object(Session, "add", side_effect=Exception()): + with caplog.at_level(logging.ERROR, LOG.name), patch.object( + Session, "add", side_effect=Exception() + ): # Then execute processor. processor.sync_new_logs() # Error occurs in events with exception of Escrow. - assert caplog.record_tuples.count((LOG.name, logging.ERROR, "An exception occurred during event synchronization")) == 3 + assert ( + caplog.record_tuples.count( + ( + LOG.name, + logging.ERROR, + "An exception occurred during event synchronization", + ) + ) + == 3 + ) # # Newly tokens added - def test_normal_5(self, processor: Processor, db: Session, personal_info_contract, ibet_security_token_escrow_contract): + def test_normal_5( + self, + processor: Processor, + db: Session, + personal_info_contract, + ibet_security_token_escrow_contract, + ): escrow_contract = ibet_security_token_escrow_contract user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) # Issuer issues bond token. token_contract1 = deploy_bond_token_contract( @@ -1417,17 +1612,22 @@ def test_normal_5(self, processor: Processor, db: Session, personal_info_contrac # # If each error occurs, batch will output logs and continue next sync. - def test_error_1(self, main_func, db:Session, personal_info_contract, caplog: pytest.LogCaptureFixture): + def test_error_1( + self, + main_func, + db: Session, + personal_info_contract, + caplog: pytest.LogCaptureFixture, + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract = deploy_bond_token_contract(issuer_address, - issuer_private_key, - personal_info_contract.address) + token_contract = deploy_bond_token_contract( + issuer_address, issuer_private_key, personal_info_contract.address + ) token_address = token_contract.address token = Token() token.type = TokenType.IBET_STRAIGHT_BOND.value @@ -1440,17 +1640,27 @@ def test_error_1(self, main_func, db:Session, personal_info_contract, caplog: py db.commit() # Run mainloop once and fail with web3 utils error - with patch("batch.indexer_transfer_approval.INDEXER_SYNC_INTERVAL", None),\ - patch.object(web3.eth, "contract", side_effect=ServiceUnavailableError()), \ - pytest.raises(TypeError): + with patch( + "batch.indexer_transfer_approval.INDEXER_SYNC_INTERVAL", None + ), patch.object( + web3.eth, "contract", side_effect=ServiceUnavailableError() + ), pytest.raises( + TypeError + ): main_func() - assert 1 == caplog.record_tuples.count((LOG.name, logging.WARNING, "An external service was unavailable")) + assert 1 == caplog.record_tuples.count( + (LOG.name, logging.WARNING, "An external service was unavailable") + ) caplog.clear() # Run mainloop once and fail with sqlalchemy Error - with patch("batch.indexer_transfer_approval.INDEXER_SYNC_INTERVAL", None),\ - patch.object(Session, "commit", side_effect=SQLAlchemyError(code="dbapi")), \ - pytest.raises(TypeError): + with patch( + "batch.indexer_transfer_approval.INDEXER_SYNC_INTERVAL", None + ), patch.object( + Session, "commit", side_effect=SQLAlchemyError(code="dbapi") + ), pytest.raises( + TypeError + ): main_func() - assert 'A database error has occurred: code=dbapi' in caplog.text + assert "A database error has occurred: code=dbapi" in caplog.text caplog.clear() diff --git a/tests/test_batch_processor_batch_issue_redeem.py b/tests/test_batch_processor_batch_issue_redeem.py index 0e22159a..847164bc 100644 --- a/tests/test_batch_processor_batch_issue_redeem.py +++ b/tests/test_batch_processor_batch_issue_redeem.py @@ -18,36 +18,35 @@ """ import logging import uuid -from sqlalchemy.orm import Session from typing import List -from unittest.mock import patch, ANY +from unittest.mock import ANY, patch import pytest - from eth_keyfile import decode_keyfile_json +from sqlalchemy.orm import Session -from app.exceptions import SendTransactionError, ContractRevertError +from app.exceptions import ContractRevertError, SendTransactionError from app.model.db import ( Account, - BatchIssueRedeemUpload, - BatchIssueRedeemProcessingCategory, BatchIssueRedeem, - TokenType, + BatchIssueRedeemProcessingCategory, + BatchIssueRedeemUpload, Notification, - NotificationType + NotificationType, + TokenType, ) from app.model.schema import ( + IbetShareAdditionalIssue, + IbetShareRedeem, IbetStraightBondAdditionalIssue, IbetStraightBondRedeem, - IbetShareAdditionalIssue, - IbetShareRedeem ) from app.utils.e2ee_utils import E2EEUtils -from batch.processor_batch_issue_redeem import Processor, LOG +from batch.processor_batch_issue_redeem import LOG, Processor from tests.account_config import config_eth_account -@pytest.fixture(scope='function') +@pytest.fixture(scope="function") def processor(db, caplog: pytest.LogCaptureFixture): log = logging.getLogger("background") default_log_level = LOG.level @@ -59,7 +58,6 @@ def processor(db, caplog: pytest.LogCaptureFixture): class TestProcessor: - ########################################################################### # Normal Case ########################################################################### @@ -75,7 +73,7 @@ def test_normal_1(self, processor, db, caplog): issuer_eoa_password = E2EEUtils.encrypt("password") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer_keyfile, - password=E2EEUtils.decrypt(issuer_eoa_password).encode("utf-8") + password=E2EEUtils.decrypt(issuer_eoa_password).encode("utf-8"), ) token_address = "test_token_address" @@ -114,38 +112,43 @@ def test_normal_1(self, processor, db, caplog): # Execute batch with patch( - target="app.model.blockchain.token.IbetStraightBondContract.additional_issue", - return_value="mock_tx_hash") as IbetStraightBondContract_additional_issue: + target="app.model.blockchain.token.IbetStraightBondContract.additional_issue", + return_value="mock_tx_hash", + ) as IbetStraightBondContract_additional_issue: processor.process() # Assertion: contract IbetStraightBondContract_additional_issue.assert_called_with( data=IbetStraightBondAdditionalIssue( - account_address=target_address, - amount=target_amount + account_address=target_address, amount=target_amount ), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) # Assertion: DB - _upload_after: BatchIssueRedeemUpload = db.query(BatchIssueRedeemUpload). \ - filter(BatchIssueRedeemUpload.upload_id == upload_id). \ - first() + _upload_after: BatchIssueRedeemUpload = ( + db.query(BatchIssueRedeemUpload) + .filter(BatchIssueRedeemUpload.upload_id == upload_id) + .first() + ) assert _upload_after.processed == True - _upload_data_after: List[BatchIssueRedeem] = db.query(BatchIssueRedeem). \ - filter(BatchIssueRedeem.upload_id == upload_id). \ - all() + _upload_data_after: List[BatchIssueRedeem] = ( + db.query(BatchIssueRedeem) + .filter(BatchIssueRedeem.upload_id == upload_id) + .all() + ) assert len(_upload_data_after) == 1 assert _upload_data_after[0].status == 1 # Assertion: Log - assert caplog.record_tuples.count(( - LOG.name, - logging.DEBUG, - "Transaction sent successfully: mock_tx_hash" - )) == 1 + assert ( + caplog.record_tuples.count( + (LOG.name, logging.DEBUG, "Transaction sent successfully: mock_tx_hash") + ) + == 1 + ) _notification_list = db.query(Notification).all() for _notification in _notification_list: @@ -159,7 +162,7 @@ def test_normal_1(self, processor, db, caplog): "upload_id": upload_id, "error_data_id": [], "token_address": token_address, - "token_type": TokenType.IBET_STRAIGHT_BOND + "token_type": TokenType.IBET_STRAIGHT_BOND, } # Normal_2 @@ -173,7 +176,7 @@ def test_normal_2(self, processor, db, caplog): issuer_eoa_password = E2EEUtils.encrypt("password") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer_keyfile, - password=E2EEUtils.decrypt(issuer_eoa_password).encode("utf-8") + password=E2EEUtils.decrypt(issuer_eoa_password).encode("utf-8"), ) token_address = "test_token_address" @@ -212,38 +215,43 @@ def test_normal_2(self, processor, db, caplog): # Execute batch with patch( - target="app.model.blockchain.token.IbetStraightBondContract.redeem", - return_value="mock_tx_hash") as IbetStraightBondContract_redeem: + target="app.model.blockchain.token.IbetStraightBondContract.redeem", + return_value="mock_tx_hash", + ) as IbetStraightBondContract_redeem: processor.process() # Assertion: contract IbetStraightBondContract_redeem.assert_called_with( data=IbetStraightBondRedeem( - account_address=target_address, - amount=target_amount + account_address=target_address, amount=target_amount ), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) # Assertion: DB - _upload_after: BatchIssueRedeemUpload = db.query(BatchIssueRedeemUpload). \ - filter(BatchIssueRedeemUpload.upload_id == upload_id). \ - first() + _upload_after: BatchIssueRedeemUpload = ( + db.query(BatchIssueRedeemUpload) + .filter(BatchIssueRedeemUpload.upload_id == upload_id) + .first() + ) assert _upload_after.processed == True - _upload_data_after: List[BatchIssueRedeem] = db.query(BatchIssueRedeem). \ - filter(BatchIssueRedeem.upload_id == upload_id). \ - all() + _upload_data_after: List[BatchIssueRedeem] = ( + db.query(BatchIssueRedeem) + .filter(BatchIssueRedeem.upload_id == upload_id) + .all() + ) assert len(_upload_data_after) == 1 assert _upload_data_after[0].status == 1 # Assertion: Log - assert caplog.record_tuples.count(( - LOG.name, - logging.DEBUG, - "Transaction sent successfully: mock_tx_hash" - )) == 1 + assert ( + caplog.record_tuples.count( + (LOG.name, logging.DEBUG, "Transaction sent successfully: mock_tx_hash") + ) + == 1 + ) _notification_list = db.query(Notification).all() for _notification in _notification_list: @@ -257,7 +265,7 @@ def test_normal_2(self, processor, db, caplog): "upload_id": upload_id, "error_data_id": [], "token_address": token_address, - "token_type": TokenType.IBET_STRAIGHT_BOND + "token_type": TokenType.IBET_STRAIGHT_BOND, } # Normal_3 @@ -271,7 +279,7 @@ def test_normal_3(self, processor, db, caplog): issuer_eoa_password = E2EEUtils.encrypt("password") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer_keyfile, - password=E2EEUtils.decrypt(issuer_eoa_password).encode("utf-8") + password=E2EEUtils.decrypt(issuer_eoa_password).encode("utf-8"), ) token_address = "test_token_address" @@ -310,38 +318,43 @@ def test_normal_3(self, processor, db, caplog): # Execute batch with patch( - target="app.model.blockchain.token.IbetShareContract.additional_issue", - return_value="mock_tx_hash") as IbetShareContract_additional_issue: + target="app.model.blockchain.token.IbetShareContract.additional_issue", + return_value="mock_tx_hash", + ) as IbetShareContract_additional_issue: processor.process() # Assertion: contract IbetShareContract_additional_issue.assert_called_with( data=IbetShareAdditionalIssue( - account_address=target_address, - amount=target_amount + account_address=target_address, amount=target_amount ), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) # Assertion: DB - _upload_after: BatchIssueRedeemUpload = db.query(BatchIssueRedeemUpload). \ - filter(BatchIssueRedeemUpload.upload_id == upload_id). \ - first() + _upload_after: BatchIssueRedeemUpload = ( + db.query(BatchIssueRedeemUpload) + .filter(BatchIssueRedeemUpload.upload_id == upload_id) + .first() + ) assert _upload_after.processed == True - _upload_data_after: List[BatchIssueRedeem] = db.query(BatchIssueRedeem). \ - filter(BatchIssueRedeem.upload_id == upload_id). \ - all() + _upload_data_after: List[BatchIssueRedeem] = ( + db.query(BatchIssueRedeem) + .filter(BatchIssueRedeem.upload_id == upload_id) + .all() + ) assert len(_upload_data_after) == 1 assert _upload_data_after[0].status == 1 # Assertion: Log - assert caplog.record_tuples.count(( - LOG.name, - logging.DEBUG, - "Transaction sent successfully: mock_tx_hash" - )) == 1 + assert ( + caplog.record_tuples.count( + (LOG.name, logging.DEBUG, "Transaction sent successfully: mock_tx_hash") + ) + == 1 + ) _notification_list = db.query(Notification).all() for _notification in _notification_list: @@ -355,7 +368,7 @@ def test_normal_3(self, processor, db, caplog): "upload_id": upload_id, "error_data_id": [], "token_address": token_address, - "token_type": TokenType.IBET_SHARE + "token_type": TokenType.IBET_SHARE, } # Normal_4 @@ -369,7 +382,7 @@ def test_normal_4(self, processor, db, caplog): issuer_eoa_password = E2EEUtils.encrypt("password") issuer_pk = decode_keyfile_json( raw_keyfile_json=issuer_keyfile, - password=E2EEUtils.decrypt(issuer_eoa_password).encode("utf-8") + password=E2EEUtils.decrypt(issuer_eoa_password).encode("utf-8"), ) token_address = "test_token_address" @@ -408,38 +421,41 @@ def test_normal_4(self, processor, db, caplog): # Execute batch with patch( - target="app.model.blockchain.token.IbetShareContract.redeem", - return_value="mock_tx_hash") as IbetShareContract_redeem: + target="app.model.blockchain.token.IbetShareContract.redeem", + return_value="mock_tx_hash", + ) as IbetShareContract_redeem: processor.process() # Assertion: contract IbetShareContract_redeem.assert_called_with( - data=IbetShareRedeem( - account_address=target_address, - amount=target_amount - ), + data=IbetShareRedeem(account_address=target_address, amount=target_amount), tx_from=issuer_address, - private_key=issuer_pk + private_key=issuer_pk, ) # Assertion: DB - _upload_after: BatchIssueRedeemUpload = db.query(BatchIssueRedeemUpload). \ - filter(BatchIssueRedeemUpload.upload_id == upload_id). \ - first() + _upload_after: BatchIssueRedeemUpload = ( + db.query(BatchIssueRedeemUpload) + .filter(BatchIssueRedeemUpload.upload_id == upload_id) + .first() + ) assert _upload_after.processed == True - _upload_data_after: List[BatchIssueRedeem] = db.query(BatchIssueRedeem). \ - filter(BatchIssueRedeem.upload_id == upload_id). \ - all() + _upload_data_after: List[BatchIssueRedeem] = ( + db.query(BatchIssueRedeem) + .filter(BatchIssueRedeem.upload_id == upload_id) + .all() + ) assert len(_upload_data_after) == 1 assert _upload_data_after[0].status == 1 # Assertion: Log - assert caplog.record_tuples.count(( - LOG.name, - logging.DEBUG, - "Transaction sent successfully: mock_tx_hash" - )) == 1 + assert ( + caplog.record_tuples.count( + (LOG.name, logging.DEBUG, "Transaction sent successfully: mock_tx_hash") + ) + == 1 + ) _notification_list = db.query(Notification).all() for _notification in _notification_list: @@ -453,7 +469,7 @@ def test_normal_4(self, processor, db, caplog): "upload_id": upload_id, "error_data_id": [], "token_address": token_address, - "token_type": TokenType.IBET_SHARE + "token_type": TokenType.IBET_SHARE, } ########################################################################### @@ -496,31 +512,37 @@ def test_error_1(self, processor, db, caplog): # Execute batch with patch( - target="app.model.blockchain.token.IbetStraightBondContract.additional_issue", - return_value="mock_tx_hash") as IbetStraightBondContract_additional_issue: + target="app.model.blockchain.token.IbetStraightBondContract.additional_issue", + return_value="mock_tx_hash", + ) as IbetStraightBondContract_additional_issue: processor.process() # Assertion: contract IbetStraightBondContract_additional_issue.assert_not_called() # Assertion: DB - _upload_after: BatchIssueRedeemUpload = db.query(BatchIssueRedeemUpload). \ - filter(BatchIssueRedeemUpload.upload_id == upload_id). \ - first() + _upload_after: BatchIssueRedeemUpload = ( + db.query(BatchIssueRedeemUpload) + .filter(BatchIssueRedeemUpload.upload_id == upload_id) + .first() + ) assert _upload_after.processed == True - _upload_data_after: List[BatchIssueRedeem] = db.query(BatchIssueRedeem). \ - filter(BatchIssueRedeem.upload_id == upload_id). \ - all() + _upload_data_after: List[BatchIssueRedeem] = ( + db.query(BatchIssueRedeem) + .filter(BatchIssueRedeem.upload_id == upload_id) + .all() + ) assert len(_upload_data_after) == 1 assert _upload_data_after[0].status == 0 # Assertion: Log - assert caplog.record_tuples.count(( - LOG.name, - logging.ERROR, - "Issuer account does not exist" - )) == 1 + assert ( + caplog.record_tuples.count( + (LOG.name, logging.ERROR, "Issuer account does not exist") + ) + == 1 + ) _notification_list = db.query(Notification).all() for _notification in _notification_list: @@ -534,7 +556,7 @@ def test_error_1(self, processor, db, caplog): "upload_id": upload_id, "error_data_id": [], "token_address": token_address, - "token_type": TokenType.IBET_STRAIGHT_BOND + "token_type": TokenType.IBET_STRAIGHT_BOND, } # Error_2 @@ -582,31 +604,37 @@ def test_error_2(self, processor, db, caplog): # Execute batch with patch( - target="app.model.blockchain.token.IbetStraightBondContract.additional_issue", - return_value="mock_tx_hash") as IbetStraightBondContract_additional_issue: + target="app.model.blockchain.token.IbetStraightBondContract.additional_issue", + return_value="mock_tx_hash", + ) as IbetStraightBondContract_additional_issue: processor.process() # Assertion: contract IbetStraightBondContract_additional_issue.assert_not_called() # Assertion: DB - _upload_after: BatchIssueRedeemUpload = db.query(BatchIssueRedeemUpload). \ - filter(BatchIssueRedeemUpload.upload_id == upload_id). \ - first() + _upload_after: BatchIssueRedeemUpload = ( + db.query(BatchIssueRedeemUpload) + .filter(BatchIssueRedeemUpload.upload_id == upload_id) + .first() + ) assert _upload_after.processed == True - _upload_data_after: List[BatchIssueRedeem] = db.query(BatchIssueRedeem). \ - filter(BatchIssueRedeem.upload_id == upload_id). \ - all() + _upload_data_after: List[BatchIssueRedeem] = ( + db.query(BatchIssueRedeem) + .filter(BatchIssueRedeem.upload_id == upload_id) + .all() + ) assert len(_upload_data_after) == 1 assert _upload_data_after[0].status == 0 # Assertion: Log - assert caplog.record_tuples.count(( - LOG.name, - logging.ERROR, - "Failed to decode keyfile" - )) == 1 + assert ( + caplog.record_tuples.count( + (LOG.name, logging.ERROR, "Failed to decode keyfile") + ) + == 1 + ) _notification_list = db.query(Notification).all() for _notification in _notification_list: @@ -620,7 +648,7 @@ def test_error_2(self, processor, db, caplog): "upload_id": upload_id, "error_data_id": [], "token_address": token_address, - "token_type": TokenType.IBET_STRAIGHT_BOND + "token_type": TokenType.IBET_STRAIGHT_BOND, } # Error_3 @@ -675,29 +703,35 @@ def test_error_3(self, processor, db, caplog): # Execute batch with patch( - target="app.model.blockchain.token.IbetStraightBondContract.additional_issue", - side_effect=SendTransactionError()) as IbetStraightBondContract_additional_issue: + target="app.model.blockchain.token.IbetStraightBondContract.additional_issue", + side_effect=SendTransactionError(), + ) as IbetStraightBondContract_additional_issue: processor.process() # Assertion: DB - _upload_after: BatchIssueRedeemUpload = db.query(BatchIssueRedeemUpload). \ - filter(BatchIssueRedeemUpload.upload_id == upload_id). \ - first() + _upload_after: BatchIssueRedeemUpload = ( + db.query(BatchIssueRedeemUpload) + .filter(BatchIssueRedeemUpload.upload_id == upload_id) + .first() + ) assert _upload_after.processed == True - _upload_data_after: List[BatchIssueRedeem] = db.query(BatchIssueRedeem). \ - filter(BatchIssueRedeem.upload_id == upload_id). \ - all() + _upload_data_after: List[BatchIssueRedeem] = ( + db.query(BatchIssueRedeem) + .filter(BatchIssueRedeem.upload_id == upload_id) + .all() + ) assert len(_upload_data_after) == 2 assert _upload_data_after[0].status == 2 assert _upload_data_after[1].status == 2 # Assertion: Log - assert caplog.record_tuples.count(( - LOG.name, - logging.WARNING, - "Failed to send transaction: -" - )) == 2 + assert ( + caplog.record_tuples.count( + (LOG.name, logging.WARNING, "Failed to send transaction: -") + ) + == 2 + ) _notification_list = db.query(Notification).all() for _notification in _notification_list: @@ -711,13 +745,15 @@ def test_error_3(self, processor, db, caplog): "upload_id": upload_id, "error_data_id": ANY, "token_address": token_address, - "token_type": TokenType.IBET_STRAIGHT_BOND + "token_type": TokenType.IBET_STRAIGHT_BOND, } assert len(_notification.metainfo["error_data_id"]) == 2 # # ContractRevertError - def test_error_4(self, processor: Processor, db: Session, caplog: pytest.LogCaptureFixture): + def test_error_4( + self, processor: Processor, db: Session, caplog: pytest.LogCaptureFixture + ): # Test settings issuer_account = config_eth_account("user1") issuer_address = issuer_account["address"] @@ -777,78 +813,97 @@ def test_error_4(self, processor: Processor, db: Session, caplog: pytest.LogCapt db.commit() # mock - with ( - patch( - target="app.model.blockchain.token.IbetStraightBondContract.additional_issue", - side_effect=ContractRevertError("999999") - ), - patch( - target="app.model.blockchain.token.IbetShareContract.additional_issue", - side_effect=ContractRevertError("999999") - ) + with patch( + target="app.model.blockchain.token.IbetStraightBondContract.additional_issue", + side_effect=ContractRevertError("999999"), + ), patch( + target="app.model.blockchain.token.IbetShareContract.additional_issue", + side_effect=ContractRevertError("999999"), ): processor.process() # Assertion: DB - _upload_1_after: BatchIssueRedeemUpload = db.query(BatchIssueRedeemUpload). \ - filter(BatchIssueRedeemUpload.upload_id == upload_1_id). \ - first() + _upload_1_after: BatchIssueRedeemUpload = ( + db.query(BatchIssueRedeemUpload) + .filter(BatchIssueRedeemUpload.upload_id == upload_1_id) + .first() + ) assert _upload_1_after.processed == True - _upload_1_data_after: List[BatchIssueRedeem] = db.query(BatchIssueRedeem). \ - filter(BatchIssueRedeem.upload_id == upload_1_id). \ - all() + _upload_1_data_after: List[BatchIssueRedeem] = ( + db.query(BatchIssueRedeem) + .filter(BatchIssueRedeem.upload_id == upload_1_id) + .all() + ) assert len(_upload_1_data_after) == 1 assert _upload_1_data_after[0].status == 2 - _upload_2_after: BatchIssueRedeemUpload = db.query(BatchIssueRedeemUpload). \ - filter(BatchIssueRedeemUpload.upload_id == upload_2_id). \ - first() + _upload_2_after: BatchIssueRedeemUpload = ( + db.query(BatchIssueRedeemUpload) + .filter(BatchIssueRedeemUpload.upload_id == upload_2_id) + .first() + ) assert _upload_2_after.processed == True - _upload_2_data_after: List[BatchIssueRedeem] = db.query(BatchIssueRedeem). \ - filter(BatchIssueRedeem.upload_id == upload_2_id). \ - all() + _upload_2_data_after: List[BatchIssueRedeem] = ( + db.query(BatchIssueRedeem) + .filter(BatchIssueRedeem.upload_id == upload_2_id) + .all() + ) assert len(_upload_2_data_after) == 1 assert _upload_2_data_after[0].status == 2 # Assertion: Log - assert caplog.record_tuples.count(( - LOG.name, - logging.WARNING, - f"Transaction reverted: upload_id=<{_upload_1_after.upload_id}> error_code:<999999> error_msg:<>" - )) == 1 - assert caplog.record_tuples.count(( - LOG.name, - logging.WARNING, - f"Transaction reverted: upload_id=<{_upload_2_after.upload_id}> error_code:<999999> error_msg:<>" - )) == 1 + assert ( + caplog.record_tuples.count( + ( + LOG.name, + logging.WARNING, + f"Transaction reverted: upload_id=<{_upload_1_after.upload_id}> error_code:<999999> error_msg:<>", + ) + ) + == 1 + ) + assert ( + caplog.record_tuples.count( + ( + LOG.name, + logging.WARNING, + f"Transaction reverted: upload_id=<{_upload_2_after.upload_id}> error_code:<999999> error_msg:<>", + ) + ) + == 1 + ) _notification_list = db.query(Notification).all() assert _notification_list[0].notice_id is not None assert _notification_list[0].issuer_address == issuer_address assert _notification_list[0].priority == 1 - assert _notification_list[0].type == NotificationType.BATCH_ISSUE_REDEEM_PROCESSED + assert ( + _notification_list[0].type == NotificationType.BATCH_ISSUE_REDEEM_PROCESSED + ) assert _notification_list[0].code == 3 # Failed assert _notification_list[0].metainfo == { "category": BatchIssueRedeemProcessingCategory.ISSUE.value, "upload_id": upload_1_id, "error_data_id": ANY, "token_address": token_address, - "token_type": TokenType.IBET_STRAIGHT_BOND + "token_type": TokenType.IBET_STRAIGHT_BOND, } assert len(_notification_list[0].metainfo["error_data_id"]) == 1 assert _notification_list[1].notice_id is not None assert _notification_list[1].issuer_address == issuer_address assert _notification_list[1].priority == 1 - assert _notification_list[1].type == NotificationType.BATCH_ISSUE_REDEEM_PROCESSED + assert ( + _notification_list[1].type == NotificationType.BATCH_ISSUE_REDEEM_PROCESSED + ) assert _notification_list[1].code == 3 # Failed assert _notification_list[1].metainfo == { "category": BatchIssueRedeemProcessingCategory.ISSUE.value, "upload_id": upload_2_id, "error_data_id": ANY, "token_address": token_address, - "token_type": TokenType.IBET_SHARE + "token_type": TokenType.IBET_SHARE, } assert len(_notification_list[1].metainfo["error_data_id"]) == 1 diff --git a/tests/test_batch_processor_bulk_transfer.py b/tests/test_batch_processor_bulk_transfer.py index 921f6513..8d383d62 100644 --- a/tests/test_batch_processor_bulk_transfer.py +++ b/tests/test_batch_processor_bulk_transfer.py @@ -16,21 +16,21 @@ SPDX-License-Identifier: Apache-2.0 """ -import pytest from unittest.mock import patch +import pytest + +from app.exceptions import SendTransactionError from app.model.db import ( Account, BulkTransfer, BulkTransferUpload, - TokenType, Notification, - NotificationType + NotificationType, + TokenType, ) from app.utils.e2ee_utils import E2EEUtils -from app.exceptions import SendTransactionError from batch.processor_bulk_transfer import Processor - from tests.account_config import config_eth_account @@ -43,14 +43,16 @@ class TestProcessor: account_list = [ { "address": config_eth_account("user1")["address"], - "keyfile": config_eth_account("user1")["keyfile_json"] - }, { + "keyfile": config_eth_account("user1")["keyfile_json"], + }, + { "address": config_eth_account("user2")["address"], - "keyfile": config_eth_account("user2")["keyfile_json"] - }, { + "keyfile": config_eth_account("user2")["keyfile_json"], + }, + { "address": config_eth_account("user3")["address"], - "keyfile": config_eth_account("user3")["keyfile_json"] - } + "keyfile": config_eth_account("user3")["keyfile_json"], + }, ] upload_id_list = [ @@ -59,7 +61,7 @@ class TestProcessor: "0f33d48f-9e6e-4a36-a55e-5bbcbda69c80", "1c961f7d-e1ad-40e5-988b-cca3d6009643", "1e778f46-864e-4ec0-b566-21bd31cf63ff", - "1f33d48f-9e6e-4a36-a55e-5bbcbda69c80" + "1f33d48f-9e6e-4a36-a55e-5bbcbda69c80", ] bulk_transfer_token = [ @@ -117,7 +119,7 @@ def test_normal_1(self, processor, db): # mock IbetStraightBondContract_transfer = patch( target="app.model.blockchain.token.IbetStraightBondContract.transfer", - return_value=None + return_value=None, ) with IbetStraightBondContract_transfer: @@ -125,14 +127,18 @@ def test_normal_1(self, processor, db): processor.process() # Assertion - _bulk_transfer_upload = db.query(BulkTransferUpload). \ - filter(BulkTransferUpload.upload_id == self.upload_id_list[0]). \ - first() + _bulk_transfer_upload = ( + db.query(BulkTransferUpload) + .filter(BulkTransferUpload.upload_id == self.upload_id_list[0]) + .first() + ) assert _bulk_transfer_upload.status == 1 - _bulk_transfer_list = db.query(BulkTransfer). \ - filter(BulkTransfer.upload_id == self.upload_id_list[0]). \ - all() + _bulk_transfer_list = ( + db.query(BulkTransfer) + .filter(BulkTransfer.upload_id == self.upload_id_list[0]) + .all() + ) for _bulk_transfer in _bulk_transfer_list: assert _bulk_transfer.status == 1 @@ -178,7 +184,7 @@ def test_normal_2(self, processor, db): # mock IbetShareContract_transfer = patch( target="app.model.blockchain.token.IbetShareContract.transfer", - return_value=None + return_value=None, ) with IbetShareContract_transfer: @@ -186,14 +192,18 @@ def test_normal_2(self, processor, db): processor.process() # Assertion - _bulk_transfer_upload = db.query(BulkTransferUpload). \ - filter(BulkTransferUpload.upload_id == self.upload_id_list[0]). \ - first() + _bulk_transfer_upload = ( + db.query(BulkTransferUpload) + .filter(BulkTransferUpload.upload_id == self.upload_id_list[0]) + .first() + ) assert _bulk_transfer_upload.status == 1 - _bulk_transfer_list = db.query(BulkTransfer). \ - filter(BulkTransfer.upload_id == self.upload_id_list[0]). \ - all() + _bulk_transfer_list = ( + db.query(BulkTransfer) + .filter(BulkTransfer.upload_id == self.upload_id_list[0]) + .all() + ) for _bulk_transfer in _bulk_transfer_list: assert _bulk_transfer.status == 1 @@ -215,13 +225,17 @@ def test_normal_3(self, processor, db): # Prepare data : BulkTransferUpload bulk_transfer_upload = BulkTransferUpload() - bulk_transfer_upload.issuer_address = _other_issuer_address_1 # other thread processed issuer + bulk_transfer_upload.issuer_address = ( + _other_issuer_address_1 # other thread processed issuer + ) bulk_transfer_upload.upload_id = self.upload_id_list[0] bulk_transfer_upload.token_type = TokenType.IBET_STRAIGHT_BOND.value bulk_transfer_upload.status = 0 db.add(bulk_transfer_upload) bulk_transfer_upload = BulkTransferUpload() - bulk_transfer_upload.issuer_address = _other_issuer_address_1 # other thread processed issuer + bulk_transfer_upload.issuer_address = ( + _other_issuer_address_1 # other thread processed issuer + ) bulk_transfer_upload.upload_id = self.upload_id_list[1] bulk_transfer_upload.token_type = TokenType.IBET_STRAIGHT_BOND.value bulk_transfer_upload.status = 0 @@ -274,7 +288,7 @@ def test_normal_3(self, processor, db): # mock IbetStraightBondContract_transfer = patch( target="app.model.blockchain.token.IbetStraightBondContract.transfer", - return_value=None + return_value=None, ) processing_issuer = patch( "batch.processor_bulk_transfer.processing_issuer", @@ -283,7 +297,7 @@ def test_normal_3(self, processor, db): self.upload_id_list[0]: _other_issuer_address_1, self.upload_id_list[1]: _other_issuer_address_1, } - } + }, ) with IbetStraightBondContract_transfer, processing_issuer: @@ -291,9 +305,9 @@ def test_normal_3(self, processor, db): processor.process() # Assertion - _bulk_transfer_upload_list = db.query(BulkTransferUpload). \ - order_by(BulkTransferUpload.created). \ - all() + _bulk_transfer_upload_list = ( + db.query(BulkTransferUpload).order_by(BulkTransferUpload.created).all() + ) _bulk_transfer_upload = _bulk_transfer_upload_list[0] assert _bulk_transfer_upload.status == 0 _bulk_transfer_upload = _bulk_transfer_upload_list[1] @@ -304,16 +318,20 @@ def test_normal_3(self, processor, db): assert _bulk_transfer_upload.status == 1 _bulk_transfer_upload = _bulk_transfer_upload_list[4] assert _bulk_transfer_upload.status == 1 - _bulk_transfer_list = db.query(BulkTransfer). \ - filter(BulkTransfer.upload_id == self.upload_id_list[3]). \ - order_by(BulkTransfer.id). \ - all() + _bulk_transfer_list = ( + db.query(BulkTransfer) + .filter(BulkTransfer.upload_id == self.upload_id_list[3]) + .order_by(BulkTransfer.id) + .all() + ) _bulk_transfer = _bulk_transfer_list[0] assert _bulk_transfer.status == 1 - _bulk_transfer_list = db.query(BulkTransfer). \ - filter(BulkTransfer.upload_id == self.upload_id_list[4]). \ - order_by(BulkTransfer.id). \ - all() + _bulk_transfer_list = ( + db.query(BulkTransfer) + .filter(BulkTransfer.upload_id == self.upload_id_list[4]) + .order_by(BulkTransfer.id) + .all() + ) _bulk_transfer = _bulk_transfer_list[0] assert _bulk_transfer.status == 1 @@ -334,25 +352,33 @@ def test_normal_4(self, processor, db): # Prepare data : BulkTransferUpload bulk_transfer_upload = BulkTransferUpload() - bulk_transfer_upload.issuer_address = _account["address"] # other thread processed issuer + bulk_transfer_upload.issuer_address = _account[ + "address" + ] # other thread processed issuer bulk_transfer_upload.upload_id = self.upload_id_list[0] bulk_transfer_upload.token_type = TokenType.IBET_STRAIGHT_BOND.value bulk_transfer_upload.status = 0 db.add(bulk_transfer_upload) bulk_transfer_upload = BulkTransferUpload() - bulk_transfer_upload.issuer_address = _account["address"] # other thread processed issuer + bulk_transfer_upload.issuer_address = _account[ + "address" + ] # other thread processed issuer bulk_transfer_upload.upload_id = self.upload_id_list[1] bulk_transfer_upload.token_type = TokenType.IBET_STRAIGHT_BOND.value bulk_transfer_upload.status = 0 db.add(bulk_transfer_upload) bulk_transfer_upload = BulkTransferUpload() - bulk_transfer_upload.issuer_address = _account["address"] # other thread same issuer + bulk_transfer_upload.issuer_address = _account[ + "address" + ] # other thread same issuer bulk_transfer_upload.upload_id = self.upload_id_list[2] bulk_transfer_upload.token_type = TokenType.IBET_STRAIGHT_BOND.value bulk_transfer_upload.status = 0 db.add(bulk_transfer_upload) bulk_transfer_upload = BulkTransferUpload() - bulk_transfer_upload.issuer_address = _account["address"] # other thread same issuer + bulk_transfer_upload.issuer_address = _account[ + "address" + ] # other thread same issuer bulk_transfer_upload.upload_id = self.upload_id_list[3] bulk_transfer_upload.token_type = TokenType.IBET_STRAIGHT_BOND.value bulk_transfer_upload.status = 0 @@ -387,7 +413,7 @@ def test_normal_4(self, processor, db): # mock IbetStraightBondContract_transfer = patch( target="app.model.blockchain.token.IbetStraightBondContract.transfer", - return_value=None + return_value=None, ) processing_issuer = patch( "batch.processor_bulk_transfer.processing_issuer", @@ -396,7 +422,7 @@ def test_normal_4(self, processor, db): self.upload_id_list[0]: _account["address"], self.upload_id_list[1]: _account["address"], } - } + }, ) with IbetStraightBondContract_transfer, processing_issuer: @@ -404,9 +430,9 @@ def test_normal_4(self, processor, db): processor.process() # Assertion - _bulk_transfer_upload_list = db.query(BulkTransferUpload). \ - order_by(BulkTransferUpload.created). \ - all() + _bulk_transfer_upload_list = ( + db.query(BulkTransferUpload).order_by(BulkTransferUpload.created).all() + ) _bulk_transfer_upload = _bulk_transfer_upload_list[0] assert _bulk_transfer_upload.status == 0 _bulk_transfer_upload = _bulk_transfer_upload_list[1] @@ -415,16 +441,20 @@ def test_normal_4(self, processor, db): assert _bulk_transfer_upload.status == 1 _bulk_transfer_upload = _bulk_transfer_upload_list[3] assert _bulk_transfer_upload.status == 1 - _bulk_transfer_list = db.query(BulkTransfer). \ - filter(BulkTransfer.upload_id == self.upload_id_list[2]). \ - order_by(BulkTransfer.id). \ - all() + _bulk_transfer_list = ( + db.query(BulkTransfer) + .filter(BulkTransfer.upload_id == self.upload_id_list[2]) + .order_by(BulkTransfer.id) + .all() + ) _bulk_transfer = _bulk_transfer_list[0] assert _bulk_transfer.status == 1 - _bulk_transfer_list = db.query(BulkTransfer). \ - filter(BulkTransfer.upload_id == self.upload_id_list[3]). \ - order_by(BulkTransfer.id). \ - all() + _bulk_transfer_list = ( + db.query(BulkTransfer) + .filter(BulkTransfer.upload_id == self.upload_id_list[3]) + .order_by(BulkTransfer.id) + .all() + ) _bulk_transfer = _bulk_transfer_list[0] assert _bulk_transfer.status == 1 @@ -451,9 +481,11 @@ def test_error_1(self, processor, db): processor.process() # Assertion - _bulk_transfer_upload = db.query(BulkTransferUpload). \ - filter(BulkTransferUpload.upload_id == self.upload_id_list[0]). \ - first() + _bulk_transfer_upload = ( + db.query(BulkTransferUpload) + .filter(BulkTransferUpload.upload_id == self.upload_id_list[0]) + .first() + ) assert _bulk_transfer_upload.status == 2 _notification = db.query(Notification).first() assert _notification.id == 1 @@ -465,7 +497,7 @@ def test_error_1(self, processor, db): assert _notification.metainfo == { "upload_id": self.upload_id_list[0], "token_type": TokenType.IBET_STRAIGHT_BOND.value, - "error_transfer_id": [] + "error_transfer_id": [], } # @@ -494,9 +526,11 @@ def test_error_2(self, processor, db): processor.process() # Assertion - _bulk_transfer_upload = db.query(BulkTransferUpload). \ - filter(BulkTransferUpload.upload_id == self.upload_id_list[0]). \ - first() + _bulk_transfer_upload = ( + db.query(BulkTransferUpload) + .filter(BulkTransferUpload.upload_id == self.upload_id_list[0]) + .first() + ) assert _bulk_transfer_upload.status == 2 _notification = db.query(Notification).first() assert _notification.id == 1 @@ -508,7 +542,7 @@ def test_error_2(self, processor, db): assert _notification.metainfo == { "upload_id": self.upload_id_list[0], "token_type": TokenType.IBET_STRAIGHT_BOND.value, - "error_transfer_id": [] + "error_transfer_id": [], } # @@ -550,7 +584,7 @@ def test_error_3(self, processor, db): # mock IbetStraightBondContract_transfer = patch( target="app.model.blockchain.token.IbetStraightBondContract.transfer", - side_effect=SendTransactionError() + side_effect=SendTransactionError(), ) with IbetStraightBondContract_transfer: @@ -558,15 +592,19 @@ def test_error_3(self, processor, db): processor.process() # Assertion - _bulk_transfer_upload = db.query(BulkTransferUpload). \ - filter(BulkTransferUpload.upload_id == self.upload_id_list[0]). \ - first() + _bulk_transfer_upload = ( + db.query(BulkTransferUpload) + .filter(BulkTransferUpload.upload_id == self.upload_id_list[0]) + .first() + ) assert _bulk_transfer_upload.status == 2 - _bulk_transfer = db.query(BulkTransfer). \ - filter(BulkTransfer.upload_id == self.upload_id_list[0]). \ - filter(BulkTransfer.token_address == self.bulk_transfer_token[0]). \ - first() + _bulk_transfer = ( + db.query(BulkTransfer) + .filter(BulkTransfer.upload_id == self.upload_id_list[0]) + .filter(BulkTransfer.token_address == self.bulk_transfer_token[0]) + .first() + ) assert _bulk_transfer.status == 2 _notification = db.query(Notification).first() @@ -579,7 +617,7 @@ def test_error_3(self, processor, db): assert _notification.metainfo == { "upload_id": self.upload_id_list[0], "token_type": TokenType.IBET_STRAIGHT_BOND.value, - "error_transfer_id": [1] + "error_transfer_id": [1], } # @@ -621,7 +659,7 @@ def test_error_4(self, processor, db): # mock IbetShareContract_transfer = patch( target="app.model.blockchain.token.IbetShareContract.transfer", - side_effect=SendTransactionError() + side_effect=SendTransactionError(), ) with IbetShareContract_transfer: @@ -629,15 +667,19 @@ def test_error_4(self, processor, db): processor.process() # Assertion - _bulk_transfer_upload = db.query(BulkTransferUpload). \ - filter(BulkTransferUpload.upload_id == self.upload_id_list[0]). \ - first() + _bulk_transfer_upload = ( + db.query(BulkTransferUpload) + .filter(BulkTransferUpload.upload_id == self.upload_id_list[0]) + .first() + ) assert _bulk_transfer_upload.status == 2 - _bulk_transfer = db.query(BulkTransfer). \ - filter(BulkTransfer.upload_id == self.upload_id_list[0]). \ - filter(BulkTransfer.token_address == self.bulk_transfer_token[0]). \ - first() + _bulk_transfer = ( + db.query(BulkTransfer) + .filter(BulkTransfer.upload_id == self.upload_id_list[0]) + .filter(BulkTransfer.token_address == self.bulk_transfer_token[0]) + .first() + ) assert _bulk_transfer.status == 2 _notification = db.query(Notification).first() @@ -650,7 +692,7 @@ def test_error_4(self, processor, db): assert _notification.metainfo == { "upload_id": self.upload_id_list[0], "token_type": TokenType.IBET_SHARE.value, - "error_transfer_id": [1] + "error_transfer_id": [1], } # @@ -695,7 +737,7 @@ def test_error_5(self, processor, db): # mock IbetStraightBondContract_transfer = patch( target="app.model.blockchain.token.IbetStraightBondContract.transfer", - return_value=None + return_value=None, ) with IbetStraightBondContract_transfer: @@ -703,15 +745,19 @@ def test_error_5(self, processor, db): processor.process() # Assertion - _bulk_transfer_upload = db.query(BulkTransferUpload). \ - filter(BulkTransferUpload.upload_id == self.upload_id_list[0]). \ - first() + _bulk_transfer_upload = ( + db.query(BulkTransferUpload) + .filter(BulkTransferUpload.upload_id == self.upload_id_list[0]) + .first() + ) assert _bulk_transfer_upload.status == 2 - _bulk_transfer = db.query(BulkTransfer). \ - filter(BulkTransfer.upload_id == self.upload_id_list[0]). \ - filter(BulkTransfer.token_address == self.bulk_transfer_token[0]). \ - first() + _bulk_transfer = ( + db.query(BulkTransfer) + .filter(BulkTransfer.upload_id == self.upload_id_list[0]) + .filter(BulkTransfer.token_address == self.bulk_transfer_token[0]) + .first() + ) assert _bulk_transfer.status == 1 _notification = db.query(Notification).first() @@ -724,5 +770,5 @@ def test_error_5(self, processor, db): assert _notification.metainfo == { "upload_id": self.upload_id_list[0], "token_type": TokenType.IBET_STRAIGHT_BOND.value, - "error_transfer_id": [3] + "error_transfer_id": [3], } diff --git a/tests/test_batch_processor_create_utxo.py b/tests/test_batch_processor_create_utxo.py index fc251b4a..1bc7e432 100644 --- a/tests/test_batch_processor_create_utxo.py +++ b/tests/test_batch_processor_create_utxo.py @@ -16,65 +16,66 @@ SPDX-License-Identifier: Apache-2.0 """ -import pytest -from unittest import mock -from unittest.mock import ( - call, - MagicMock, - ANY -) import time +from unittest import mock +from unittest.mock import ANY, MagicMock, call +import pytest +from eth_keyfile import decode_keyfile_json from web3 import Web3 from web3.middleware import geth_poa_middleware -from eth_keyfile import decode_keyfile_json -from config import ( - WEB3_HTTP_PROVIDER, - CHAIN_ID, - TX_GAS_LIMIT +from app.model.blockchain import IbetShareContract, IbetStraightBondContract +from app.model.blockchain.tx_params.ibet_share import ( + AdditionalIssueParams as IbetShareAdditionalIssueParams, ) -from app.model.blockchain import ( - IbetShareContract, - IbetStraightBondContract +from app.model.blockchain.tx_params.ibet_share import ( + RedeemParams as IbetShareRedeemParams, ) from app.model.blockchain.tx_params.ibet_share import ( - UpdateParams as IbetShareUpdateParams, TransferParams as IbetShareTransferParams, - AdditionalIssueParams as IbetShareAdditionalIssueParams, - RedeemParams as IbetShareRedeemParams +) +from app.model.blockchain.tx_params.ibet_share import ( + UpdateParams as IbetShareUpdateParams, ) from app.model.blockchain.tx_params.ibet_straight_bond import ( - UpdateParams as IbetStraightBondUpdateParams, - TransferParams as IbetStraightBondTransferParams, AdditionalIssueParams as IbetStraightBondAdditionalIssueParams, - RedeemParams as IbetStraightBondRedeemParams ) -from app.model.db import ( - Token, - TokenType, - UTXO, - UTXOBlockNumber +from app.model.blockchain.tx_params.ibet_straight_bond import ( + RedeemParams as IbetStraightBondRedeemParams, +) +from app.model.blockchain.tx_params.ibet_straight_bond import ( + TransferParams as IbetStraightBondTransferParams, +) +from app.model.blockchain.tx_params.ibet_straight_bond import ( + UpdateParams as IbetStraightBondUpdateParams, ) +from app.model.db import UTXO, Token, TokenType, UTXOBlockNumber from app.utils.contract_utils import ContractUtils from batch.processor_create_utxo import Processor +from config import CHAIN_ID, TX_GAS_LIMIT, WEB3_HTTP_PROVIDER from tests.account_config import config_eth_account +from tests.utils.contract_utils import IbetExchangeContractTestUtils from tests.utils.contract_utils import ( IbetSecurityTokenContractTestUtils as STContractUtils, - PersonalInfoContractTestUtils, - IbetExchangeContractTestUtils ) +from tests.utils.contract_utils import PersonalInfoContractTestUtils web3 = Web3(Web3.HTTPProvider(WEB3_HTTP_PROVIDER)) web3.middleware_onion.inject(geth_poa_middleware, layer=0) -@pytest.fixture(scope='function') +@pytest.fixture(scope="function") def processor(db): return Processor() -def deploy_bond_token_contract(address, private_key, personal_info_contract_address=None, tradable_exchange_contract_address=None): +def deploy_bond_token_contract( + address, + private_key, + personal_info_contract_address=None, + tradable_exchange_contract_address=None, +): arguments = [ "token.name", "token.symbol", @@ -84,7 +85,7 @@ def deploy_bond_token_contract(address, private_key, personal_info_contract_addr 30, "token.return_date", "token.return_amount", - "token.purpose" + "token.purpose", ] bond_contrat = IbetStraightBondContract() contract_address, _, _ = bond_contrat.create(arguments, address, private_key) @@ -95,7 +96,7 @@ def deploy_bond_token_contract(address, private_key, personal_info_contract_addr tradable_exchange_contract_address=tradable_exchange_contract_address, ), address, - private_key + private_key, ) return contract_address @@ -111,21 +112,18 @@ def deploy_share_token_contract(address, private_key): "token.dividend_record_date", "token.dividend_payment_date", "token.cancellation_date", - 30 + 30, ] share_contract = IbetShareContract() contract_address, _, _ = share_contract.create(arguments, address, private_key) share_contract.update( - IbetShareUpdateParams(transferable=True), - address, - private_key + IbetShareUpdateParams(transferable=True), address, private_key ) return contract_address class TestProcessor: - ########################################################################### # Normal Case ########################################################################### @@ -138,8 +136,7 @@ def test_normal_1(self, mock_func, processor, db): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] @@ -156,7 +153,9 @@ def test_normal_1(self, mock_func, processor, db): _token_1.abi = {} db.add(_token_1) - token_address_2 = deploy_share_token_contract(issuer_address, issuer_private_key) + token_address_2 = deploy_share_token_contract( + issuer_address, issuer_private_key + ) _token_2 = Token() _token_2.type = TokenType.IBET_SHARE.value _token_2.tx_hash = "" @@ -181,38 +180,38 @@ def test_normal_1(self, mock_func, processor, db): # Execute Transfer Event # Share:issuer -> user1 _transfer_1 = IbetShareTransferParams( - from_address=issuer_address, - to_address=user_address_1, - amount=70 + from_address=issuer_address, to_address=user_address_1, amount=70 + ) + IbetShareContract(token_address_2).transfer( + _transfer_1, issuer_address, issuer_private_key ) - IbetShareContract(token_address_2).transfer(_transfer_1, issuer_address, issuer_private_key) time.sleep(1) # Bond:issuer -> user1 _transfer_2 = IbetStraightBondTransferParams( - from_address=issuer_address, - to_address=user_address_1, - amount=40 + from_address=issuer_address, to_address=user_address_1, amount=40 + ) + IbetStraightBondContract(token_address_1).transfer( + _transfer_2, issuer_address, issuer_private_key ) - IbetStraightBondContract(token_address_1).transfer(_transfer_2, issuer_address, issuer_private_key) time.sleep(1) # Bond:issuer -> user2 _transfer_3 = IbetStraightBondTransferParams( - from_address=issuer_address, - to_address=user_address_2, - amount=20 + from_address=issuer_address, to_address=user_address_2, amount=20 + ) + IbetStraightBondContract(token_address_1).transfer( + _transfer_3, issuer_address, issuer_private_key ) - IbetStraightBondContract(token_address_1).transfer(_transfer_3, issuer_address, issuer_private_key) time.sleep(1) # Share:user1 -> user2 _transfer_4 = IbetShareTransferParams( - from_address=user_address_1, - to_address=user_address_2, - amount=10 + from_address=user_address_1, to_address=user_address_2, amount=10 + ) + IbetShareContract(token_address_2).transfer( + _transfer_4, issuer_address, issuer_private_key ) - IbetShareContract(token_address_2).transfer(_transfer_4, issuer_address, issuer_private_key) time.sleep(1) # Execute batch(Run 2nd) @@ -258,10 +257,12 @@ def test_normal_1(self, mock_func, processor, db): _utox_block_number = db.query(UTXOBlockNumber).first() assert _utox_block_number.latest_block_number == _utox_list[3].block_number - mock_func.assert_has_calls([ - call(token_address=token_address_1, db=ANY), - call(token_address=token_address_2, db=ANY) - ]) + mock_func.assert_has_calls( + [ + call(token_address=token_address_1, db=ANY), + call(token_address=token_address_2, db=ANY), + ] + ) # # Over max block lot @@ -271,8 +272,7 @@ def test_normal_2(self, mock_func, processor, db): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] @@ -298,26 +298,34 @@ def test_normal_2(self, mock_func, processor, db): # Transfer event 6 times _transfer = IbetStraightBondTransferParams( - from_address=issuer_address, - to_address=user_address_1, - amount=60 + from_address=issuer_address, to_address=user_address_1, amount=60 + ) + IbetStraightBondContract(token_address_1).transfer( + _transfer, issuer_address, issuer_private_key ) - IbetStraightBondContract(token_address_1).transfer(_transfer, issuer_address, issuer_private_key) time.sleep(1) _transfer = IbetStraightBondTransferParams( - from_address=user_address_1, - to_address=user_address_2, - amount=10 + from_address=user_address_1, to_address=user_address_2, amount=10 + ) + IbetStraightBondContract(token_address_1).transfer( + _transfer, issuer_address, issuer_private_key ) - IbetStraightBondContract(token_address_1).transfer(_transfer, issuer_address, issuer_private_key) time.sleep(1) - IbetStraightBondContract(token_address_1).transfer(_transfer, issuer_address, issuer_private_key) + IbetStraightBondContract(token_address_1).transfer( + _transfer, issuer_address, issuer_private_key + ) time.sleep(1) - IbetStraightBondContract(token_address_1).transfer(_transfer, issuer_address, issuer_private_key) + IbetStraightBondContract(token_address_1).transfer( + _transfer, issuer_address, issuer_private_key + ) time.sleep(1) - IbetStraightBondContract(token_address_1).transfer(_transfer, issuer_address, issuer_private_key) + IbetStraightBondContract(token_address_1).transfer( + _transfer, issuer_address, issuer_private_key + ) time.sleep(1) - IbetStraightBondContract(token_address_1).transfer(_transfer, issuer_address, issuer_private_key) + IbetStraightBondContract(token_address_1).transfer( + _transfer, issuer_address, issuer_private_key + ) time.sleep(1) # Execute batch @@ -366,20 +374,17 @@ def test_normal_3(self, mock_func, processor, db): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] user_1_private_key = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] user_2_private_key = decode_keyfile_json( - raw_keyfile_json=user_3["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") ) # prepare data @@ -398,19 +403,24 @@ def test_normal_3(self, mock_func, processor, db): # set personal info personal_contract_address, _, _ = ContractUtils.deploy_contract( - "PersonalInfo", [], issuer_address, issuer_private_key) + "PersonalInfo", [], issuer_address, issuer_private_key + ) IbetStraightBondContract(token_address_1).update( - IbetStraightBondUpdateParams(personal_info_contract_address=personal_contract_address), + IbetStraightBondUpdateParams( + personal_info_contract_address=personal_contract_address + ), issuer_address, - issuer_private_key + issuer_private_key, + ) + personal_contract = ContractUtils.get_contract( + "PersonalInfo", personal_contract_address ) - personal_contract = ContractUtils.get_contract("PersonalInfo", personal_contract_address) tx = personal_contract.functions.register(issuer_address, "").build_transaction( { "chainId": CHAIN_ID, "from": user_address_1, "gas": TX_GAS_LIMIT, - "gasPrice": 0 + "gasPrice": 0, } ) ContractUtils.send_transaction(tx, user_1_private_key) @@ -419,21 +429,20 @@ def test_normal_3(self, mock_func, processor, db): "chainId": CHAIN_ID, "from": user_address_2, "gas": TX_GAS_LIMIT, - "gasPrice": 0 + "gasPrice": 0, } ) ContractUtils.send_transaction(tx, user_2_private_key) # bulk transfer tx = token_contract.functions.bulkTransfer( - [user_address_1, user_address_2, user_address_1], - [10, 20, 40] + [user_address_1, user_address_2, user_address_1], [10, 20, 40] ).build_transaction( { "chainId": CHAIN_ID, "from": issuer_address, "gas": TX_GAS_LIMIT, - "gasPrice": 0 + "gasPrice": 0, } ) ContractUtils.send_transaction(tx, issuer_private_key) @@ -462,8 +471,7 @@ def test_normal_4(self, mock_func, processor, db): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # prepare data @@ -479,29 +487,39 @@ def test_normal_4(self, mock_func, processor, db): db.commit() # set exchange address - storage_address, _, _ = \ - ContractUtils.deploy_contract("EscrowStorage", [], issuer_address, issuer_private_key) - exchange_address, _, _ = \ - ContractUtils.deploy_contract("IbetEscrow", [storage_address], issuer_address, issuer_private_key) + storage_address, _, _ = ContractUtils.deploy_contract( + "EscrowStorage", [], issuer_address, issuer_private_key + ) + exchange_address, _, _ = ContractUtils.deploy_contract( + "IbetEscrow", [storage_address], issuer_address, issuer_private_key + ) storage_contract = ContractUtils.get_contract("EscrowStorage", storage_address) - tx = storage_contract.functions.upgradeVersion(exchange_address).build_transaction({ - "chainId": CHAIN_ID, - "from": issuer_address, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = storage_contract.functions.upgradeVersion( + exchange_address + ).build_transaction( + { + "chainId": CHAIN_ID, + "from": issuer_address, + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, issuer_private_key) - update_data = IbetStraightBondUpdateParams(tradable_exchange_contract_address=exchange_address) - IbetStraightBondContract(token_address_1).update(update_data, issuer_address, issuer_private_key) + update_data = IbetStraightBondUpdateParams( + tradable_exchange_contract_address=exchange_address + ) + IbetStraightBondContract(token_address_1).update( + update_data, issuer_address, issuer_private_key + ) # Execute Transfer Event # Bond:issuer -> Exchange _transfer_1 = IbetStraightBondTransferParams( - from_address=issuer_address, - to_address=exchange_address, - amount=100 + from_address=issuer_address, to_address=exchange_address, amount=100 + ) + IbetStraightBondContract(token_address_1).transfer( + _transfer_1, issuer_address, issuer_private_key ) - IbetStraightBondContract(token_address_1).transfer(_transfer_1, issuer_address, issuer_private_key) # Execute batch # Assume: Not Create UTXO and Ledger @@ -515,22 +533,31 @@ def test_normal_4(self, mock_func, processor, db): # # Holder Changed @mock.patch("batch.processor_create_utxo.create_ledger") - def test_normal_5(self, mock_func, processor, db, personal_info_contract, ibet_exchange_contract): + def test_normal_5( + self, mock_func, processor, db, personal_info_contract, ibet_exchange_contract + ): user_1 = config_eth_account("user1") issuer_address = user_1["address"] - issuer_private_key = decode_keyfile_json(raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8")) + issuer_private_key = decode_keyfile_json( + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") + ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] - user_pk_1 = decode_keyfile_json(raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8")) + user_pk_1 = decode_keyfile_json( + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") + ) user_3 = config_eth_account("user3") user_address_2 = user_3["address"] - user_pk_2 = decode_keyfile_json(raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8")) + user_pk_2 = decode_keyfile_json( + raw_keyfile_json=user_3["keyfile_json"], password="password".encode("utf-8") + ) # prepare data token_address_1 = deploy_bond_token_contract( - issuer_address, issuer_private_key, + issuer_address, + issuer_private_key, personal_info_contract_address=personal_info_contract.address, - tradable_exchange_contract_address=ibet_exchange_contract.address + tradable_exchange_contract_address=ibet_exchange_contract.address, ) _token_1 = Token() _token_1.type = TokenType.IBET_STRAIGHT_BOND.value @@ -540,43 +567,118 @@ def test_normal_5(self, mock_func, processor, db, personal_info_contract, ibet_e _token_1.abi = {} db.add(_token_1) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_1, user_pk_1, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, user_address_2, user_pk_2, [issuer_address, ""]) - PersonalInfoContractTestUtils.register(personal_info_contract.address, issuer_address, issuer_private_key, [issuer_address, ""]) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_1, + user_pk_1, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + user_address_2, + user_pk_2, + [issuer_address, ""], + ) + PersonalInfoContractTestUtils.register( + personal_info_contract.address, + issuer_address, + issuer_private_key, + [issuer_address, ""], + ) - STContractUtils.transfer(token_address_1, issuer_address, issuer_private_key, [user_address_1, 10]) - STContractUtils.transfer(token_address_1, issuer_address, issuer_private_key, [user_address_2, 10]) - STContractUtils.transfer(token_address_1, user_address_1, user_pk_1, [ibet_exchange_contract.address, 10]) - STContractUtils.transfer(token_address_1, issuer_address, issuer_private_key, [ibet_exchange_contract.address, 10]) + STContractUtils.transfer( + token_address_1, issuer_address, issuer_private_key, [user_address_1, 10] + ) + STContractUtils.transfer( + token_address_1, issuer_address, issuer_private_key, [user_address_2, 10] + ) + STContractUtils.transfer( + token_address_1, + user_address_1, + user_pk_1, + [ibet_exchange_contract.address, 10], + ) + STContractUtils.transfer( + token_address_1, + issuer_address, + issuer_private_key, + [ibet_exchange_contract.address, 10], + ) IbetExchangeContractTestUtils.create_order( - ibet_exchange_contract.address, user_address_1, user_pk_1, [token_address_1, 10, 100, False, issuer_address] + ibet_exchange_contract.address, + user_address_1, + user_pk_1, + [token_address_1, 10, 100, False, issuer_address], + ) + latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id( + ibet_exchange_contract.address + ) + IbetExchangeContractTestUtils.execute_order( + ibet_exchange_contract.address, + user_address_2, + user_pk_2, + [latest_order_id, 10, True], + ) + latest_agreement_id = IbetExchangeContractTestUtils.get_latest_agreementid( + ibet_exchange_contract.address, latest_order_id ) - latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id(ibet_exchange_contract.address) - IbetExchangeContractTestUtils.execute_order(ibet_exchange_contract.address, user_address_2, user_pk_2, [latest_order_id, 10, True]) - latest_agreement_id = IbetExchangeContractTestUtils.get_latest_agreementid(ibet_exchange_contract.address, latest_order_id) IbetExchangeContractTestUtils.confirm_agreement( - ibet_exchange_contract.address, issuer_address, issuer_private_key, [latest_order_id, latest_agreement_id] + ibet_exchange_contract.address, + issuer_address, + issuer_private_key, + [latest_order_id, latest_agreement_id], ) # prepare other data other_token_address = deploy_bond_token_contract( - issuer_address, issuer_private_key, + issuer_address, + issuer_private_key, personal_info_contract_address=personal_info_contract.address, - tradable_exchange_contract_address=ibet_exchange_contract.address + tradable_exchange_contract_address=ibet_exchange_contract.address, + ) + STContractUtils.transfer( + other_token_address, + issuer_address, + issuer_private_key, + [user_address_1, 10], + ) + STContractUtils.transfer( + other_token_address, + user_address_1, + user_pk_1, + [ibet_exchange_contract.address, 10], + ) + STContractUtils.transfer( + other_token_address, + issuer_address, + issuer_private_key, + [ibet_exchange_contract.address, 10], ) - STContractUtils.transfer(other_token_address, issuer_address, issuer_private_key, [user_address_1, 10]) - STContractUtils.transfer(other_token_address, user_address_1, user_pk_1, [ibet_exchange_contract.address, 10]) - STContractUtils.transfer(other_token_address, issuer_address, issuer_private_key, [ibet_exchange_contract.address, 10]) IbetExchangeContractTestUtils.create_order( - ibet_exchange_contract.address, user_address_1, user_pk_1, [other_token_address, 10, 100, False, issuer_address] + ibet_exchange_contract.address, + user_address_1, + user_pk_1, + [other_token_address, 10, 100, False, issuer_address], + ) + latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id( + ibet_exchange_contract.address + ) + IbetExchangeContractTestUtils.execute_order( + ibet_exchange_contract.address, + user_address_2, + user_pk_2, + [latest_order_id, 10, True], + ) + latest_agreement_id = IbetExchangeContractTestUtils.get_latest_agreementid( + ibet_exchange_contract.address, latest_order_id ) - latest_order_id = IbetExchangeContractTestUtils.get_latest_order_id(ibet_exchange_contract.address) - IbetExchangeContractTestUtils.execute_order(ibet_exchange_contract.address, user_address_2, user_pk_2, [latest_order_id, 10, True]) - latest_agreement_id = IbetExchangeContractTestUtils.get_latest_agreementid(ibet_exchange_contract.address, latest_order_id) IbetExchangeContractTestUtils.confirm_agreement( - ibet_exchange_contract.address, issuer_address, issuer_private_key, [latest_order_id, latest_agreement_id] + ibet_exchange_contract.address, + issuer_address, + issuer_private_key, + [latest_order_id, latest_agreement_id], ) db.commit() @@ -613,9 +715,7 @@ def test_normal_5(self, mock_func, processor, db, personal_info_contract, ibet_e _utox_block_number = db.query(UTXOBlockNumber).first() assert _utox_block_number.latest_block_number >= _utox_list[1].block_number - mock_func.assert_has_calls([ - call(token_address=token_address_1, db=ANY) - ]) + mock_func.assert_has_calls([call(token_address=token_address_1, db=ANY)]) # # Additional Issue @@ -624,8 +724,7 @@ def test_normal_6(self, mock_func, processor, db): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] @@ -642,7 +741,9 @@ def test_normal_6(self, mock_func, processor, db): _token_1.abi = {} db.add(_token_1) - token_address_2 = deploy_share_token_contract(issuer_address, issuer_private_key) + token_address_2 = deploy_share_token_contract( + issuer_address, issuer_private_key + ) _token_2 = Token() _token_2.type = TokenType.IBET_SHARE.value _token_2.tx_hash = "" @@ -656,18 +757,20 @@ def test_normal_6(self, mock_func, processor, db): # Execute Issue Event # Share _additional_issue_1 = IbetShareAdditionalIssueParams( - account_address=user_address_1, - amount=70 + account_address=user_address_1, amount=70 + ) + IbetShareContract(token_address_1).additional_issue( + _additional_issue_1, issuer_address, issuer_private_key ) - IbetShareContract(token_address_1).additional_issue(_additional_issue_1, issuer_address, issuer_private_key) time.sleep(1) # Bond _additional_issue_2 = IbetStraightBondAdditionalIssueParams( - account_address=user_address_2, - amount=80 + account_address=user_address_2, amount=80 + ) + IbetStraightBondContract(token_address_2).additional_issue( + _additional_issue_2, issuer_address, issuer_private_key ) - IbetStraightBondContract(token_address_2).additional_issue(_additional_issue_2, issuer_address, issuer_private_key) time.sleep(1) # Execute batch @@ -698,8 +801,7 @@ def test_normal_7(self, mock_func, processor, db): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_1 = user_2["address"] @@ -716,7 +818,9 @@ def test_normal_7(self, mock_func, processor, db): _token_1.abi = {} db.add(_token_1) - token_address_2 = deploy_share_token_contract(issuer_address, issuer_private_key) + token_address_2 = deploy_share_token_contract( + issuer_address, issuer_private_key + ) _token_2 = Token() _token_2.type = TokenType.IBET_SHARE.value _token_2.tx_hash = "" @@ -730,30 +834,34 @@ def test_normal_7(self, mock_func, processor, db): # Execute Issue Event # Share _additional_issue_1 = IbetShareAdditionalIssueParams( - account_address=user_address_1, - amount=10 + account_address=user_address_1, amount=10 + ) + IbetShareContract(token_address_1).additional_issue( + _additional_issue_1, issuer_address, issuer_private_key ) - IbetShareContract(token_address_1).additional_issue(_additional_issue_1, issuer_address, issuer_private_key) time.sleep(1) _additional_issue_2 = IbetShareAdditionalIssueParams( - account_address=user_address_1, - amount=20 + account_address=user_address_1, amount=20 + ) + IbetShareContract(token_address_1).additional_issue( + _additional_issue_2, issuer_address, issuer_private_key ) - IbetShareContract(token_address_1).additional_issue(_additional_issue_2, issuer_address, issuer_private_key) time.sleep(1) # Bond _additional_issue_3 = IbetStraightBondAdditionalIssueParams( - account_address=user_address_2, - amount=30 + account_address=user_address_2, amount=30 + ) + IbetStraightBondContract(token_address_2).additional_issue( + _additional_issue_3, issuer_address, issuer_private_key ) - IbetStraightBondContract(token_address_2).additional_issue(_additional_issue_3, issuer_address, issuer_private_key) time.sleep(1) _additional_issue_4 = IbetStraightBondAdditionalIssueParams( - account_address=user_address_2, - amount=40 + account_address=user_address_2, amount=40 + ) + IbetStraightBondContract(token_address_2).additional_issue( + _additional_issue_4, issuer_address, issuer_private_key ) - IbetStraightBondContract(token_address_2).additional_issue(_additional_issue_4, issuer_address, issuer_private_key) time.sleep(1) # Before execute @@ -783,19 +891,19 @@ def test_normal_7(self, mock_func, processor, db): # Execute Redeem Event # Share - _redeem_1 = IbetShareRedeemParams( - account_address=user_address_1, - amount=20 + _redeem_1 = IbetShareRedeemParams(account_address=user_address_1, amount=20) + IbetShareContract(token_address_1).redeem( + _redeem_1, issuer_address, issuer_private_key ) - IbetShareContract(token_address_1).redeem(_redeem_1, issuer_address, issuer_private_key) time.sleep(1) # Bond _redeem_2 = IbetStraightBondRedeemParams( - account_address=user_address_2, - amount=40 + account_address=user_address_2, amount=40 + ) + IbetStraightBondContract(token_address_2).redeem( + _redeem_2, issuer_address, issuer_private_key ) - IbetStraightBondContract(token_address_2).redeem(_redeem_2, issuer_address, issuer_private_key) time.sleep(1) # Execute batch @@ -836,8 +944,7 @@ def test_error_1(self, processor, db): user_1 = config_eth_account("user1") issuer_address = user_1["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # prepare data @@ -854,7 +961,10 @@ def test_error_1(self, processor, db): # Execute batch latest_block = web3.eth.block_number - with mock.patch("web3.eth.Eth.uninstallFilter", MagicMock(side_effect=Exception("mock test"))) as web3_mock: + with mock.patch( + "web3.eth.Eth.uninstallFilter", + MagicMock(side_effect=Exception("mock test")), + ) as web3_mock: processor.process() _utox_list = db.query(UTXO).all() diff --git a/tests/test_batch_processor_generate_rsa_key.py b/tests/test_batch_processor_generate_rsa_key.py index b3eefa3d..01a6c41d 100644 --- a/tests/test_batch_processor_generate_rsa_key.py +++ b/tests/test_batch_processor_generate_rsa_key.py @@ -16,22 +16,22 @@ SPDX-License-Identifier: Apache-2.0 """ -import pytest from unittest import mock +import pytest + from app.model.db import Account, AccountRsaStatus from app.utils.e2ee_utils import E2EEUtils from batch.processor_generate_rsa_key import Processor from tests.account_config import config_eth_account -@pytest.fixture(scope='function') +@pytest.fixture(scope="function") def processor(db): return Processor() class TestProcessor: - ########################################################################### # Normal Case ########################################################################### @@ -144,8 +144,14 @@ def crypto_publickey_rsa_generate(*args, **kwargs): assert _account.issuer_address == issuer_address_2 assert _account.keyfile == keyfile_2 assert _account.eoa_password == eoa_password_2 - assert _account.rsa_private_key is not None and _account.rsa_private_key != rsa_private_key_2 - assert _account.rsa_public_key is not None and _account.rsa_private_key != rsa_public_key_2 + assert ( + _account.rsa_private_key is not None + and _account.rsa_private_key != rsa_private_key_2 + ) + assert ( + _account.rsa_public_key is not None + and _account.rsa_private_key != rsa_public_key_2 + ) assert _account.rsa_passphrase == rsa_passphrase_2 assert _account.rsa_status == AccountRsaStatus.CHANGING.value # don't change _account = account_after[2] diff --git a/tests/test_batch_processor_modify_personal_info.py b/tests/test_batch_processor_modify_personal_info.py index 58cb59e5..4e81ba60 100644 --- a/tests/test_batch_processor_modify_personal_info.py +++ b/tests/test_batch_processor_modify_personal_info.py @@ -17,41 +17,40 @@ SPDX-License-Identifier: Apache-2.0 """ import pytest - +from eth_keyfile import decode_keyfile_json from web3 import Web3 from web3.middleware import geth_poa_middleware -from eth_keyfile import decode_keyfile_json -from config import ( - WEB3_HTTP_PROVIDER, - CHAIN_ID, - TX_GAS_LIMIT -) from app.model.blockchain import ( - IbetStraightBondContract, IbetShareContract, - PersonalInfoContract + IbetStraightBondContract, + PersonalInfoContract, +) +from app.model.blockchain.tx_params.ibet_share import ( + UpdateParams as IbetShareUpdateParams, +) +from app.model.blockchain.tx_params.ibet_straight_bond import ( + UpdateParams as IbetStraightBondUpdateParams, ) -from app.model.blockchain.tx_params.ibet_straight_bond import UpdateParams as IbetStraightBondUpdateParams -from app.model.blockchain.tx_params.ibet_share import UpdateParams as IbetShareUpdateParams -from app.utils.contract_utils import ContractUtils from app.model.db import ( Account, AccountRsaKeyTemporary, AccountRsaStatus, + IDXPersonalInfo, Token, TokenType, - IDXPersonalInfo ) +from app.utils.contract_utils import ContractUtils from app.utils.e2ee_utils import E2EEUtils from batch.processor_modify_personal_info import Processor +from config import CHAIN_ID, TX_GAS_LIMIT, WEB3_HTTP_PROVIDER from tests.account_config import config_eth_account web3 = Web3(Web3.HTTPProvider(WEB3_HTTP_PROVIDER)) web3.middleware_onion.inject(geth_poa_middleware, layer=0) -@pytest.fixture(scope='function') +@pytest.fixture(scope="function") def processor(db): return Processor() @@ -62,10 +61,11 @@ def deploy_personal_info_contract(issuer_user): eoa_password = "password" private_key = decode_keyfile_json( - raw_keyfile_json=keyfile, - password=eoa_password.encode("utf-8") + raw_keyfile_json=keyfile, password=eoa_password.encode("utf-8") + ) + contract_address, _, _ = ContractUtils.deploy_contract( + "PersonalInfo", [], address, private_key ) - contract_address, _, _ = ContractUtils.deploy_contract("PersonalInfo", [], address, private_key) return contract_address @@ -73,16 +73,18 @@ def set_personal_info_contract(db, contract_address, issuer_address, sender_list contract = ContractUtils.get_contract("PersonalInfo", contract_address) for sender in sender_list: - tx = contract.functions.register(issuer_address, "").build_transaction({ - "nonce": web3.eth.get_transaction_count(sender["user"]["address"]), - "chainId": CHAIN_ID, - "from": sender["user"]["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = contract.functions.register(issuer_address, "").build_transaction( + { + "nonce": web3.eth.get_transaction_count(sender["user"]["address"]), + "chainId": CHAIN_ID, + "from": sender["user"]["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) private_key = decode_keyfile_json( raw_keyfile_json=sender["user"]["keyfile_json"], - password="password".encode("utf-8") + password="password".encode("utf-8"), ) ContractUtils.send_transaction(tx, private_key) @@ -105,12 +107,11 @@ def deploy_bond_token_contract(issuer_user, personal_info_contract_address): 30, "token.return_date", "token.return_amount", - "token.purpose" + "token.purpose", ] private_key = decode_keyfile_json( - raw_keyfile_json=keyfile, - password=eoa_password.encode("utf-8") + raw_keyfile_json=keyfile, password=eoa_password.encode("utf-8") ) bond_contract = IbetStraightBondContract() @@ -138,12 +139,11 @@ def deploy_share_token_contract(issuer_user, personal_info_contract_address): "token.dividend_record_date", "token.dividend_payment_date", "token.cancellation_date", - 10 + 10, ] private_key = decode_keyfile_json( - raw_keyfile_json=keyfile, - password=eoa_password.encode("utf-8") + raw_keyfile_json=keyfile, password=eoa_password.encode("utf-8") ) share_contract = IbetShareContract() @@ -158,7 +158,6 @@ def deploy_share_token_contract(issuer_user, personal_info_contract_address): class TestProcessor: - ########################################################################### # Normal Case ########################################################################### @@ -194,7 +193,9 @@ def test_normal_1(self, processor, db): # token personal_info_contract_address_1 = deploy_personal_info_contract(user_1) - token_contract_address_1 = deploy_bond_token_contract(user_1, personal_info_contract_address_1) + token_contract_address_1 = deploy_bond_token_contract( + user_1, personal_info_contract_address_1 + ) token_1 = Token() token_1.type = TokenType.IBET_STRAIGHT_BOND.value token_1.tx_hash = "tx_hash" @@ -204,7 +205,9 @@ def test_normal_1(self, processor, db): db.add(token_1) personal_info_contract_address_2 = deploy_personal_info_contract(user_1) - token_contract_address_2 = deploy_share_token_contract(user_1, personal_info_contract_address_2) + token_contract_address_2 = deploy_share_token_contract( + user_1, personal_info_contract_address_2 + ) token_2 = Token() token_2.type = TokenType.IBET_SHARE.value token_2.tx_hash = "tx_hash" @@ -264,14 +267,11 @@ def test_normal_1(self, processor, db): "email": "email_user1", "birth": "birth_user1", "is_corporate": False, - "tax_category": 10 - } + "tax_category": 10, + }, }, - { - "user": personal_user_2, - "data": "" - } - ] + {"user": personal_user_2, "data": ""}, + ], ) idx_3 = IDXPersonalInfo() @@ -288,12 +288,10 @@ def test_normal_1(self, processor, db): set_personal_info_contract( db, - personal_info_contract_address_2, user_1["address"], + personal_info_contract_address_2, + user_1["address"], [ - { - "user": personal_user_3, - "data": "" - }, + {"user": personal_user_3, "data": ""}, { "user": personal_user_4, "data": { @@ -304,10 +302,10 @@ def test_normal_1(self, processor, db): "email": "email_user4", "birth": "birth_user4", "is_corporate": True, - "tax_category": 20 - } - } - ] + "tax_category": 20, + }, + }, + ], ) db.commit() @@ -330,8 +328,12 @@ def test_normal_1(self, processor, db): assert temporary.rsa_private_key == user_1["rsa_private_key"] assert temporary.rsa_public_key == user_1["rsa_public_key"] assert temporary.rsa_passphrase == rsa_passphrase - _personal_info_1 = PersonalInfoContract(db, user_1["address"], personal_info_contract_address_1) - assert _personal_info_1.get_info(personal_user_1["address"]) == { # Previous RSA Decrypt + _personal_info_1 = PersonalInfoContract( + db, user_1["address"], personal_info_contract_address_1 + ) + assert _personal_info_1.get_info( + personal_user_1["address"] + ) == { # Previous RSA Decrypt "key_manager": "key_manager_user1", "name": "name_user1", "postal_code": "postal_code_user1", @@ -339,7 +341,7 @@ def test_normal_1(self, processor, db): "email": "email_user1", "birth": "birth_user1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } assert _personal_info_1.get_info(personal_user_2["address"]) == { "key_manager": None, @@ -349,9 +351,11 @@ def test_normal_1(self, processor, db): "email": None, "birth": None, "is_corporate": None, - "tax_category": None + "tax_category": None, } - _personal_info_2 = PersonalInfoContract(db, user_1["address"], personal_info_contract_address_2) + _personal_info_2 = PersonalInfoContract( + db, user_1["address"], personal_info_contract_address_2 + ) assert _personal_info_2.get_info(personal_user_3["address"]) == { "key_manager": None, "name": None, @@ -360,9 +364,11 @@ def test_normal_1(self, processor, db): "email": None, "birth": None, "is_corporate": None, - "tax_category": None + "tax_category": None, } - assert _personal_info_2.get_info(personal_user_4["address"]) == { # Previous RSA Decrypt + assert _personal_info_2.get_info( + personal_user_4["address"] + ) == { # Previous RSA Decrypt "key_manager": "key_manager_user4", "name": "name_user4", "postal_code": "postal_code_user4", @@ -370,7 +376,7 @@ def test_normal_1(self, processor, db): "email": "email_user4", "birth": "birth_user4", "is_corporate": True, - "tax_category": 20 + "tax_category": 20, } # RSA Key Change Completed @@ -400,8 +406,12 @@ def test_normal_1(self, processor, db): assert temporary.rsa_private_key == user_1["rsa_private_key"] assert temporary.rsa_public_key == user_1["rsa_public_key"] assert temporary.rsa_passphrase == rsa_passphrase - _personal_info_1 = PersonalInfoContract(db, user_1["address"], personal_info_contract_address_1) - assert _personal_info_1.get_info(personal_user_1["address"]) == { # New RSA Decrypt + _personal_info_1 = PersonalInfoContract( + db, user_1["address"], personal_info_contract_address_1 + ) + assert _personal_info_1.get_info( + personal_user_1["address"] + ) == { # New RSA Decrypt "key_manager": "key_manager_user1", "name": "name_user1", "postal_code": "postal_code_user1", @@ -409,7 +419,7 @@ def test_normal_1(self, processor, db): "email": "email_user1", "birth": "birth_user1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } assert _personal_info_1.get_info(personal_user_2["address"]) == { "key_manager": None, @@ -419,10 +429,11 @@ def test_normal_1(self, processor, db): "email": None, "birth": None, "is_corporate": None, - "tax_category": None - + "tax_category": None, } - _personal_info_2 = PersonalInfoContract(db, user_1["address"], personal_info_contract_address_2) + _personal_info_2 = PersonalInfoContract( + db, user_1["address"], personal_info_contract_address_2 + ) assert _personal_info_2.get_info(personal_user_3["address"]) == { "key_manager": None, "name": None, @@ -431,9 +442,11 @@ def test_normal_1(self, processor, db): "email": None, "birth": None, "is_corporate": None, - "tax_category": None + "tax_category": None, } - assert _personal_info_2.get_info(personal_user_4["address"]) == { # New RSA Decrypt + assert _personal_info_2.get_info( + personal_user_4["address"] + ) == { # New RSA Decrypt "key_manager": "key_manager_user4", "name": "name_user4", "postal_code": "postal_code_user4", @@ -441,7 +454,7 @@ def test_normal_1(self, processor, db): "email": "email_user4", "birth": "birth_user4", "is_corporate": True, - "tax_category": 20 + "tax_category": 20, } # Execute batch(Run 3rd) @@ -460,8 +473,12 @@ def test_normal_1(self, processor, db): assert _account.rsa_status == AccountRsaStatus.SET.value _temporary_count = db.query(AccountRsaKeyTemporary).count() assert _temporary_count == 0 - _personal_info_1 = PersonalInfoContract(db, user_1["address"], personal_info_contract_address_1) - assert _personal_info_1.get_info(personal_user_1["address"]) == { # New RSA Decrypt + _personal_info_1 = PersonalInfoContract( + db, user_1["address"], personal_info_contract_address_1 + ) + assert _personal_info_1.get_info( + personal_user_1["address"] + ) == { # New RSA Decrypt "key_manager": "key_manager_user1", "name": "name_user1", "postal_code": "postal_code_user1", @@ -469,7 +486,7 @@ def test_normal_1(self, processor, db): "email": "email_user1", "birth": "birth_user1", "is_corporate": False, - "tax_category": 10 + "tax_category": 10, } assert _personal_info_1.get_info(personal_user_2["address"]) == { "key_manager": None, @@ -479,9 +496,11 @@ def test_normal_1(self, processor, db): "email": None, "birth": None, "is_corporate": None, - "tax_category": None + "tax_category": None, } - _personal_info_2 = PersonalInfoContract(db, user_1["address"], personal_info_contract_address_2) + _personal_info_2 = PersonalInfoContract( + db, user_1["address"], personal_info_contract_address_2 + ) assert _personal_info_2.get_info(personal_user_3["address"]) == { "key_manager": None, "name": None, @@ -490,9 +509,11 @@ def test_normal_1(self, processor, db): "email": None, "birth": None, "is_corporate": None, - "tax_category": None + "tax_category": None, } - assert _personal_info_2.get_info(personal_user_4["address"]) == { # New RSA Decrypt + assert _personal_info_2.get_info( + personal_user_4["address"] + ) == { # New RSA Decrypt "key_manager": "key_manager_user4", "name": "name_user4", "postal_code": "postal_code_user4", @@ -500,7 +521,7 @@ def test_normal_1(self, processor, db): "email": "email_user4", "birth": "birth_user4", "is_corporate": True, - "tax_category": 20 + "tax_category": 20, } ########################################################################### diff --git a/tests/test_batch_processor_monitor_block_sync.py b/tests/test_batch_processor_monitor_block_sync.py index 4a9e654e..e10a7cb9 100644 --- a/tests/test_batch_processor_monitor_block_sync.py +++ b/tests/test_batch_processor_monitor_block_sync.py @@ -16,32 +16,28 @@ SPDX-License-Identifier: Apache-2.0 """ -import pytest import time from unittest import mock from unittest.mock import MagicMock +import pytest from web3 import Web3 from web3.middleware import geth_poa_middleware -from config import ( - BLOCK_SYNC_STATUS_SLEEP_INTERVAL, - WEB3_HTTP_PROVIDER -) from app.model.db import Node from batch.processor_monitor_block_sync import Processor +from config import BLOCK_SYNC_STATUS_SLEEP_INTERVAL, WEB3_HTTP_PROVIDER web3 = Web3(Web3.HTTPProvider(WEB3_HTTP_PROVIDER)) web3.middleware_onion.inject(geth_poa_middleware, layer=0) -@pytest.fixture(scope='function') +@pytest.fixture(scope="function") def processor(db): return Processor() class TestProcessor: - ########################################################################### # Normal Case ########################################################################### @@ -66,7 +62,9 @@ def test_normal_1(self, processor, db): time.sleep(BLOCK_SYNC_STATUS_SLEEP_INTERVAL) # Run 2nd: block generation speed down(same the previous) - with mock.patch("batch.processor_monitor_block_sync.BLOCK_GENERATION_SPEED_THRESHOLD", 100): + with mock.patch( + "batch.processor_monitor_block_sync.BLOCK_GENERATION_SPEED_THRESHOLD", 100 + ): processor.process() # assertion @@ -90,10 +88,7 @@ def test_normal_1(self, processor, db): block_number = web3.eth.block_number with mock.patch("web3.eth.BaseEth._is_syncing") as mock_is_syncing: mock_is_syncing.side_effect = [ - { - "highestBlock": block_number, - "currentBlock": block_number - 3 - } + {"highestBlock": block_number, "currentBlock": block_number - 3} ] processor.process() @@ -108,10 +103,7 @@ def test_normal_1(self, processor, db): block_number = web3.eth.block_number with mock.patch("web3.eth.BaseEth._is_syncing") as mock_is_syncing: mock_is_syncing.side_effect = [ - { - "highestBlock": block_number, - "currentBlock": block_number - 2 - } + {"highestBlock": block_number, "currentBlock": block_number - 2} ] processor.process() @@ -122,7 +114,10 @@ def test_normal_1(self, processor, db): # # standby node is down to sync - @mock.patch("batch.processor_monitor_block_sync.WEB3_HTTP_PROVIDER_STANDBY", ["http://test1:1000"]) + @mock.patch( + "batch.processor_monitor_block_sync.WEB3_HTTP_PROVIDER_STANDBY", + ["http://test1:1000"], + ) def test_normal_2(self, db): processor = Processor() @@ -135,10 +130,16 @@ def test_normal_2(self, db): assert _node.is_synced == False # node sync(processing) - org_value = processor.node_info["http://test1:1000"]["web3"].manager.provider.endpoint_uri - processor.node_info["http://test1:1000"]["web3"].manager.provider.endpoint_uri = WEB3_HTTP_PROVIDER + org_value = processor.node_info["http://test1:1000"][ + "web3" + ].manager.provider.endpoint_uri + processor.node_info["http://test1:1000"][ + "web3" + ].manager.provider.endpoint_uri = WEB3_HTTP_PROVIDER processor.process() - processor.node_info["http://test1:1000"]["web3"].manager.provider.endpoint_uri = org_value + processor.node_info["http://test1:1000"][ + "web3" + ].manager.provider.endpoint_uri = org_value # assertion db.rollback() @@ -159,9 +160,11 @@ def test_normal_3(self, db): processor = Processor() # assertion-1 - old_node = db.query(Node).\ - filter(Node.endpoint_uri.not_in(list(WEB3_HTTP_PROVIDER))).\ - all() + old_node = ( + db.query(Node) + .filter(Node.endpoint_uri.not_in(list(WEB3_HTTP_PROVIDER))) + .all() + ) assert len(old_node) == 0 # process @@ -181,9 +184,14 @@ def test_normal_3(self, db): # # node down(initialize) - @mock.patch("batch.processor_monitor_block_sync.WEB3_HTTP_PROVIDER_STANDBY", - ["http://test1:1000", "http://test2:2000"]) - @mock.patch("web3.providers.rpc.HTTPProvider.make_request", MagicMock(side_effect=Exception())) + @mock.patch( + "batch.processor_monitor_block_sync.WEB3_HTTP_PROVIDER_STANDBY", + ["http://test1:1000", "http://test2:2000"], + ) + @mock.patch( + "web3.providers.rpc.HTTPProvider.make_request", + MagicMock(side_effect=Exception()), + ) def test_error_1(self, db): Processor() @@ -221,10 +229,16 @@ def test_error_2(self, processor, db): assert _node.is_synced == True # node down(processing) - org_value = processor.node_info[WEB3_HTTP_PROVIDER]["web3"].manager.provider.endpoint_uri - processor.node_info[WEB3_HTTP_PROVIDER]["web3"].manager.provider.endpoint_uri = "http://hogehoge" + org_value = processor.node_info[WEB3_HTTP_PROVIDER][ + "web3" + ].manager.provider.endpoint_uri + processor.node_info[WEB3_HTTP_PROVIDER][ + "web3" + ].manager.provider.endpoint_uri = "http://hogehoge" processor.process() - processor.node_info[WEB3_HTTP_PROVIDER]["web3"].manager.provider.endpoint_uri = org_value + processor.node_info[WEB3_HTTP_PROVIDER][ + "web3" + ].manager.provider.endpoint_uri = org_value # assertion db.rollback() diff --git a/tests/test_batch_processor_register_personal_info.py b/tests/test_batch_processor_register_personal_info.py index 5e259eed..c396c605 100644 --- a/tests/test_batch_processor_register_personal_info.py +++ b/tests/test_batch_processor_register_personal_info.py @@ -18,28 +18,30 @@ """ import logging from typing import Optional +from unittest.mock import patch + import pytest from eth_keyfile import decode_keyfile_json from sqlalchemy.orm import Session -from unittest.mock import patch +from app.exceptions import ContractRevertError, SendTransactionError from app.model.blockchain import IbetShareContract -from app.model.blockchain.tx_params.ibet_share import UpdateParams as IbetShareUpdateParams +from app.model.blockchain.tx_params.ibet_share import ( + UpdateParams as IbetShareUpdateParams, +) from app.model.db import ( Account, - TokenType, - Notification, - NotificationType, - BatchRegisterPersonalInfoUpload, BatchRegisterPersonalInfo, + BatchRegisterPersonalInfoUpload, BatchRegisterPersonalInfoUploadStatus, - Token + Notification, + NotificationType, + Token, + TokenType, ) from app.utils.contract_utils import ContractUtils from app.utils.e2ee_utils import E2EEUtils -from app.exceptions import SendTransactionError, ContractRevertError -from batch.processor_batch_register_personal_info import Processor, LOG - +from batch.processor_batch_register_personal_info import LOG, Processor from tests.account_config import config_eth_account @@ -58,20 +60,24 @@ class TestProcessor: account_list = [ { "address": config_eth_account("user1")["address"], - "keyfile": config_eth_account("user1")["keyfile_json"] - }, { + "keyfile": config_eth_account("user1")["keyfile_json"], + }, + { "address": config_eth_account("user2")["address"], - "keyfile": config_eth_account("user2")["keyfile_json"] - }, { + "keyfile": config_eth_account("user2")["keyfile_json"], + }, + { "address": config_eth_account("user3")["address"], - "keyfile": config_eth_account("user3")["keyfile_json"] - }, { + "keyfile": config_eth_account("user3")["keyfile_json"], + }, + { "address": config_eth_account("user4")["address"], - "keyfile": config_eth_account("user4")["keyfile_json"] - }, { + "keyfile": config_eth_account("user4")["keyfile_json"], + }, + { "address": config_eth_account("user5")["address"], - "keyfile": config_eth_account("user5")["keyfile_json"] - } + "keyfile": config_eth_account("user5")["keyfile_json"], + }, ] upload_id_list = [ @@ -80,7 +86,7 @@ class TestProcessor: "0f33d48f-9e6e-4a36-a55e-5bbcbda69c80", "1c961f7d-e1ad-40e5-988b-cca3d6009643", "1e778f46-864e-4ec0-b566-21bd31cf63ff", - "1f33d48f-9e6e-4a36-a55e-5bbcbda69c80" + "1f33d48f-9e6e-4a36-a55e-5bbcbda69c80", ] register_personal_info_token = [ @@ -93,11 +99,13 @@ class TestProcessor: ] @staticmethod - def deploy_share_token_contract(address, - private_key, - personal_info_contract_address, - tradable_exchange_contract_address=None, - transfer_approval_required=None): + def deploy_share_token_contract( + address, + private_key, + personal_info_contract_address, + tradable_exchange_contract_address=None, + transfer_approval_required=None, + ): arguments = [ "token.name", "token.symbol", @@ -107,7 +115,7 @@ def deploy_share_token_contract(address, "token.dividend_record_date", "token.dividend_payment_date", "token.cancellation_date", - 30 + 30, ] share_contract = IbetShareContract() token_address, _, _ = share_contract.create(arguments, address, private_key) @@ -116,10 +124,10 @@ def deploy_share_token_contract(address, transferable=True, personal_info_contract_address=personal_info_contract_address, tradable_exchange_contract_address=tradable_exchange_contract_address, - transfer_approval_required=transfer_approval_required + transfer_approval_required=transfer_approval_required, ), tx_from=address, - private_key=private_key + private_key=private_key, ) return ContractUtils.get_contract("IbetShare", token_address) @@ -133,8 +141,7 @@ def deploy_share_token_contract(address, def test_normal_1(self, processor: Processor, db: Session, personal_info_contract): _account = self.account_list[0] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=_account["keyfile"], - password="password".encode("utf-8") + raw_keyfile_json=_account["keyfile"], password="password".encode("utf-8") ) # Prepare data : Account @@ -145,9 +152,9 @@ def test_normal_1(self, processor: Processor, db: Session, personal_info_contrac db.add(account) # Prepare data : Token - token_contract_1 = self.deploy_share_token_contract(_account["address"], - issuer_private_key, - personal_info_contract.address) + token_contract_1 = self.deploy_share_token_contract( + _account["address"], issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_SHARE.value @@ -162,7 +169,7 @@ def test_normal_1(self, processor: Processor, db: Session, personal_info_contrac # mock PersonalInfoContract_register_info = patch( target="app.model.blockchain.personal_info.PersonalInfoContract.register_info", - return_value="mock_tx_hash" + return_value="mock_tx_hash", ) with PersonalInfoContract_register_info as mock: @@ -175,8 +182,7 @@ def test_normal_1(self, processor: Processor, db: Session, personal_info_contrac def test_normal_2(self, processor: Processor, db: Session, personal_info_contract): _account = self.account_list[0] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=_account["keyfile"], - password="password".encode("utf-8") + raw_keyfile_json=_account["keyfile"], password="password".encode("utf-8") ) # Prepare data : Account @@ -187,9 +193,9 @@ def test_normal_2(self, processor: Processor, db: Session, personal_info_contrac db.add(account) # Prepare data : Token - token_contract_1 = self.deploy_share_token_contract(_account["address"], - issuer_private_key, - personal_info_contract.address) + token_contract_1 = self.deploy_share_token_contract( + _account["address"], issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_SHARE.value @@ -205,7 +211,9 @@ def test_normal_2(self, processor: Processor, db: Session, personal_info_contrac batch_register_upload = BatchRegisterPersonalInfoUpload() batch_register_upload.issuer_address = _account["address"] batch_register_upload.upload_id = self.upload_id_list[i] - batch_register_upload.status = [s.value for s in BatchRegisterPersonalInfoUploadStatus][i % 3] + batch_register_upload.status = [ + s.value for s in BatchRegisterPersonalInfoUploadStatus + ][i % 3] db.add(batch_register_upload) # Prepare data : BatchRegisterPersonalInfo @@ -224,7 +232,7 @@ def test_normal_2(self, processor: Processor, db: Session, personal_info_contrac "email": "test_value@a.test", "birth": "19900101", "is_corporate": True, - "tax_category": 3 + "tax_category": 3, } db.add(batch_register) @@ -233,7 +241,7 @@ def test_normal_2(self, processor: Processor, db: Session, personal_info_contrac # mock PersonalInfoContract_register_info = patch( target="app.model.blockchain.personal_info.PersonalInfoContract.register_info", - return_value="mock_tx_hash" + return_value="mock_tx_hash", ) with PersonalInfoContract_register_info: @@ -241,26 +249,42 @@ def test_normal_2(self, processor: Processor, db: Session, personal_info_contrac processor.process() # Assertion - _batch_register_upload_list = db.query(BatchRegisterPersonalInfoUpload). \ - filter(BatchRegisterPersonalInfoUpload.upload_id.in_([self.upload_id_list[0], self.upload_id_list[4]])). \ - all() + _batch_register_upload_list = ( + db.query(BatchRegisterPersonalInfoUpload) + .filter( + BatchRegisterPersonalInfoUpload.upload_id.in_( + [self.upload_id_list[0], self.upload_id_list[4]] + ) + ) + .all() + ) for _upload in _batch_register_upload_list: - assert _upload.status == BatchRegisterPersonalInfoUploadStatus.DONE.value - - _batch_register_list = db.query(BatchRegisterPersonalInfo). \ - filter(BatchRegisterPersonalInfo.upload_id.in_([self.upload_id_list[0], self.upload_id_list[4]])). \ - all() + assert ( + _upload.status == BatchRegisterPersonalInfoUploadStatus.DONE.value + ) + + _batch_register_list = ( + db.query(BatchRegisterPersonalInfo) + .filter( + BatchRegisterPersonalInfo.upload_id.in_( + [self.upload_id_list[0], self.upload_id_list[4]] + ) + ) + .all() + ) for _batch_register in _batch_register_list: assert _batch_register.status == 1 # # Skip other thread processed issuer - @patch("batch.processor_batch_register_personal_info.BATCH_REGISTER_PERSONAL_INFO_WORKER_LOT_SIZE", 2) + @patch( + "batch.processor_batch_register_personal_info.BATCH_REGISTER_PERSONAL_INFO_WORKER_LOT_SIZE", + 2, + ) def test_normal_3(self, processor: Processor, db: Session, personal_info_contract): _account = self.account_list[0] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=_account["keyfile"], - password="password".encode("utf-8") + raw_keyfile_json=_account["keyfile"], password="password".encode("utf-8") ) _other_issuer = self.account_list[1] @@ -272,9 +296,9 @@ def test_normal_3(self, processor: Processor, db: Session, personal_info_contrac db.add(account) # Prepare data : Token - token_contract_1 = self.deploy_share_token_contract(_account["address"], - issuer_private_key, - personal_info_contract.address) + token_contract_1 = self.deploy_share_token_contract( + _account["address"], issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_SHARE.value @@ -288,9 +312,13 @@ def test_normal_3(self, processor: Processor, db: Session, personal_info_contrac # Only record with "pending" status should be processed for i in range(0, 6): batch_register_upload = BatchRegisterPersonalInfoUpload() - batch_register_upload.issuer_address = _account["address"] if i % 3 == 0 else _other_issuer["address"] + batch_register_upload.issuer_address = ( + _account["address"] if i % 3 == 0 else _other_issuer["address"] + ) batch_register_upload.upload_id = self.upload_id_list[i] - batch_register_upload.status = BatchRegisterPersonalInfoUploadStatus.PENDING.value + batch_register_upload.status = ( + BatchRegisterPersonalInfoUploadStatus.PENDING.value + ) db.add(batch_register_upload) # Prepare data : BatchRegisterPersonalInfo @@ -309,7 +337,7 @@ def test_normal_3(self, processor: Processor, db: Session, personal_info_contrac "email": "test_value@a.test", "birth": "19900101", "is_corporate": True, - "tax_category": 3 + "tax_category": 3, } db.add(batch_register) @@ -318,7 +346,7 @@ def test_normal_3(self, processor: Processor, db: Session, personal_info_contrac # mock PersonalInfoContract_register_info = patch( target="app.model.blockchain.personal_info.PersonalInfoContract.register_info", - return_value="mock_tx_hash" + return_value="mock_tx_hash", ) processing_issuer = patch( "batch.processor_batch_register_personal_info.processing_issuer", @@ -327,9 +355,9 @@ def test_normal_3(self, processor: Processor, db: Session, personal_info_contrac self.upload_id_list[1]: _other_issuer["address"], self.upload_id_list[2]: _other_issuer["address"], self.upload_id_list[4]: _other_issuer["address"], - self.upload_id_list[5]: _other_issuer["address"] + self.upload_id_list[5]: _other_issuer["address"], } - } + }, ) with PersonalInfoContract_register_info, processing_issuer: @@ -337,45 +365,83 @@ def test_normal_3(self, processor: Processor, db: Session, personal_info_contrac processor.process() # Assertion - _batch_register_upload_list: list[BatchRegisterPersonalInfoUpload] = db.query(BatchRegisterPersonalInfoUpload). \ - filter(BatchRegisterPersonalInfoUpload.status == BatchRegisterPersonalInfoUploadStatus.DONE.value). \ - order_by(BatchRegisterPersonalInfoUpload.created).all() + _batch_register_upload_list: list[BatchRegisterPersonalInfoUpload] = ( + db.query(BatchRegisterPersonalInfoUpload) + .filter( + BatchRegisterPersonalInfoUpload.status + == BatchRegisterPersonalInfoUploadStatus.DONE.value + ) + .order_by(BatchRegisterPersonalInfoUpload.created) + .all() + ) assert len(_batch_register_upload_list) == 2 assert _batch_register_upload_list[0].issuer_address == _account["address"] assert _batch_register_upload_list[1].issuer_address == _account["address"] - _batch_register_list = db.query(BatchRegisterPersonalInfo). \ - filter(BatchRegisterPersonalInfo.upload_id.in_([r.upload_id for r in _batch_register_upload_list])). \ - all() + _batch_register_list = ( + db.query(BatchRegisterPersonalInfo) + .filter( + BatchRegisterPersonalInfo.upload_id.in_( + [r.upload_id for r in _batch_register_upload_list] + ) + ) + .all() + ) for _batch_register in _batch_register_list: assert _batch_register.status == 1 - _batch_register_upload_list: list[BatchRegisterPersonalInfoUpload] = db.query(BatchRegisterPersonalInfoUpload). \ - filter(BatchRegisterPersonalInfoUpload.status == BatchRegisterPersonalInfoUploadStatus.PENDING.value). \ - order_by(BatchRegisterPersonalInfoUpload.created).all() + _batch_register_upload_list: list[BatchRegisterPersonalInfoUpload] = ( + db.query(BatchRegisterPersonalInfoUpload) + .filter( + BatchRegisterPersonalInfoUpload.status + == BatchRegisterPersonalInfoUploadStatus.PENDING.value + ) + .order_by(BatchRegisterPersonalInfoUpload.created) + .all() + ) assert len(_batch_register_upload_list) == 4 - assert _batch_register_upload_list[0].issuer_address == _other_issuer["address"] - assert _batch_register_upload_list[1].issuer_address == _other_issuer["address"] - assert _batch_register_upload_list[2].issuer_address == _other_issuer["address"] - assert _batch_register_upload_list[3].issuer_address == _other_issuer["address"] + assert ( + _batch_register_upload_list[0].issuer_address + == _other_issuer["address"] + ) + assert ( + _batch_register_upload_list[1].issuer_address + == _other_issuer["address"] + ) + assert ( + _batch_register_upload_list[2].issuer_address + == _other_issuer["address"] + ) + assert ( + _batch_register_upload_list[3].issuer_address + == _other_issuer["address"] + ) - _batch_register_list = db.query(BatchRegisterPersonalInfo). \ - filter(BatchRegisterPersonalInfo.upload_id.in_([r.upload_id for r in _batch_register_upload_list])). \ - all() + _batch_register_list = ( + db.query(BatchRegisterPersonalInfo) + .filter( + BatchRegisterPersonalInfo.upload_id.in_( + [r.upload_id for r in _batch_register_upload_list] + ) + ) + .all() + ) for _batch_register in _batch_register_list: assert _batch_register.status == 0 # # other thread processed issuer(all same issuer) - @patch("batch.processor_batch_register_personal_info.BATCH_REGISTER_PERSONAL_INFO_WORKER_LOT_SIZE", 2) + @patch( + "batch.processor_batch_register_personal_info.BATCH_REGISTER_PERSONAL_INFO_WORKER_LOT_SIZE", + 2, + ) def test_normal_4(self, processor: Processor, db: Session, personal_info_contract): _account = self.account_list[0] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=_account["keyfile"], - password="password".encode("utf-8") + raw_keyfile_json=_account["keyfile"], password="password".encode("utf-8") ) _other_issuer = self.account_list[1] @@ -387,9 +453,9 @@ def test_normal_4(self, processor: Processor, db: Session, personal_info_contrac db.add(account) # Prepare data : Token - token_contract_1 = self.deploy_share_token_contract(_account["address"], - issuer_private_key, - personal_info_contract.address) + token_contract_1 = self.deploy_share_token_contract( + _account["address"], issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_SHARE.value @@ -405,7 +471,9 @@ def test_normal_4(self, processor: Processor, db: Session, personal_info_contrac batch_register_upload = BatchRegisterPersonalInfoUpload() batch_register_upload.issuer_address = _account["address"] batch_register_upload.upload_id = self.upload_id_list[i] - batch_register_upload.status = BatchRegisterPersonalInfoUploadStatus.PENDING.value + batch_register_upload.status = ( + BatchRegisterPersonalInfoUploadStatus.PENDING.value + ) db.add(batch_register_upload) # Prepare data : BatchRegisterPersonalInfo @@ -424,7 +492,7 @@ def test_normal_4(self, processor: Processor, db: Session, personal_info_contrac "email": "test_value@a.test", "birth": "19900101", "is_corporate": True, - "tax_category": 3 + "tax_category": 3, } db.add(batch_register) @@ -433,7 +501,7 @@ def test_normal_4(self, processor: Processor, db: Session, personal_info_contrac # mock PersonalInfoContract_register_info = patch( target="app.model.blockchain.personal_info.PersonalInfoContract.register_info", - return_value="mock_tx_hash" + return_value="mock_tx_hash", ) processing_issuer = patch( "batch.processor_batch_register_personal_info.processing_issuer", @@ -441,9 +509,9 @@ def test_normal_4(self, processor: Processor, db: Session, personal_info_contrac 1: { self.upload_id_list[3]: _account["address"], self.upload_id_list[4]: _account["address"], - self.upload_id_list[5]: _account["address"] + self.upload_id_list[5]: _account["address"], } - } + }, ) with PersonalInfoContract_register_info, processing_issuer: @@ -451,23 +519,41 @@ def test_normal_4(self, processor: Processor, db: Session, personal_info_contrac processor.process() # Assertion - _batch_register_upload_list: list[BatchRegisterPersonalInfoUpload] = db.query(BatchRegisterPersonalInfoUpload). \ - filter(BatchRegisterPersonalInfoUpload.status == BatchRegisterPersonalInfoUploadStatus.DONE.value). \ - order_by(BatchRegisterPersonalInfoUpload.created).all() + _batch_register_upload_list: list[BatchRegisterPersonalInfoUpload] = ( + db.query(BatchRegisterPersonalInfoUpload) + .filter( + BatchRegisterPersonalInfoUpload.status + == BatchRegisterPersonalInfoUploadStatus.DONE.value + ) + .order_by(BatchRegisterPersonalInfoUpload.created) + .all() + ) assert len(_batch_register_upload_list) == 2 assert _batch_register_upload_list[0].issuer_address == _account["address"] assert _batch_register_upload_list[1].issuer_address == _account["address"] - _batch_register_list = db.query(BatchRegisterPersonalInfo). \ - filter(BatchRegisterPersonalInfo.upload_id.in_([r.upload_id for r in _batch_register_upload_list])). \ - all() + _batch_register_list = ( + db.query(BatchRegisterPersonalInfo) + .filter( + BatchRegisterPersonalInfo.upload_id.in_( + [r.upload_id for r in _batch_register_upload_list] + ) + ) + .all() + ) for _batch_register in _batch_register_list: assert _batch_register.status == 1 - _batch_register_upload_list: list[BatchRegisterPersonalInfoUpload] = db.query(BatchRegisterPersonalInfoUpload). \ - filter(BatchRegisterPersonalInfoUpload.status == BatchRegisterPersonalInfoUploadStatus.PENDING.value). \ - order_by(BatchRegisterPersonalInfoUpload.created).all() + _batch_register_upload_list: list[BatchRegisterPersonalInfoUpload] = ( + db.query(BatchRegisterPersonalInfoUpload) + .filter( + BatchRegisterPersonalInfoUpload.status + == BatchRegisterPersonalInfoUploadStatus.PENDING.value + ) + .order_by(BatchRegisterPersonalInfoUpload.created) + .all() + ) assert len(_batch_register_upload_list) == 4 @@ -476,9 +562,15 @@ def test_normal_4(self, processor: Processor, db: Session, personal_info_contrac assert _batch_register_upload_list[2].issuer_address == _account["address"] assert _batch_register_upload_list[3].issuer_address == _account["address"] - _batch_register_list = db.query(BatchRegisterPersonalInfo). \ - filter(BatchRegisterPersonalInfo.upload_id.in_([r.upload_id for r in _batch_register_upload_list[0:3]])). \ - all() + _batch_register_list = ( + db.query(BatchRegisterPersonalInfo) + .filter( + BatchRegisterPersonalInfo.upload_id.in_( + [r.upload_id for r in _batch_register_upload_list[0:3]] + ) + ) + .all() + ) for _batch_register in _batch_register_list: assert _batch_register.status == 0 @@ -488,17 +580,22 @@ def test_normal_4(self, processor: Processor, db: Session, personal_info_contrac # # 1 Batch Task but no issuer - def test_error_1(self, processor: Processor, db: Session, personal_info_contract, caplog: pytest.LogCaptureFixture): + def test_error_1( + self, + processor: Processor, + db: Session, + personal_info_contract, + caplog: pytest.LogCaptureFixture, + ): _account = self.account_list[0] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=_account["keyfile"], - password="password".encode("utf-8") + raw_keyfile_json=_account["keyfile"], password="password".encode("utf-8") ) # Prepare data : Token - token_contract_1 = self.deploy_share_token_contract(_account["address"], - issuer_private_key, - personal_info_contract.address) + token_contract_1 = self.deploy_share_token_contract( + _account["address"], issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_SHARE.value @@ -512,7 +609,9 @@ def test_error_1(self, processor: Processor, db: Session, personal_info_contract batch_register_upload = BatchRegisterPersonalInfoUpload() batch_register_upload.issuer_address = _account["address"] batch_register_upload.upload_id = self.upload_id_list[0] - batch_register_upload.status = BatchRegisterPersonalInfoUploadStatus.PENDING.value + batch_register_upload.status = ( + BatchRegisterPersonalInfoUploadStatus.PENDING.value + ) db.add(batch_register_upload) # Prepare data : BatchRegisterPersonalInfo @@ -529,7 +628,7 @@ def test_error_1(self, processor: Processor, db: Session, personal_info_contract "email": "test_value@a.test", "birth": "19900101", "is_corporate": True, - "tax_category": 3 + "tax_category": 3, } db.add(batch_register) @@ -538,7 +637,7 @@ def test_error_1(self, processor: Processor, db: Session, personal_info_contract # mock PersonalInfoContract_register_info = patch( target="app.model.blockchain.personal_info.PersonalInfoContract.register_info", - return_value="mock_tx_hash" + return_value="mock_tx_hash", ) with PersonalInfoContract_register_info as mock: @@ -547,12 +646,25 @@ def test_error_1(self, processor: Processor, db: Session, personal_info_contract mock.assert_not_called() # Assertion - _batch_register_upload: Optional[BatchRegisterPersonalInfoUpload] = db.query(BatchRegisterPersonalInfoUpload).\ - filter(BatchRegisterPersonalInfoUpload.issuer_address == _account["address"]).first() - assert _batch_register_upload.status == BatchRegisterPersonalInfoUploadStatus.FAILED.value + _batch_register_upload: Optional[BatchRegisterPersonalInfoUpload] = ( + db.query(BatchRegisterPersonalInfoUpload) + .filter( + BatchRegisterPersonalInfoUpload.issuer_address + == _account["address"] + ) + .first() + ) + assert ( + _batch_register_upload.status + == BatchRegisterPersonalInfoUploadStatus.FAILED.value + ) assert 1 == caplog.record_tuples.count( - (LOG.name, logging.WARN, f"Issuer of the upload_id:{_batch_register_upload.upload_id} does not exist") + ( + LOG.name, + logging.WARN, + f"Issuer of the upload_id:{_batch_register_upload.upload_id} does not exist", + ) ) _notification_list = db.query(Notification).all() @@ -560,20 +672,28 @@ def test_error_1(self, processor: Processor, db: Session, personal_info_contract assert _notification.notice_id is not None assert _notification.issuer_address == _account["address"] assert _notification.priority == 1 - assert _notification.type == NotificationType.BATCH_REGISTER_PERSONAL_INFO_ERROR + assert ( + _notification.type + == NotificationType.BATCH_REGISTER_PERSONAL_INFO_ERROR + ) assert _notification.code == 0 assert _notification.metainfo == { "upload_id": batch_register_upload.upload_id, - "error_registration_id": [] + "error_registration_id": [], } # # fail to get the private key - def test_error_2(self, processor: Processor, db: Session, personal_info_contract, caplog: pytest.LogCaptureFixture): + def test_error_2( + self, + processor: Processor, + db: Session, + personal_info_contract, + caplog: pytest.LogCaptureFixture, + ): _account = self.account_list[0] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=_account["keyfile"], - password="password".encode("utf-8") + raw_keyfile_json=_account["keyfile"], password="password".encode("utf-8") ) # Prepare data : Account @@ -584,9 +704,9 @@ def test_error_2(self, processor: Processor, db: Session, personal_info_contract db.add(account) # Prepare data : Token - token_contract_1 = self.deploy_share_token_contract(_account["address"], - issuer_private_key, - personal_info_contract.address) + token_contract_1 = self.deploy_share_token_contract( + _account["address"], issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_SHARE.value @@ -600,7 +720,9 @@ def test_error_2(self, processor: Processor, db: Session, personal_info_contract batch_register_upload = BatchRegisterPersonalInfoUpload() batch_register_upload.issuer_address = _account["address"] batch_register_upload.upload_id = self.upload_id_list[0] - batch_register_upload.status = BatchRegisterPersonalInfoUploadStatus.PENDING.value + batch_register_upload.status = ( + BatchRegisterPersonalInfoUploadStatus.PENDING.value + ) db.add(batch_register_upload) # Prepare data : BatchRegisterPersonalInfo @@ -619,7 +741,7 @@ def test_error_2(self, processor: Processor, db: Session, personal_info_contract "email": "test_value@a.test", "birth": "19900101", "is_corporate": True, - "tax_category": 3 + "tax_category": 3, } db.add(batch_register) batch_register_list.append(batch_register) @@ -629,7 +751,7 @@ def test_error_2(self, processor: Processor, db: Session, personal_info_contract # mock PersonalInfoContract_register_info = patch( target="app.model.blockchain.personal_info.PersonalInfoContract.register_info", - side_effect=SendTransactionError() + side_effect=SendTransactionError(), ) with PersonalInfoContract_register_info: @@ -637,18 +759,39 @@ def test_error_2(self, processor: Processor, db: Session, personal_info_contract processor.process() # Assertion - _batch_register_upload: Optional[BatchRegisterPersonalInfoUpload] = db.query(BatchRegisterPersonalInfoUpload).\ - filter(BatchRegisterPersonalInfoUpload.issuer_address == _account["address"]).first() - assert _batch_register_upload.status == BatchRegisterPersonalInfoUploadStatus.FAILED.value + _batch_register_upload: Optional[BatchRegisterPersonalInfoUpload] = ( + db.query(BatchRegisterPersonalInfoUpload) + .filter( + BatchRegisterPersonalInfoUpload.issuer_address + == _account["address"] + ) + .first() + ) + assert ( + _batch_register_upload.status + == BatchRegisterPersonalInfoUploadStatus.FAILED.value + ) assert 1 == caplog.record_tuples.count( - (LOG.name, logging.WARN, f"Failed to send transaction: id=<{batch_register_list[0].id}>") + ( + LOG.name, + logging.WARN, + f"Failed to send transaction: id=<{batch_register_list[0].id}>", + ) ) assert 1 == caplog.record_tuples.count( - (LOG.name, logging.WARN, f"Failed to send transaction: id=<{batch_register_list[1].id}>") + ( + LOG.name, + logging.WARN, + f"Failed to send transaction: id=<{batch_register_list[1].id}>", + ) ) assert 1 == caplog.record_tuples.count( - (LOG.name, logging.WARN, f"Failed to send transaction: id=<{batch_register_list[2].id}>") + ( + LOG.name, + logging.WARN, + f"Failed to send transaction: id=<{batch_register_list[2].id}>", + ) ) _notification_list = db.query(Notification).all() @@ -656,20 +799,30 @@ def test_error_2(self, processor: Processor, db: Session, personal_info_contract assert _notification.notice_id is not None assert _notification.issuer_address == _account["address"] assert _notification.priority == 1 - assert _notification.type == NotificationType.BATCH_REGISTER_PERSONAL_INFO_ERROR + assert ( + _notification.type + == NotificationType.BATCH_REGISTER_PERSONAL_INFO_ERROR + ) assert _notification.code == 2 assert _notification.metainfo == { "upload_id": batch_register_upload.upload_id, - "error_registration_id": [batch_register.id for batch_register in batch_register_list] + "error_registration_id": [ + batch_register.id for batch_register in batch_register_list + ], } # # ContractRevertError - def test_error_3(self, processor: Processor, db: Session, personal_info_contract, caplog: pytest.LogCaptureFixture): + def test_error_3( + self, + processor: Processor, + db: Session, + personal_info_contract, + caplog: pytest.LogCaptureFixture, + ): _account = self.account_list[0] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=_account["keyfile"], - password="password".encode("utf-8") + raw_keyfile_json=_account["keyfile"], password="password".encode("utf-8") ) # Prepare data : Account @@ -680,9 +833,9 @@ def test_error_3(self, processor: Processor, db: Session, personal_info_contract db.add(account) # Prepare data : Token - token_contract_1 = self.deploy_share_token_contract(_account["address"], - issuer_private_key, - personal_info_contract.address) + token_contract_1 = self.deploy_share_token_contract( + _account["address"], issuer_private_key, personal_info_contract.address + ) token_address_1 = token_contract_1.address token_1 = Token() token_1.type = TokenType.IBET_SHARE.value @@ -696,7 +849,9 @@ def test_error_3(self, processor: Processor, db: Session, personal_info_contract batch_register_upload = BatchRegisterPersonalInfoUpload() batch_register_upload.issuer_address = _account["address"] batch_register_upload.upload_id = self.upload_id_list[0] - batch_register_upload.status = BatchRegisterPersonalInfoUploadStatus.PENDING.value + batch_register_upload.status = ( + BatchRegisterPersonalInfoUploadStatus.PENDING.value + ) db.add(batch_register_upload) # Prepare data : BatchRegisterPersonalInfo @@ -715,7 +870,7 @@ def test_error_3(self, processor: Processor, db: Session, personal_info_contract "email": "test_value@a.test", "birth": "19900101", "is_corporate": True, - "tax_category": 3 + "tax_category": 3, } db.add(batch_register) batch_register_list.append(batch_register) @@ -725,7 +880,7 @@ def test_error_3(self, processor: Processor, db: Session, personal_info_contract # mock PersonalInfoContract_register_info = patch( target="app.model.blockchain.personal_info.PersonalInfoContract.register_info", - side_effect=ContractRevertError("999999") + side_effect=ContractRevertError("999999"), ) with PersonalInfoContract_register_info: @@ -733,18 +888,39 @@ def test_error_3(self, processor: Processor, db: Session, personal_info_contract processor.process() # Assertion - _batch_register_upload: Optional[BatchRegisterPersonalInfoUpload] = db.query(BatchRegisterPersonalInfoUpload).\ - filter(BatchRegisterPersonalInfoUpload.issuer_address == _account["address"]).first() - assert _batch_register_upload.status == BatchRegisterPersonalInfoUploadStatus.FAILED.value + _batch_register_upload: Optional[BatchRegisterPersonalInfoUpload] = ( + db.query(BatchRegisterPersonalInfoUpload) + .filter( + BatchRegisterPersonalInfoUpload.issuer_address + == _account["address"] + ) + .first() + ) + assert ( + _batch_register_upload.status + == BatchRegisterPersonalInfoUploadStatus.FAILED.value + ) assert 1 == caplog.record_tuples.count( - (LOG.name, logging.WARN, f"Transaction reverted: id=<{batch_register_list[0].id}> error_code:<999999> error_msg:<>") + ( + LOG.name, + logging.WARN, + f"Transaction reverted: id=<{batch_register_list[0].id}> error_code:<999999> error_msg:<>", + ) ) assert 1 == caplog.record_tuples.count( - (LOG.name, logging.WARN, f"Transaction reverted: id=<{batch_register_list[1].id}> error_code:<999999> error_msg:<>") + ( + LOG.name, + logging.WARN, + f"Transaction reverted: id=<{batch_register_list[1].id}> error_code:<999999> error_msg:<>", + ) ) assert 1 == caplog.record_tuples.count( - (LOG.name, logging.WARN, f"Transaction reverted: id=<{batch_register_list[2].id}> error_code:<999999> error_msg:<>") + ( + LOG.name, + logging.WARN, + f"Transaction reverted: id=<{batch_register_list[2].id}> error_code:<999999> error_msg:<>", + ) ) _notification_list = db.query(Notification).all() @@ -752,9 +928,14 @@ def test_error_3(self, processor: Processor, db: Session, personal_info_contract assert _notification.notice_id is not None assert _notification.issuer_address == _account["address"] assert _notification.priority == 1 - assert _notification.type == NotificationType.BATCH_REGISTER_PERSONAL_INFO_ERROR + assert ( + _notification.type + == NotificationType.BATCH_REGISTER_PERSONAL_INFO_ERROR + ) assert _notification.code == 2 assert _notification.metainfo == { "upload_id": batch_register_upload.upload_id, - "error_registration_id": [batch_register.id for batch_register in batch_register_list] + "error_registration_id": [ + batch_register.id for batch_register in batch_register_list + ], } diff --git a/tests/test_batch_processor_rotate_e2e_messaging_rsa_key.py b/tests/test_batch_processor_rotate_e2e_messaging_rsa_key.py index 8cae9b5e..3fbf8892 100644 --- a/tests/test_batch_processor_rotate_e2e_messaging_rsa_key.py +++ b/tests/test_batch_processor_rotate_e2e_messaging_rsa_key.py @@ -17,38 +17,30 @@ SPDX-License-Identifier: Apache-2.0 """ import logging -import pytest -from unittest import mock -from unittest.mock import ( - ANY, - call -) import time -from datetime import ( - datetime, - timedelta, - timezone -) +from datetime import datetime, timedelta, timezone +from unittest import mock +from unittest.mock import ANY, call +import pytest from eth_keyfile import decode_keyfile_json from sqlalchemy.orm import Session +import batch.processor_rotate_e2e_messaging_rsa_key as processor_rotate_e2e_messaging_rsa_key +from app.exceptions import ContractRevertError, SendTransactionError from app.model.blockchain import E2EMessaging -from app.model.db import ( - E2EMessagingAccount, - E2EMessagingAccountRsaKey -) +from app.model.db import E2EMessagingAccount, E2EMessagingAccountRsaKey from app.utils.contract_utils import ContractUtils from app.utils.e2ee_utils import E2EEUtils -from app.exceptions import SendTransactionError, ContractRevertError -import batch.processor_rotate_e2e_messaging_rsa_key as processor_rotate_e2e_messaging_rsa_key -from batch.processor_rotate_e2e_messaging_rsa_key import Processor, LOG +from batch.processor_rotate_e2e_messaging_rsa_key import LOG, Processor from tests.account_config import config_eth_account @pytest.fixture(scope="function") def processor(db, e2e_messaging_contract): - processor_rotate_e2e_messaging_rsa_key.E2E_MESSAGING_CONTRACT_ADDRESS = e2e_messaging_contract.address + processor_rotate_e2e_messaging_rsa_key.E2E_MESSAGING_CONTRACT_ADDRESS = ( + e2e_messaging_contract.address + ) log = logging.getLogger("background") default_log_level = LOG.level log.setLevel(logging.DEBUG) @@ -59,7 +51,6 @@ def processor(db, e2e_messaging_contract): class TestProcessor: - ########################################################################### # Normal Case ########################################################################### @@ -82,7 +73,11 @@ def test_normal_1_1(self, processor, db): processor.process() # Assertion - _rsa_key_list = db.query(E2EMessagingAccountRsaKey).order_by(E2EMessagingAccountRsaKey.block_timestamp).all() + _rsa_key_list = ( + db.query(E2EMessagingAccountRsaKey) + .order_by(E2EMessagingAccountRsaKey.block_timestamp) + .all() + ) assert len(_rsa_key_list) == 0 # @@ -114,7 +109,11 @@ def test_normal_1_2(self, processor, db): processor.process() # Assertion - _rsa_key_list = db.query(E2EMessagingAccountRsaKey).order_by(E2EMessagingAccountRsaKey.block_timestamp).all() + _rsa_key_list = ( + db.query(E2EMessagingAccountRsaKey) + .order_by(E2EMessagingAccountRsaKey.block_timestamp) + .all() + ) assert len(_rsa_key_list) == 1 _rsa_key = _rsa_key_list[0] assert _rsa_key.id == 1 @@ -154,7 +153,11 @@ def test_normal_1_3(self, processor, db): processor.process() # Assertion - _rsa_key_list = db.query(E2EMessagingAccountRsaKey).order_by(E2EMessagingAccountRsaKey.block_timestamp).all() + _rsa_key_list = ( + db.query(E2EMessagingAccountRsaKey) + .order_by(E2EMessagingAccountRsaKey.block_timestamp) + .all() + ) assert len(_rsa_key_list) == 1 _rsa_key = _rsa_key_list[0] assert _rsa_key.id == 1 @@ -172,15 +175,13 @@ def test_normal_2(self, processor, db, e2e_messaging_contract): user_address_1 = user_1["address"] user_keyfile_1 = user_1["keyfile_json"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_2 = user_2["address"] user_keyfile_2 = user_2["keyfile_json"] user_private_key_2 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : E2EMessagingAccount @@ -252,46 +253,63 @@ def test_normal_2(self, processor, db, e2e_messaging_contract): # mock mock_E2EMessaging_set_public_key = mock.patch( target="app.model.blockchain.e2e_messaging.E2EMessaging.set_public_key", - side_effect=[("tx_5", {"blockNumber": 12345}), ("tx_6", {"blockNumber": 12350})] + side_effect=[ + ("tx_5", {"blockNumber": 12345}), + ("tx_6", {"blockNumber": 12350}), + ], ) mock_ContractUtils_get_block_by_transaction_hash = mock.patch( target="app.utils.contract_utils.ContractUtils.get_block_by_transaction_hash", side_effect=[ { "number": 12345, - "timestamp": datetime(2099, 4, 27, 12, 34, 56, tzinfo=timezone.utc).timestamp() + "timestamp": datetime( + 2099, 4, 27, 12, 34, 56, tzinfo=timezone.utc + ).timestamp(), }, { "number": 12350, - "timestamp": datetime(2099, 4, 27, 12, 34, 59, tzinfo=timezone.utc).timestamp() - } - ] + "timestamp": datetime( + 2099, 4, 27, 12, 34, 59, tzinfo=timezone.utc + ).timestamp(), + }, + ], ) # Run target process - with mock_E2EMessaging_set_public_key, mock_ContractUtils_get_block_by_transaction_hash: + with ( + mock_E2EMessaging_set_public_key + ), mock_ContractUtils_get_block_by_transaction_hash: processor.process() # # Assertion assert user_address_2 < user_address_1 - E2EMessaging.set_public_key.assert_has_calls([ - call(public_key=ANY, - key_type="RSA4096", - tx_from=user_address_2, - private_key=user_private_key_2), - call(public_key=ANY, - key_type="RSA4096", - tx_from=user_address_1, - private_key=user_private_key_1), - ]) + E2EMessaging.set_public_key.assert_has_calls( + [ + call( + public_key=ANY, + key_type="RSA4096", + tx_from=user_address_2, + private_key=user_private_key_2, + ), + call( + public_key=ANY, + key_type="RSA4096", + tx_from=user_address_1, + private_key=user_private_key_1, + ), + ] + ) ContractUtils.get_block_by_transaction_hash.assert_has_calls( [call(tx_hash="tx_5"), call(tx_hash="tx_6")] ) - _rsa_key_list = db.query(E2EMessagingAccountRsaKey). \ - filter(E2EMessagingAccountRsaKey.account_address == user_address_1). \ - order_by(E2EMessagingAccountRsaKey.block_timestamp). \ - all() + _rsa_key_list = ( + db.query(E2EMessagingAccountRsaKey) + .filter(E2EMessagingAccountRsaKey.account_address == user_address_1) + .order_by(E2EMessagingAccountRsaKey.block_timestamp) + .all() + ) assert len(_rsa_key_list) == 2 _rsa_key = _rsa_key_list[0] assert _rsa_key.id == 3 @@ -311,10 +329,12 @@ def test_normal_2(self, processor, db, e2e_messaging_contract): assert _rsa_key.rsa_public_key == ANY assert E2EEUtils.decrypt(_rsa_key.rsa_passphrase) == "latest_passphrase_1" assert _rsa_key.block_timestamp == datetime(2099, 4, 27, 12, 34, 59) - _rsa_key_list = db.query(E2EMessagingAccountRsaKey). \ - filter(E2EMessagingAccountRsaKey.account_address == user_address_2). \ - order_by(E2EMessagingAccountRsaKey.block_timestamp). \ - all() + _rsa_key_list = ( + db.query(E2EMessagingAccountRsaKey) + .filter(E2EMessagingAccountRsaKey.account_address == user_address_2) + .order_by(E2EMessagingAccountRsaKey.block_timestamp) + .all() + ) assert len(_rsa_key_list) == 2 _rsa_key = _rsa_key_list[0] assert _rsa_key.id == 4 @@ -374,7 +394,11 @@ def test_error_1(self, processor, db): processor.process() # Assertion - _rsa_key_list = db.query(E2EMessagingAccountRsaKey).order_by(E2EMessagingAccountRsaKey.block_timestamp).all() + _rsa_key_list = ( + db.query(E2EMessagingAccountRsaKey) + .order_by(E2EMessagingAccountRsaKey.block_timestamp) + .all() + ) # # Failed to send transaction @@ -383,8 +407,7 @@ def test_error_2(self, processor, db, e2e_messaging_contract): user_address_1 = user_1["address"] user_keyfile_1 = user_1["keyfile_json"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : E2EMessagingAccount @@ -414,7 +437,7 @@ def test_error_2(self, processor, db, e2e_messaging_contract): # mock mock_E2EMessaging_set_public_key = mock.patch( target="app.model.blockchain.e2e_messaging.E2EMessaging.set_public_key", - side_effect=SendTransactionError() + side_effect=SendTransactionError(), ) # Run target process @@ -426,21 +449,30 @@ def test_error_2(self, processor, db, e2e_messaging_contract): public_key=ANY, key_type="RSA4096", tx_from=user_address_1, - private_key=user_private_key_1 + private_key=user_private_key_1, ) - _rsa_key_list = db.query(E2EMessagingAccountRsaKey).order_by(E2EMessagingAccountRsaKey.block_timestamp).all() + _rsa_key_list = ( + db.query(E2EMessagingAccountRsaKey) + .order_by(E2EMessagingAccountRsaKey.block_timestamp) + .all() + ) assert len(_rsa_key_list) == 1 # # ContractRevertError - def test_error_3(self, processor: Processor, db: Session, e2e_messaging_contract, caplog: pytest.LogCaptureFixture): + def test_error_3( + self, + processor: Processor, + db: Session, + e2e_messaging_contract, + caplog: pytest.LogCaptureFixture, + ): user_1 = config_eth_account("user1") user_address_1 = user_1["address"] user_keyfile_1 = user_1["keyfile_json"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) # Prepare data : E2EMessagingAccount @@ -470,7 +502,7 @@ def test_error_3(self, processor: Processor, db: Session, e2e_messaging_contract # mock mock_E2EMessaging_set_public_key = mock.patch( target="app.model.blockchain.e2e_messaging.E2EMessaging.set_public_key", - side_effect=ContractRevertError("999999") + side_effect=ContractRevertError("999999"), ) # Run target process @@ -482,13 +514,22 @@ def test_error_3(self, processor: Processor, db: Session, e2e_messaging_contract public_key=ANY, key_type="RSA4096", tx_from=user_address_1, - private_key=user_private_key_1 + private_key=user_private_key_1, ) - _rsa_key_list = db.query(E2EMessagingAccountRsaKey).order_by(E2EMessagingAccountRsaKey.block_timestamp).all() + _rsa_key_list = ( + db.query(E2EMessagingAccountRsaKey) + .order_by(E2EMessagingAccountRsaKey.block_timestamp) + .all() + ) assert len(_rsa_key_list) == 1 - assert caplog.record_tuples.count(( - LOG.name, - logging.WARNING, - f"Transaction reverted: account_address=<{user_address_1}> error_code:<999999> error_msg:<>" - )) == 1 + assert ( + caplog.record_tuples.count( + ( + LOG.name, + logging.WARNING, + f"Transaction reverted: account_address=<{user_address_1}> error_code:<999999> error_msg:<>", + ) + ) + == 1 + ) diff --git a/tests/test_batch_processor_scheduled_events.py b/tests/test_batch_processor_scheduled_events.py index 8492ebf1..282fb45e 100644 --- a/tests/test_batch_processor_scheduled_events.py +++ b/tests/test_batch_processor_scheduled_events.py @@ -17,28 +17,22 @@ SPDX-License-Identifier: Apache-2.0 """ import logging -import pytest +from datetime import datetime, timedelta, timezone from unittest.mock import patch -from datetime import ( - datetime, - timedelta, - timezone -) + +import pytest + +from app.exceptions import ContractRevertError, SendTransactionError from app.model.db import ( Account, + Notification, + NotificationType, ScheduledEvents, ScheduledEventType, TokenType, - Notification, - NotificationType ) from app.utils.e2ee_utils import E2EEUtils -from app.exceptions import ( - SendTransactionError, - ContractRevertError -) -from batch.processor_scheduled_events import Processor, LOG - +from batch.processor_scheduled_events import LOG, Processor from tests.account_config import config_eth_account @@ -54,7 +48,6 @@ def processor(db): class TestProcessor: - ########################################################################### # Normal Case ########################################################################### @@ -93,7 +86,7 @@ def test_normal_1_1(self, processor, db): "image_url": [ "http://sampleurl.com/some_image1.png", "http://sampleurl.com/some_image2.png", - "http://sampleurl.com/some_image3.png" + "http://sampleurl.com/some_image3.png", ], "status": False, "is_offering": False, @@ -102,7 +95,7 @@ def test_normal_1_1(self, processor, db): "personal_info_contract_address": "0xa4CEe3b909751204AA151860ebBE8E7A851c2A1a", "contact_information": "問い合わせ先test", "privacy_policy": "プライバシーポリシーtest", - "is_canceled": False + "is_canceled": False, } # TokenType: STRAIGHT_BOND, status is 2, will not change @@ -143,7 +136,7 @@ def test_normal_1_1(self, processor, db): # mock IbetStraightBondContract_update = patch( target="app.model.blockchain.token.IbetStraightBondContract.update", - return_value=None + return_value=None, ) with IbetStraightBondContract_update: @@ -151,17 +144,23 @@ def test_normal_1_1(self, processor, db): processor.process() # Assertion - _scheduled_event = db.query(ScheduledEvents). \ - filter(ScheduledEvents.token_address == _token_address_1). \ - first() + _scheduled_event = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.token_address == _token_address_1) + .first() + ) assert _scheduled_event.status == 2 - _scheduled_event = db.query(ScheduledEvents). \ - filter(ScheduledEvents.token_address == _token_address_2). \ - first() + _scheduled_event = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.token_address == _token_address_2) + .first() + ) assert _scheduled_event.status == 1 - _scheduled_event = db.query(ScheduledEvents). \ - filter(ScheduledEvents.token_address == _token_address_3). \ - first() + _scheduled_event = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.token_address == _token_address_3) + .first() + ) assert _scheduled_event.status == 0 # @@ -198,7 +197,7 @@ def test_normal_1_2(self, processor, db): "image_url": [ "http://sampleurl.com/some_image1.png", "http://sampleurl.com/some_image2.png", - "http://sampleurl.com/some_image3.png" + "http://sampleurl.com/some_image3.png", ], "status": False, "is_offering": False, @@ -248,7 +247,7 @@ def test_normal_1_2(self, processor, db): # mock IbetStraightBondContract_update = patch( target="app.model.blockchain.token.IbetStraightBondContract.update", - return_value=None + return_value=None, ) with IbetStraightBondContract_update: @@ -256,17 +255,23 @@ def test_normal_1_2(self, processor, db): processor.process() # Assertion - _scheduled_event = db.query(ScheduledEvents). \ - filter(ScheduledEvents.token_address == _token_address_1). \ - first() + _scheduled_event = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.token_address == _token_address_1) + .first() + ) assert _scheduled_event.status == 2 - _scheduled_event = db.query(ScheduledEvents). \ - filter(ScheduledEvents.token_address == _token_address_2). \ - first() + _scheduled_event = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.token_address == _token_address_2) + .first() + ) assert _scheduled_event.status == 1 - _scheduled_event = db.query(ScheduledEvents). \ - filter(ScheduledEvents.token_address == _token_address_3). \ - first() + _scheduled_event = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.token_address == _token_address_3) + .first() + ) assert _scheduled_event.status == 0 # @@ -305,14 +310,14 @@ def test_normal_2_1(self, processor, db): "image_url": [ "http://sampleurl.com/some_image1.png", "http://sampleurl.com/some_image2.png", - "http://sampleurl.com/some_image3.png" + "http://sampleurl.com/some_image3.png", ], "transferable": False, "status": False, "is_offering": False, "contact_information": "問い合わせ先test", "privacy_policy": "プライバシーポリシーtest", - "is_canceled": False + "is_canceled": False, } # TokenType: STRAIGHT_BOND, status is 2, will not change @@ -353,7 +358,7 @@ def test_normal_2_1(self, processor, db): # mock IbetShareContract_update = patch( target="app.model.blockchain.token.IbetShareContract.update", - return_value=None + return_value=None, ) with IbetShareContract_update: @@ -361,17 +366,23 @@ def test_normal_2_1(self, processor, db): processor.process() # Assertion - _scheduled_event = db.query(ScheduledEvents). \ - filter(ScheduledEvents.token_address == _token_address_1). \ - first() + _scheduled_event = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.token_address == _token_address_1) + .first() + ) assert _scheduled_event.status == 2 - _scheduled_event = db.query(ScheduledEvents). \ - filter(ScheduledEvents.token_address == _token_address_2). \ - first() + _scheduled_event = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.token_address == _token_address_2) + .first() + ) assert _scheduled_event.status == 1 - _scheduled_event = db.query(ScheduledEvents). \ - filter(ScheduledEvents.token_address == _token_address_3). \ - first() + _scheduled_event = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.token_address == _token_address_3) + .first() + ) assert _scheduled_event.status == 0 # @@ -410,7 +421,7 @@ def test_normal_2_2(self, processor, db): "image_url": [ "http://sampleurl.com/some_image1.png", "http://sampleurl.com/some_image2.png", - "http://sampleurl.com/some_image3.png" + "http://sampleurl.com/some_image3.png", ], "transferable": False, "status": False, @@ -458,7 +469,7 @@ def test_normal_2_2(self, processor, db): # mock IbetShareContract_update = patch( target="app.model.blockchain.token.IbetShareContract.update", - return_value=None + return_value=None, ) with IbetShareContract_update: @@ -466,17 +477,23 @@ def test_normal_2_2(self, processor, db): processor.process() # Assertion - _scheduled_event = db.query(ScheduledEvents). \ - filter(ScheduledEvents.token_address == _token_address_1). \ - first() + _scheduled_event = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.token_address == _token_address_1) + .first() + ) assert _scheduled_event.status == 2 - _scheduled_event = db.query(ScheduledEvents). \ - filter(ScheduledEvents.token_address == _token_address_2). \ - first() + _scheduled_event = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.token_address == _token_address_2) + .first() + ) assert _scheduled_event.status == 1 - _scheduled_event = db.query(ScheduledEvents). \ - filter(ScheduledEvents.token_address == _token_address_3). \ - first() + _scheduled_event = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.token_address == _token_address_3) + .first() + ) assert _scheduled_event.status == 0 ########################################################################### @@ -513,9 +530,11 @@ def test_error_1(self, processor, db): processor.process() # Assertion - _scheduled_event = db.query(ScheduledEvents). \ - filter(ScheduledEvents.token_address == _token_address). \ - first() + _scheduled_event = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.token_address == _token_address) + .first() + ) assert _scheduled_event.status == 2 _notification = db.query(Notification).first() assert _notification.id == 1 @@ -527,7 +546,7 @@ def test_error_1(self, processor, db): assert _notification.metainfo == { "scheduled_event_id": "event_id_1", "token_type": TokenType.IBET_STRAIGHT_BOND.value, - "token_address": _token_address + "token_address": _token_address, } # @@ -566,9 +585,11 @@ def test_error_2(self, processor, db): processor.process() # Assertion - _scheduled_event = db.query(ScheduledEvents). \ - filter(ScheduledEvents.token_address == _token_address). \ - first() + _scheduled_event = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.token_address == _token_address) + .first() + ) assert _scheduled_event.status == 2 _notification = db.query(Notification).first() assert _notification.id == 1 @@ -580,7 +601,7 @@ def test_error_2(self, processor, db): assert _notification.metainfo == { "scheduled_event_id": "event_id_1", "token_type": TokenType.IBET_SHARE.value, - "token_address": _token_address + "token_address": _token_address, } # @@ -601,8 +622,7 @@ def test_error_3(self, processor, db): # prepare data : ScheduledEvents datetime_now_utc = datetime.now(timezone.utc) datetime_now_str = datetime_now_utc.isoformat() - update_data = { - } + update_data = {} # TokenType: STRAIGHT_BOND, status will be "2: Failed" token_event = ScheduledEvents() @@ -621,7 +641,7 @@ def test_error_3(self, processor, db): # mock IbetStraightBondContract_update = patch( target="app.model.blockchain.token.IbetStraightBondContract.update", - side_effect=SendTransactionError() + side_effect=SendTransactionError(), ) with IbetStraightBondContract_update: @@ -629,9 +649,11 @@ def test_error_3(self, processor, db): processor.process() # Assertion - _scheduled_event = db.query(ScheduledEvents). \ - filter(ScheduledEvents.token_address == _token_address). \ - first() + _scheduled_event = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.token_address == _token_address) + .first() + ) assert _scheduled_event.status == 2 _notification = db.query(Notification).first() assert _notification.id == 1 @@ -643,7 +665,7 @@ def test_error_3(self, processor, db): assert _notification.metainfo == { "scheduled_event_id": "event_id_1", "token_type": TokenType.IBET_STRAIGHT_BOND.value, - "token_address": _token_address + "token_address": _token_address, } # @@ -665,8 +687,7 @@ def test_error_4(self, processor, db): datetime_now_jtc = datetime.now(timezone.utc) datetime_now_str = datetime_now_jtc.isoformat() - update_data = { - } + update_data = {} # TokenType: STRAIGHT_BOND, status will be "2: Failed" token_event = ScheduledEvents() @@ -685,7 +706,7 @@ def test_error_4(self, processor, db): # mock IbetShareContract_update = patch( target="app.model.blockchain.token.IbetShareContract.update", - side_effect=SendTransactionError() + side_effect=SendTransactionError(), ) with IbetShareContract_update: @@ -693,9 +714,11 @@ def test_error_4(self, processor, db): processor.process() # Assertion - _scheduled_event = db.query(ScheduledEvents). \ - filter(ScheduledEvents.token_address == _token_address). \ - first() + _scheduled_event = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.token_address == _token_address) + .first() + ) assert _scheduled_event.status == 2 _notification = db.query(Notification).first() assert _notification.id == 1 @@ -707,7 +730,7 @@ def test_error_4(self, processor, db): assert _notification.metainfo == { "scheduled_event_id": "event_id_1", "token_type": TokenType.IBET_SHARE.value, - "token_address": _token_address + "token_address": _token_address, } # @@ -728,8 +751,7 @@ def test_error_5(self, processor, db, caplog): # prepare data : ScheduledEvents datetime_now_utc = datetime.now(timezone.utc) datetime_now_str = datetime_now_utc.isoformat() - update_data = { - } + update_data = {} # TokenType: STRAIGHT_BOND, status will be "2: Failed" token_event = ScheduledEvents() @@ -748,7 +770,7 @@ def test_error_5(self, processor, db, caplog): # mock IbetStraightBondContract_update = patch( target="app.model.blockchain.token.IbetStraightBondContract.update", - side_effect=ContractRevertError("999999") + side_effect=ContractRevertError("999999"), ) with IbetStraightBondContract_update: @@ -756,9 +778,11 @@ def test_error_5(self, processor, db, caplog): processor.process() # Assertion - _scheduled_event = db.query(ScheduledEvents). \ - filter(ScheduledEvents.token_address == _token_address). \ - first() + _scheduled_event = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.token_address == _token_address) + .first() + ) assert _scheduled_event.status == 2 _notification = db.query(Notification).first() assert _notification.id == 1 @@ -770,13 +794,18 @@ def test_error_5(self, processor, db, caplog): assert _notification.metainfo == { "scheduled_event_id": "event_id_1", "token_type": TokenType.IBET_STRAIGHT_BOND.value, - "token_address": _token_address + "token_address": _token_address, } - assert caplog.record_tuples.count(( - LOG.name, - logging.WARNING, - f"Transaction reverted: id=<{token_event.id}> error_code:<999999> error_msg:<>" - )) == 1 + assert ( + caplog.record_tuples.count( + ( + LOG.name, + logging.WARNING, + f"Transaction reverted: id=<{token_event.id}> error_code:<999999> error_msg:<>", + ) + ) + == 1 + ) # # IbetShare : ContractRevertError @@ -797,8 +826,7 @@ def test_error_6(self, processor, db, caplog): datetime_now_jtc = datetime.now(timezone.utc) datetime_now_str = datetime_now_jtc.isoformat() - update_data = { - } + update_data = {} # TokenType: STRAIGHT_BOND, status will be "2: Failed" token_event = ScheduledEvents() @@ -817,7 +845,7 @@ def test_error_6(self, processor, db, caplog): # mock IbetShareContract_update = patch( target="app.model.blockchain.token.IbetShareContract.update", - side_effect=ContractRevertError("999999") + side_effect=ContractRevertError("999999"), ) with IbetShareContract_update: @@ -825,9 +853,11 @@ def test_error_6(self, processor, db, caplog): processor.process() # Assertion - _scheduled_event = db.query(ScheduledEvents). \ - filter(ScheduledEvents.token_address == _token_address). \ - first() + _scheduled_event = ( + db.query(ScheduledEvents) + .filter(ScheduledEvents.token_address == _token_address) + .first() + ) assert _scheduled_event.status == 2 _notification = db.query(Notification).first() assert _notification.id == 1 @@ -839,11 +869,16 @@ def test_error_6(self, processor, db, caplog): assert _notification.metainfo == { "scheduled_event_id": "event_id_1", "token_type": TokenType.IBET_SHARE.value, - "token_address": _token_address + "token_address": _token_address, } - assert caplog.record_tuples.count(( - LOG.name, - logging.WARNING, - f"Transaction reverted: id=<{token_event.id}> error_code:<999999> error_msg:<>" - )) == 1 + assert ( + caplog.record_tuples.count( + ( + LOG.name, + logging.WARNING, + f"Transaction reverted: id=<{token_event.id}> error_code:<999999> error_msg:<>", + ) + ) + == 1 + ) diff --git a/tests/test_batch_processor_update_token.py b/tests/test_batch_processor_update_token.py index 828be571..439c2a8c 100644 --- a/tests/test_batch_processor_update_token.py +++ b/tests/test_batch_processor_update_token.py @@ -16,35 +16,26 @@ SPDX-License-Identifier: Apache-2.0 """ +from datetime import datetime, timezone +from unittest.mock import ANY, call, patch + import pytest -from unittest.mock import ( - patch, - ANY, - call -) -from datetime import ( - datetime, - timezone -) -from config import TOKEN_LIST_CONTRACT_ADDRESS -from app.model.schema import ( - IbetShareUpdate, - IbetStraightBondUpdate -) +from app.exceptions import SendTransactionError from app.model.db import ( + UTXO, Account, - Token, - TokenType, - UpdateToken, IDXPosition, Notification, NotificationType, - UTXO + Token, + TokenType, + UpdateToken, ) +from app.model.schema import IbetShareUpdate, IbetStraightBondUpdate from app.utils.e2ee_utils import E2EEUtils -from app.exceptions import SendTransactionError from batch.processor_update_token import Processor +from config import TOKEN_LIST_CONTRACT_ADDRESS from tests.account_config import config_eth_account @@ -54,7 +45,6 @@ def processor(db): class TestProcessor: - ########################################################################### # Normal Case ########################################################################### @@ -108,7 +98,7 @@ def test_normal_1(self, processor, db): "privacy_policy": "privacy policy test", # update "transfer_approval_required": True, # update "principal_value": 1000, - "is_canceled": True # update + "is_canceled": True, # update } _update_token_1.status = 0 _update_token_1.trigger = "Issue" @@ -177,16 +167,23 @@ def test_normal_1(self, processor, db): mock_block = { "number": 12345, - "timestamp": datetime(2021, 4, 27, 12, 34, 56, tzinfo=timezone.utc).timestamp() + "timestamp": datetime( + 2021, 4, 27, 12, 34, 56, tzinfo=timezone.utc + ).timestamp(), } - with patch(target="app.model.blockchain.token.IbetShareContract.update", - return_value=None) as IbetShareContract_update, \ - patch(target="app.model.blockchain.token.IbetStraightBondContract.update", - return_value=None) as IbetStraightBondContract_update, \ - patch(target="app.model.blockchain.token_list.TokenListContract.register", - return_value=None) as TokenListContract_register, \ - patch(target="app.utils.contract_utils.ContractUtils.get_block_by_transaction_hash", - return_value=mock_block) as ContractUtils_get_block_by_transaction_hash: + with patch( + target="app.model.blockchain.token.IbetShareContract.update", + return_value=None, + ) as IbetShareContract_update, patch( + target="app.model.blockchain.token.IbetStraightBondContract.update", + return_value=None, + ) as IbetStraightBondContract_update, patch( + target="app.model.blockchain.token_list.TokenListContract.register", + return_value=None, + ) as TokenListContract_register, patch( + target="app.utils.contract_utils.ContractUtils.get_block_by_transaction_hash", + return_value=mock_block, + ) as ContractUtils_get_block_by_transaction_hash: # Execute batch processor.process() @@ -205,10 +202,10 @@ def test_normal_1(self, processor, db): contact_information="contact info test", privacy_policy="privacy policy test", transfer_approval_required=True, - is_canceled=True + is_canceled=True, ), tx_from=_issuer_address, - private_key=ANY + private_key=ANY, ) IbetStraightBondContract_update.assert_called_with( @@ -223,27 +220,35 @@ def test_normal_1(self, processor, db): personal_info_contract_address="0x0000000000000000000000000000000000000002", contact_information="contact info test", privacy_policy="privacy policy test", - transfer_approval_required=True + transfer_approval_required=True, ), tx_from=_issuer_address, - private_key=ANY + private_key=ANY, + ) + + TokenListContract_register.assert_has_calls( + [ + call( + token_address=_token_address_1, + token_template=TokenType.IBET_SHARE.value, + tx_from=_issuer_address, + private_key=ANY, + ), + call( + token_address=_token_address_2, + token_template=TokenType.IBET_STRAIGHT_BOND.value, + tx_from=_issuer_address, + private_key=ANY, + ), + ] ) - TokenListContract_register.assert_has_calls([ - call(token_address=_token_address_1, - token_template=TokenType.IBET_SHARE.value, - tx_from=_issuer_address, - private_key=ANY), - call(token_address=_token_address_2, - token_template=TokenType.IBET_STRAIGHT_BOND.value, - tx_from=_issuer_address, - private_key=ANY), - ]) - - ContractUtils_get_block_by_transaction_hash.assert_has_calls([ - call("tx_hash_1"), - call("tx_hash_2"), - ]) + ContractUtils_get_block_by_transaction_hash.assert_has_calls( + [ + call("tx_hash_1"), + call("tx_hash_2"), + ] + ) # assertion(DB) _idx_position_list = db.query(IDXPosition).order_by(IDXPosition.id).all() @@ -351,7 +356,7 @@ def test_error_1(self, processor, db): "privacy_policy": "privacy policy test", # update "transfer_approval_required": True, # update "principal_value": 1000, - "is_canceled": True # update + "is_canceled": True, # update } _update_token_1.status = 0 _update_token_1.trigger = "Issue" @@ -473,8 +478,8 @@ def test_error_1(self, processor, db): "privacy_policy": "privacy policy test", # update "transfer_approval_required": True, # update "principal_value": 1000, - "is_canceled": True # update - } + "is_canceled": True, # update + }, } _notification = _notification_list[1] assert _notification.id == 2 @@ -507,7 +512,7 @@ def test_error_1(self, processor, db): "contact_information": "contact info test", # update "privacy_policy": "privacy policy test", # update "transfer_approval_required": True, # update - } + }, } # @@ -559,7 +564,7 @@ def test_error_2(self, processor, db): "privacy_policy": "privacy policy test", # update "transfer_approval_required": True, # update "principal_value": 1000, - "is_canceled": True # update + "is_canceled": True, # update } _update_token_1.status = 0 _update_token_1.trigger = "Issue" @@ -681,8 +686,8 @@ def test_error_2(self, processor, db): "privacy_policy": "privacy policy test", # update "transfer_approval_required": True, # update "principal_value": 1000, - "is_canceled": True # update - } + "is_canceled": True, # update + }, } _notification = _notification_list[1] assert _notification.id == 2 @@ -715,7 +720,7 @@ def test_error_2(self, processor, db): "contact_information": "contact info test", # update "privacy_policy": "privacy policy test", # update "transfer_approval_required": True, # update - } + }, } # @@ -767,7 +772,7 @@ def test_error_3(self, processor, db): "privacy_policy": "privacy policy test", # update "transfer_approval_required": True, # update "principal_value": 1000, - "is_canceled": True # update + "is_canceled": True, # update } _update_token_1.status = 0 _update_token_1.trigger = "Issue" @@ -834,10 +839,13 @@ def test_error_3(self, processor, db): db.commit() - with patch(target="app.model.blockchain.token.IbetShareContract.update", - rside_effect=SendTransactionError()) as IbetShareContract_update, \ - patch(target="app.model.blockchain.token.IbetStraightBondContract.update", - side_effect=SendTransactionError()) as IbetStraightBondContract_update: + with patch( + target="app.model.blockchain.token.IbetShareContract.update", + rside_effect=SendTransactionError(), + ) as IbetShareContract_update, patch( + target="app.model.blockchain.token.IbetStraightBondContract.update", + side_effect=SendTransactionError(), + ) as IbetStraightBondContract_update: # Execute batch processor.process() @@ -893,8 +901,8 @@ def test_error_3(self, processor, db): "privacy_policy": "privacy policy test", # update "transfer_approval_required": True, # update "principal_value": 1000, - "is_canceled": True # update - } + "is_canceled": True, # update + }, } _notification = _notification_list[1] assert _notification.id == 2 @@ -927,7 +935,7 @@ def test_error_3(self, processor, db): "contact_information": "contact info test", # update "privacy_policy": "privacy policy test", # update "transfer_approval_required": True, # update - } + }, } # @@ -979,7 +987,7 @@ def test_error_4(self, processor, db): "privacy_policy": "privacy policy test", # update "transfer_approval_required": True, # update "principal_value": 1000, - "is_canceled": True # update + "is_canceled": True, # update } _update_token_1.status = 0 _update_token_1.trigger = "Issue" @@ -1046,12 +1054,16 @@ def test_error_4(self, processor, db): db.commit() - with patch(target="app.model.blockchain.token.IbetShareContract.update", - return_value=None) as IbetShareContract_update, \ - patch(target="app.model.blockchain.token.IbetStraightBondContract.update", - return_value=None) as IbetStraightBondContract_update, \ - patch(target="app.model.blockchain.token_list.TokenListContract.register", - side_effect=SendTransactionError()) as TokenListContract_register: + with patch( + target="app.model.blockchain.token.IbetShareContract.update", + return_value=None, + ) as IbetShareContract_update, patch( + target="app.model.blockchain.token.IbetStraightBondContract.update", + return_value=None, + ) as IbetStraightBondContract_update, patch( + target="app.model.blockchain.token_list.TokenListContract.register", + side_effect=SendTransactionError(), + ) as TokenListContract_register: # Execute batch processor.process() @@ -1070,10 +1082,10 @@ def test_error_4(self, processor, db): contact_information="contact info test", privacy_policy="privacy policy test", transfer_approval_required=True, - is_canceled=True + is_canceled=True, ), tx_from=_issuer_address, - private_key=ANY + private_key=ANY, ) IbetStraightBondContract_update.assert_called_with( @@ -1088,10 +1100,10 @@ def test_error_4(self, processor, db): personal_info_contract_address="0x0000000000000000000000000000000000000002", contact_information="contact info test", privacy_policy="privacy policy test", - transfer_approval_required=True + transfer_approval_required=True, ), tx_from=_issuer_address, - private_key=ANY + private_key=ANY, ) # assertion(DB) @@ -1146,8 +1158,8 @@ def test_error_4(self, processor, db): "privacy_policy": "privacy policy test", # update "transfer_approval_required": True, # update "principal_value": 1000, - "is_canceled": True # update - } + "is_canceled": True, # update + }, } _notification = _notification_list[1] assert _notification.id == 2 @@ -1180,5 +1192,5 @@ def test_error_4(self, processor, db): "contact_information": "contact info test", # update "privacy_policy": "privacy policy test", # update "transfer_approval_required": True, # update - } + }, } diff --git a/tests/test_utils_check_utils.py b/tests/test_utils_check_utils.py index 2d49f78d..b917517a 100644 --- a/tests/test_utils_check_utils.py +++ b/tests/test_utils_check_utils.py @@ -24,10 +24,7 @@ from fastapi import Request from app.exceptions import AuthorizationError -from app.model.db import ( - Account, - AuthToken -) +from app.model.db import Account, AuthToken from app.utils.check_utils import check_auth from app.utils.e2ee_utils import E2EEUtils from tests.account_config import config_eth_account @@ -58,7 +55,7 @@ def test_normal_1_1(self, db): request=Request(scope={"type": "http", "client": ("192.168.1.1", 50000)}), db=db, issuer_address=test_account["address"], - eoa_password=E2EEUtils.encrypt(self.eoa_password) + eoa_password=E2EEUtils.encrypt(self.eoa_password), ) assert account == _account @@ -82,7 +79,7 @@ def test_normal_1_2(self, db): request=Request(scope={"type": "http", "client": ("192.168.1.1", 50000)}), db=db, issuer_address=test_account["address"], - eoa_password=self.eoa_password + eoa_password=self.eoa_password, ) assert account == _account @@ -112,7 +109,7 @@ def test_normal_2_1(self, db): request=Request(scope={"type": "http", "client": ("192.168.1.1", 50000)}), db=db, issuer_address=test_account["address"], - auth_token=self.auth_token + auth_token=self.auth_token, ) assert account == _account @@ -134,17 +131,19 @@ def test_normal_2_2(self, freezer, db): _auth_token = AuthToken() _auth_token.issuer_address = test_account["address"] _auth_token.auth_token = hashlib.sha256(self.auth_token.encode()).hexdigest() - _auth_token.usage_start = datetime(2022, 7, 15, 12, 32, 56) # 2022-07-15 12:34:56 - 120sec + _auth_token.usage_start = datetime( + 2022, 7, 15, 12, 32, 56 + ) # 2022-07-15 12:34:56 - 120sec _auth_token.valid_duration = 120 db.add(_auth_token) # test function - freezer.move_to('2022-07-15 12:34:56') + freezer.move_to("2022-07-15 12:34:56") account, decrypted_eoa_password = check_auth( request=Request(scope={"type": "http", "client": ("192.168.1.1", 50000)}), db=db, issuer_address=test_account["address"], - auth_token=self.auth_token + auth_token=self.auth_token, ) assert account == _account @@ -162,10 +161,12 @@ def test_error_1(self, db): # test function with pytest.raises(AuthorizationError): check_auth( - request=Request(scope={"type": "http", "client": ("192.168.1.1", 50000)}), + request=Request( + scope={"type": "http", "client": ("192.168.1.1", 50000)} + ), db=db, issuer_address=test_account["address"], - eoa_password=E2EEUtils.encrypt(self.eoa_password) + eoa_password=E2EEUtils.encrypt(self.eoa_password), ) # Error_2 @@ -183,9 +184,11 @@ def test_error_2(self, db): # test function with pytest.raises(AuthorizationError): check_auth( - request=Request(scope={"type": "http", "client": ("192.168.1.1", 50000)}), + request=Request( + scope={"type": "http", "client": ("192.168.1.1", 50000)} + ), db=db, - issuer_address=test_account["address"] + issuer_address=test_account["address"], ) # Error_3_1 @@ -203,10 +206,14 @@ def test_error_3_1(self, db): # test function with pytest.raises(AuthorizationError): check_auth( - request=Request(scope={"type": "http", "client": ("192.168.1.1", 50000)}), + request=Request( + scope={"type": "http", "client": ("192.168.1.1", 50000)} + ), db=db, issuer_address=test_account["address"], - eoa_password=E2EEUtils.encrypt("incorrect_password") # incorrect password + eoa_password=E2EEUtils.encrypt( + "incorrect_password" + ), # incorrect password ) # Error_3_2 @@ -225,10 +232,12 @@ def test_error_3_2(self, db): # test function with pytest.raises(AuthorizationError): check_auth( - request=Request(scope={"type": "http", "client": ("192.168.1.1", 50000)}), + request=Request( + scope={"type": "http", "client": ("192.168.1.1", 50000)} + ), db=db, issuer_address=test_account["address"], - eoa_password="incorrect_password" # incorrect password + eoa_password="incorrect_password", # incorrect password ) # Error_4_1 @@ -246,10 +255,12 @@ def test_error_4_1(self, db): # test function with pytest.raises(AuthorizationError): check_auth( - request=Request(scope={"type": "http", "client": ("192.168.1.1", 50000)}), + request=Request( + scope={"type": "http", "client": ("192.168.1.1", 50000)} + ), db=db, issuer_address=test_account["address"], - auth_token=self.eoa_password + auth_token=self.eoa_password, ) # Error_4_2 @@ -273,10 +284,12 @@ def test_error_4_2(self, db): # test function with pytest.raises(AuthorizationError): check_auth( - request=Request(scope={"type": "http", "client": ("192.168.1.1", 50000)}), + request=Request( + scope={"type": "http", "client": ("192.168.1.1", 50000)} + ), db=db, issuer_address=test_account["address"], - auth_token="incorrect_token" # incorrect token + auth_token="incorrect_token", # incorrect token ) # Error_4_3 @@ -294,16 +307,20 @@ def test_error_4_3(self, freezer, db): _auth_token = AuthToken() _auth_token.issuer_address = test_account["address"] _auth_token.auth_token = hashlib.sha256(self.auth_token.encode()).hexdigest() - _auth_token.usage_start = datetime(2022, 7, 15, 12, 32, 55) # 2022-07-15 12:34:56 - 121sec + _auth_token.usage_start = datetime( + 2022, 7, 15, 12, 32, 55 + ) # 2022-07-15 12:34:56 - 121sec _auth_token.valid_duration = 120 db.add(_auth_token) # test function - freezer.move_to('2022-07-15 12:34:56') + freezer.move_to("2022-07-15 12:34:56") with pytest.raises(AuthorizationError): check_auth( - request=Request(scope={"type": "http", "client": ("192.168.1.1", 50000)}), + request=Request( + scope={"type": "http", "client": ("192.168.1.1", 50000)} + ), db=db, issuer_address=test_account["address"], - auth_token=self.auth_token + auth_token=self.auth_token, ) diff --git a/tests/test_utils_contract_utils.py b/tests/test_utils_contract_utils.py index 892d7b43..0144742f 100755 --- a/tests/test_utils_contract_utils.py +++ b/tests/test_utils_contract_utils.py @@ -16,22 +16,20 @@ SPDX-License-Identifier: Apache-2.0 """ +import json from unittest.mock import patch import pytest -import json - +from eth_keyfile import decode_keyfile_json +from sqlalchemy.orm import Session from web3 import Web3 from web3.exceptions import ContractLogicError from web3.middleware import geth_poa_middleware -from eth_keyfile import decode_keyfile_json - -from sqlalchemy.orm import Session -from app.exceptions import SendTransactionError, ContractRevertError -from config import WEB3_HTTP_PROVIDER, CHAIN_ID, TX_GAS_LIMIT -from app.utils.contract_utils import ContractUtils +from app.exceptions import ContractRevertError, SendTransactionError from app.model.db import TransactionLock +from app.utils.contract_utils import ContractUtils +from config import CHAIN_ID, TX_GAS_LIMIT, WEB3_HTTP_PROVIDER from tests.account_config import config_eth_account web3 = Web3(Web3.HTTPProvider(WEB3_HTTP_PROVIDER)) @@ -52,10 +50,7 @@ class TestGetContractCode: "TokenList", ] - contract_interface_list = [ - "ContractReceiver", - "IbetStandardTokenInterface" - ] + contract_interface_list = ["ContractReceiver", "IbetStandardTokenInterface"] ########################################################################### # Normal Case @@ -63,9 +58,11 @@ class TestGetContractCode: # def test_normal_1(self): for contract_name in self.contract_list: - rtn_abi, rtn_bytecode, rtn_deploy_bytecode = ContractUtils.get_contract_code( - contract_name=contract_name - ) + ( + rtn_abi, + rtn_bytecode, + rtn_deploy_bytecode, + ) = ContractUtils.get_contract_code(contract_name=contract_name) expected_json = json.load(open(f"contracts/{contract_name}.json", "r")) assert rtn_abi == expected_json["abi"] assert rtn_bytecode == expected_json["bytecode"] @@ -75,9 +72,7 @@ def test_normal_1(self): # ContractReceiver and IbetStandardTokenInterface does not have bytecode def test_normal_2(self): for contract_name in self.contract_interface_list: - rtn = ContractUtils.get_contract_code( - contract_name=contract_name - ) + rtn = ContractUtils.get_contract_code(contract_name=contract_name) expected_json = json.load(open(f"contracts/{contract_name}.json", "r")) assert rtn == (expected_json["abi"], None, None) @@ -88,9 +83,7 @@ def test_normal_2(self): # Contract name does not exist def test_error_1(self): with pytest.raises(FileNotFoundError): - ContractUtils.get_contract_code( - contract_name="NO_EXISTS" - ) + ContractUtils.get_contract_code(contract_name="NO_EXISTS") class TestDeployContract: @@ -98,7 +91,7 @@ class TestDeployContract: eoa_password = "password" private_key = decode_keyfile_json( raw_keyfile_json=test_account["keyfile_json"], - password=eoa_password.encode("utf-8") + password=eoa_password.encode("utf-8"), ) test_contract_name = "IbetCoupon" @@ -113,7 +106,7 @@ class TestDeployContract: "20210531", True, "test_contract_information", - "test_privacy_policy" + "test_privacy_policy", ] ########################################################################### @@ -125,9 +118,11 @@ def test_normal_1(self, db): contract_name=self.test_contract_name, args=self.test_arg, deployer=self.test_account["address"], - private_key=self.private_key + private_key=self.private_key, ) - expected_abi = json.load(open(f"contracts/{self.test_contract_name}.json", 'r'))["abi"] + expected_abi = json.load( + open(f"contracts/{self.test_contract_name}.json", "r") + )["abi"] assert rtn_abi == expected_abi ########################################################################### @@ -141,7 +136,7 @@ def test_error_1(self): contract_name="NOT_EXIST_CONTRACT", args=self.test_arg, deployer=self.test_account["address"], - private_key=self.private_key + private_key=self.private_key, ) assert str(ex_info.typename) == "SendTransactionError" @@ -151,7 +146,7 @@ def test_error_2(self): # mock ContractUtils_send_transaction = patch( target="app.utils.contract_utils.ContractUtils.send_transaction", - side_effect=SendTransactionError + side_effect=SendTransactionError, ) with ContractUtils_send_transaction: @@ -160,7 +155,7 @@ def test_error_2(self): contract_name=self.test_contract_name, args=self.test_arg, deployer=self.test_account["address"], - private_key=self.private_key + private_key=self.private_key, ) assert str(ex_info.typename) == "SendTransactionError" @@ -170,7 +165,7 @@ class TestGetContract: eoa_password = "password" private_key = decode_keyfile_json( raw_keyfile_json=test_account["keyfile_json"], - password=eoa_password.encode("utf-8") + password=eoa_password.encode("utf-8"), ) contract_list = [ @@ -192,8 +187,7 @@ def test_normal_1(self): test_address = "0x986eBe386b1D04C8d57387b60628fD8BBeEFF1b6" for _contract_name in self.contract_list: contract = ContractUtils.get_contract( - contract_name=_contract_name, - contract_address=test_address + contract_name=_contract_name, contract_address=test_address ) assert contract.abi == ContractUtils.get_contract_code(_contract_name)[0] assert contract.bytecode is None @@ -206,7 +200,7 @@ def test_error_1(self): with pytest.raises(ValueError): ContractUtils.get_contract( contract_name="IbetShare", - contract_address="0x986eBe386b1D04C8d57387b60628fD8BBeEFF1b6ZZZZ" # too long + contract_address="0x986eBe386b1D04C8d57387b60628fD8BBeEFF1b6ZZZZ", # too long ) # @@ -215,7 +209,7 @@ def test_error_2(self): with pytest.raises(FileNotFoundError): ContractUtils.get_contract( contract_name="NotExistContract", - contract_address="0x986eBe386b1D04C8d57387b60628fD8BBeEFF1b6" + contract_address="0x986eBe386b1D04C8d57387b60628fD8BBeEFF1b6", ) @@ -224,7 +218,7 @@ class TestSendTransaction: eoa_password = "password" private_key = decode_keyfile_json( raw_keyfile_json=test_account["keyfile_json"], - password=eoa_password.encode("utf-8") + password=eoa_password.encode("utf-8"), ) test_contract_name = "IbetCoupon" @@ -239,7 +233,7 @@ class TestSendTransaction: "20210531", True, "test_contract_information", - "test_privacy_policy" + "test_privacy_policy", ] contract_file = f"contracts/{test_contract_name}.json" contract_json = json.load(open(contract_file, "r")) @@ -267,8 +261,7 @@ def test_normal_1(self, db: Session): ) rtn_tx_hash, rtn_receipt = ContractUtils.send_transaction( - transaction=tx, - private_key=self.private_key + transaction=tx, private_key=self.private_key ) assert rtn_tx_hash == rtn_receipt["transactionHash"].hex() @@ -287,7 +280,7 @@ def test_error_1(self, db: Session): contract = web3.eth.contract( abi=self.contract_json["abi"], # add "0000" to make invalid bytecode - bytecode=self.contract_json["bytecode"]+"0000", + bytecode=self.contract_json["bytecode"] + "0000", bytecode_runtime=self.contract_json["deployedBytecode"], ) @@ -304,21 +297,17 @@ def test_error_1(self, db: Session): # mock Web3_send_raw_transaction = patch( target="web3.eth.Eth.wait_for_transaction_receipt", - return_value={ - "dummy": "hoge", - "status": 0 - } + return_value={"dummy": "hoge", "status": 0}, ) InspectionMock = patch( target="web3.eth.Eth.call", - side_effect=ContractLogicError("execution reverted") + side_effect=ContractLogicError("execution reverted"), ) with Web3_send_raw_transaction, InspectionMock: with pytest.raises(ContractRevertError): ContractUtils.send_transaction( - transaction=tx, - private_key=self.private_key + transaction=tx, private_key=self.private_key ) # @@ -343,15 +332,13 @@ def test_error_2(self, db: Session): # mock Web3_send_raw_transaction = patch( - target="web3.eth.Eth.wait_for_transaction_receipt", - side_effect=ValueError + target="web3.eth.Eth.wait_for_transaction_receipt", side_effect=ValueError ) with Web3_send_raw_transaction: with pytest.raises(ValueError): ContractUtils.send_transaction( - transaction=tx, - private_key=self.private_key + transaction=tx, private_key=self.private_key ) # @@ -381,17 +368,12 @@ def test_error_3(self, db: Session): ) # Transaction Lock - db.query(TransactionLock). \ - filter(TransactionLock.tx_from == self.test_account["address"]). \ - populate_existing(). \ - with_for_update(). \ - first() + db.query(TransactionLock).filter( + TransactionLock.tx_from == self.test_account["address"] + ).populate_existing().with_for_update().first() with pytest.raises(SendTransactionError) as ex_info: - ContractUtils.send_transaction( - transaction=tx, - private_key=self.private_key - ) + ContractUtils.send_transaction(transaction=tx, private_key=self.private_key) assert ex_info.typename == "SendTransactionError" db.rollback() @@ -402,7 +384,7 @@ class TestGetBlockByTransactionHash: eoa_password = "password" private_key = decode_keyfile_json( raw_keyfile_json=test_account["keyfile_json"], - password=eoa_password.encode("utf-8") + password=eoa_password.encode("utf-8"), ) test_contract_name = "IbetCoupon" @@ -417,7 +399,7 @@ class TestGetBlockByTransactionHash: "20210531", True, "test_contract_information", - "test_privacy_policy" + "test_privacy_policy", ] contract_file = f"contracts/{test_contract_name}.json" contract_json = json.load(open(contract_file, "r")) @@ -446,15 +428,13 @@ def test_normal_1(self, db: Session): nonce = web3.eth.get_transaction_count(self.test_account["address"]) tx["nonce"] = nonce signed_tx = web3.eth.account.sign_transaction( - transaction_dict=tx, - private_key=self.private_key + transaction_dict=tx, private_key=self.private_key ) # Send Transaction tx_hash = web3.eth.send_raw_transaction(signed_tx.rawTransaction.hex()) tx_receipt = web3.eth.wait_for_transaction_receipt( - transaction_hash=tx_hash, - timeout=10 + transaction_hash=tx_hash, timeout=10 ) block = ContractUtils.get_block_by_transaction_hash(tx_hash) diff --git a/tests/test_utils_ledger_utils.py b/tests/test_utils_ledger_utils.py index 7aa92f00..a5bc11b7 100644 --- a/tests/test_utils_ledger_utils.py +++ b/tests/test_utils_ledger_utils.py @@ -19,42 +19,40 @@ from datetime import datetime import pytz +from eth_keyfile import decode_keyfile_json from web3 import Web3 from web3.middleware import geth_poa_middleware -from eth_keyfile import decode_keyfile_json -from config import ( - WEB3_HTTP_PROVIDER, - CHAIN_ID, - TX_GAS_LIMIT, - ZERO_ADDRESS, - TZ -) -from app.utils.e2ee_utils import E2EEUtils from app.model.blockchain import ( IbetShareContract, IbetStraightBondContract, PersonalInfoContract, ) -from app.model.blockchain.tx_params.ibet_straight_bond import UpdateParams as IbetStraightBondUpdateParams -from app.model.blockchain.tx_params.ibet_share import UpdateParams as IbetShareUpdateParams -from app.utils.contract_utils import ContractUtils +from app.model.blockchain.tx_params.ibet_share import ( + UpdateParams as IbetShareUpdateParams, +) +from app.model.blockchain.tx_params.ibet_straight_bond import ( + UpdateParams as IbetStraightBondUpdateParams, +) from app.model.db import ( + UTXO, Account, AccountRsaStatus, - Token, - TokenType, IDXPersonalInfo, - UTXO, Ledger, LedgerDetailsData, - LedgerTemplate, - LedgerDetailsTemplate, LedgerDetailsDataType, + LedgerDetailsTemplate, + LedgerTemplate, Notification, NotificationType, + Token, + TokenType, ) from app.utils import ledger_utils +from app.utils.contract_utils import ContractUtils +from app.utils.e2ee_utils import E2EEUtils +from config import CHAIN_ID, TX_GAS_LIMIT, TZ, WEB3_HTTP_PROVIDER, ZERO_ADDRESS from tests.account_config import config_eth_account web3 = Web3(Web3.HTTPProvider(WEB3_HTTP_PROVIDER)) @@ -71,7 +69,7 @@ def deploy_bond_token_contract(address, private_key, personal_info_contract_addr 30, "token.return_date", "token.return_amount", - "token.purpose" + "token.purpose", ] bond_contrat = IbetStraightBondContract() contract_address, _, _ = bond_contrat.create(arguments, address, private_key) @@ -93,7 +91,7 @@ def deploy_share_token_contract(address, private_key, personal_info_contract_add "token.dividend_record_date", "token.dividend_payment_date", "token.cancellation_date", - 200 + 200, ] share_contract = IbetShareContract() contract_address, _, _ = share_contract.create(arguments, address, private_key) @@ -106,7 +104,9 @@ def deploy_share_token_contract(address, private_key, personal_info_contract_add def deploy_personal_info_contract(address, private_key): - contract_address, _, _ = ContractUtils.deploy_contract("PersonalInfo", [], address, private_key) + contract_address, _, _ = ContractUtils.deploy_contract( + "PersonalInfo", [], address, private_key + ) return contract_address @@ -114,13 +114,15 @@ def set_personal_info_contract(db, contract_address, issuer_address, sender_list contract = ContractUtils.get_contract("PersonalInfo", contract_address) for sender in sender_list: - tx = contract.functions.register(issuer_address, "").build_transaction({ - "nonce": web3.eth.get_transaction_count(sender["address"]), - "chainId": CHAIN_ID, - "from": sender["address"], - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + tx = contract.functions.register(issuer_address, "").build_transaction( + { + "nonce": web3.eth.get_transaction_count(sender["address"]), + "chainId": CHAIN_ID, + "from": sender["address"], + "gas": TX_GAS_LIMIT, + "gasPrice": 0, + } + ) ContractUtils.send_transaction(tx, sender["private_key"]) personal_info = PersonalInfoContract(db, issuer_address, contract_address) @@ -128,7 +130,6 @@ def set_personal_info_contract(db, contract_address, issuer_address, sender_list class TestCreateLedger: - ########################################################################### # Normal Case ########################################################################### @@ -139,20 +140,17 @@ def test_normal_1(self, db): issuer = config_eth_account("user5") issuer_address = issuer["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=issuer["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=issuer["keyfile_json"], password="password".encode("utf-8") ) user_1 = config_eth_account("user1") user_address_1 = user_1["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_2 = user_2["address"] user_private_key_2 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # prepare data @@ -168,28 +166,35 @@ def test_normal_1(self, db): db.add(_account) # Token - personal_info_contract_address = deploy_personal_info_contract(issuer_address, issuer_private_key) - set_personal_info_contract(db, personal_info_contract_address, issuer_address, - [ - { - "address": user_address_1, - "private_key": user_private_key_1, - "data": { - "name": "name_test_con_1", - "address": "address_test_con_1", - }, - }, - { - "address": user_address_2, - "private_key": user_private_key_2, - "data": { - "name": "name_test_con_2", - "address": "address_test_con_2", - }, - } - ]) - token_address_1 = deploy_share_token_contract(issuer_address, issuer_private_key, - personal_info_contract_address) + personal_info_contract_address = deploy_personal_info_contract( + issuer_address, issuer_private_key + ) + set_personal_info_contract( + db, + personal_info_contract_address, + issuer_address, + [ + { + "address": user_address_1, + "private_key": user_private_key_1, + "data": { + "name": "name_test_con_1", + "address": "address_test_con_1", + }, + }, + { + "address": user_address_2, + "private_key": user_private_key_2, + "data": { + "name": "name_test_con_2", + "address": "address_test_con_2", + }, + }, + ], + ) + token_address_1 = deploy_share_token_contract( + issuer_address, issuer_private_key, personal_info_contract_address + ) _token_1 = Token() _token_1.type = TokenType.IBET_SHARE.value _token_1.tx_hash = "" @@ -217,7 +222,9 @@ def test_normal_1(self, db): _utxo_1.token_address = token_address_1 _utxo_1.amount = 100 _utxo_1.block_number = 1 - _utxo_1.block_timestamp = datetime.strptime("2021/12/31 15:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/01 + _utxo_1.block_timestamp = datetime.strptime( + "2021/12/31 15:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/01 db.add(_utxo_1) _utxo_2 = UTXO() @@ -226,7 +233,9 @@ def test_normal_1(self, db): _utxo_2.token_address = token_address_1 _utxo_2.amount = 10 _utxo_2.block_number = 2 - _utxo_2.block_timestamp = datetime.strptime("2022/01/01 01:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/01 + _utxo_2.block_timestamp = datetime.strptime( + "2022/01/01 01:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/01 db.add(_utxo_2) _utxo_3 = UTXO() @@ -235,7 +244,9 @@ def test_normal_1(self, db): _utxo_3.token_address = token_address_1 _utxo_3.amount = 30 _utxo_3.block_number = 3 - _utxo_3.block_timestamp = datetime.strptime("2022/01/01 15:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/02 + _utxo_3.block_timestamp = datetime.strptime( + "2022/01/01 15:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/02 db.add(_utxo_3) _utxo_4 = UTXO() @@ -244,7 +255,9 @@ def test_normal_1(self, db): _utxo_4.token_address = token_address_1 _utxo_4.amount = 40 _utxo_4.block_number = 4 - _utxo_4.block_timestamp = datetime.strptime("2022/01/02 01:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/02 + _utxo_4.block_timestamp = datetime.strptime( + "2022/01/02 01:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/02 db.add(_utxo_4) _utxo_5 = UTXO() @@ -253,7 +266,9 @@ def test_normal_1(self, db): _utxo_5.token_address = token_address_1 _utxo_5.amount = 200 _utxo_5.block_number = 5 - _utxo_5.block_timestamp = datetime.strptime("2021/12/31 15:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/01 + _utxo_5.block_timestamp = datetime.strptime( + "2021/12/31 15:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/01 db.add(_utxo_5) _utxo_6 = UTXO() @@ -262,7 +277,9 @@ def test_normal_1(self, db): _utxo_6.token_address = token_address_1 _utxo_6.amount = 20 _utxo_6.block_number = 6 - _utxo_6.block_timestamp = datetime.strptime("2022/01/01 01:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/01 + _utxo_6.block_timestamp = datetime.strptime( + "2022/01/01 01:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/01 db.add(_utxo_6) _utxo_7 = UTXO() @@ -271,7 +288,9 @@ def test_normal_1(self, db): _utxo_7.token_address = token_address_1 _utxo_7.amount = 40 _utxo_7.block_number = 7 - _utxo_7.block_timestamp = datetime.strptime("2022/01/01 15:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/02 + _utxo_7.block_timestamp = datetime.strptime( + "2022/01/01 15:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/02 db.add(_utxo_7) _utxo_8 = UTXO() @@ -280,7 +299,9 @@ def test_normal_1(self, db): _utxo_8.token_address = token_address_1 _utxo_8.amount = 2 _utxo_8.block_number = 8 - _utxo_8.block_timestamp = datetime.strptime("2022/01/02 01:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/02 + _utxo_8.block_timestamp = datetime.strptime( + "2022/01/02 01:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/02 db.add(_utxo_8) # Template @@ -299,12 +320,10 @@ def test_normal_1(self, db): "テスト項目B": "テスト値2B", }, "テスト項目3": { - "テスト項目A": { - "テスト項目a": "テスト値3Aa" - }, + "テスト項目A": {"テスト項目a": "テスト値3Aa"}, "テスト項目B": "テスト値3B", }, - } + }, ] _template.token_name = "受益権テスト" _template.footers = [ @@ -319,12 +338,10 @@ def test_normal_1(self, db): "f-テスト項目B": "f-テスト値2B", }, "f-テスト項目3": { - "f-テスト項目A": { - "f-テスト項目a": "f-テスト値3Aa" - }, + "f-テスト項目A": {"f-テスト項目a": "f-テスト値3Aa"}, "f-テスト項目B": "f-テスト値3B", }, - } + }, ] db.add(_template) @@ -342,7 +359,7 @@ def test_normal_1(self, db): "test項目2": { "test項目A": "test値2A", }, - } + }, ] _details_1.footers = [ { @@ -351,12 +368,8 @@ def test_normal_1(self, db): }, { "test-item1": "test-value1", - "test-item2": { - "test-itemA": { - "test-itema": "test-value2Aa" - } - }, - } + "test-item2": {"test-itemA": {"test-itema": "test-value2Aa"}}, + }, ] _details_1.data_type = LedgerDetailsDataType.IBET_FIN.value _details_1.data_source = token_address_1 @@ -374,7 +387,7 @@ def test_normal_1(self, db): { "d-test項目1": "d-test値1", "d-test項目2": "d-test値2", - } + }, ] _details_2.footers = [ { @@ -384,7 +397,7 @@ def test_normal_1(self, db): { "f-d-test項目1": "d-test値1", "f-d-test項目2": "d-test値2", - } + }, ] _details_2.data_type = LedgerDetailsDataType.DB.value _details_2.data_source = "data_id_2" @@ -429,7 +442,7 @@ def test_normal_1(self, db): assert _notification.metainfo == { "token_address": token_address_1, "token_type": TokenType.IBET_SHARE.value, - "ledger_id": 1 + "ledger_id": 1, } _ledger = db.query(Ledger).first() @@ -452,12 +465,10 @@ def test_normal_1(self, db): "テスト項目B": "テスト値2B", }, "テスト項目3": { - "テスト項目A": { - "テスト項目a": "テスト値3Aa" - }, + "テスト項目A": {"テスト項目a": "テスト値3Aa"}, "テスト項目B": "テスト値3B", }, - } + }, ], "details": [ { @@ -472,7 +483,7 @@ def test_normal_1(self, db): "test項目2": { "test項目A": "test値2A", }, - } + }, ], "data": [ { @@ -520,12 +531,10 @@ def test_normal_1(self, db): { "test-item1": "test-value1", "test-item2": { - "test-itemA": { - "test-itema": "test-value2Aa" - } + "test-itemA": {"test-itema": "test-value2Aa"} }, - } - ] + }, + ], }, { "token_detail_type": "劣後受益権", @@ -537,7 +546,7 @@ def test_normal_1(self, db): { "d-test項目1": "d-test値1", "d-test項目2": "d-test値2", - } + }, ], "data": [ { @@ -567,8 +576,8 @@ def test_normal_1(self, db): { "f-d-test項目1": "d-test値1", "f-d-test項目2": "d-test値2", - } - ] + }, + ], }, ], "footers": [ @@ -583,13 +592,11 @@ def test_normal_1(self, db): "f-テスト項目B": "f-テスト値2B", }, "f-テスト項目3": { - "f-テスト項目A": { - "f-テスト項目a": "f-テスト値3Aa" - }, + "f-テスト項目A": {"f-テスト項目a": "f-テスト値3Aa"}, "f-テスト項目B": "f-テスト値3B", }, - } - ] + }, + ], } # @@ -598,20 +605,17 @@ def test_normal_2(self, db): issuer = config_eth_account("user5") issuer_address = issuer["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=issuer["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=issuer["keyfile_json"], password="password".encode("utf-8") ) user_1 = config_eth_account("user1") user_address_1 = user_1["address"] user_private_key_1 = decode_keyfile_json( - raw_keyfile_json=user_1["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_1["keyfile_json"], password="password".encode("utf-8") ) user_2 = config_eth_account("user2") user_address_2 = user_2["address"] user_private_key_2 = decode_keyfile_json( - raw_keyfile_json=user_2["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=user_2["keyfile_json"], password="password".encode("utf-8") ) # prepare data @@ -627,28 +631,35 @@ def test_normal_2(self, db): db.add(_account) # Token - personal_info_contract_address = deploy_personal_info_contract(issuer_address, issuer_private_key) - set_personal_info_contract(db, personal_info_contract_address, issuer_address, - [ - { - "address": user_address_1, - "private_key": user_private_key_1, - "data": { - "name": "name_test_con_1", - "address": "address_test_con_1", - }, - }, - { - "address": user_address_2, - "private_key": user_private_key_2, - "data": { - "name": "name_test_con_2", - "address": "address_test_con_2", - }, - } - ]) - token_address_1 = deploy_bond_token_contract(issuer_address, issuer_private_key, - personal_info_contract_address) + personal_info_contract_address = deploy_personal_info_contract( + issuer_address, issuer_private_key + ) + set_personal_info_contract( + db, + personal_info_contract_address, + issuer_address, + [ + { + "address": user_address_1, + "private_key": user_private_key_1, + "data": { + "name": "name_test_con_1", + "address": "address_test_con_1", + }, + }, + { + "address": user_address_2, + "private_key": user_private_key_2, + "data": { + "name": "name_test_con_2", + "address": "address_test_con_2", + }, + }, + ], + ) + token_address_1 = deploy_bond_token_contract( + issuer_address, issuer_private_key, personal_info_contract_address + ) _token_1 = Token() _token_1.type = TokenType.IBET_STRAIGHT_BOND.value _token_1.tx_hash = "" @@ -676,7 +687,9 @@ def test_normal_2(self, db): _utxo_1.token_address = token_address_1 _utxo_1.amount = 100 _utxo_1.block_number = 1 - _utxo_1.block_timestamp = datetime.strptime("2021/12/31 15:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/01 + _utxo_1.block_timestamp = datetime.strptime( + "2021/12/31 15:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/01 db.add(_utxo_1) _utxo_2 = UTXO() @@ -685,7 +698,9 @@ def test_normal_2(self, db): _utxo_2.token_address = token_address_1 _utxo_2.amount = 10 _utxo_2.block_number = 2 - _utxo_2.block_timestamp = datetime.strptime("2022/01/01 01:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/01 + _utxo_2.block_timestamp = datetime.strptime( + "2022/01/01 01:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/01 db.add(_utxo_2) _utxo_3 = UTXO() @@ -694,7 +709,9 @@ def test_normal_2(self, db): _utxo_3.token_address = token_address_1 _utxo_3.amount = 30 _utxo_3.block_number = 3 - _utxo_3.block_timestamp = datetime.strptime("2022/01/01 15:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/02 + _utxo_3.block_timestamp = datetime.strptime( + "2022/01/01 15:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/02 db.add(_utxo_3) _utxo_4 = UTXO() @@ -703,7 +720,9 @@ def test_normal_2(self, db): _utxo_4.token_address = token_address_1 _utxo_4.amount = 40 _utxo_4.block_number = 4 - _utxo_4.block_timestamp = datetime.strptime("2022/01/02 01:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/02 + _utxo_4.block_timestamp = datetime.strptime( + "2022/01/02 01:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/02 db.add(_utxo_4) _utxo_5 = UTXO() @@ -712,7 +731,9 @@ def test_normal_2(self, db): _utxo_5.token_address = token_address_1 _utxo_5.amount = 200 _utxo_5.block_number = 5 - _utxo_5.block_timestamp = datetime.strptime("2021/12/31 15:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/01 + _utxo_5.block_timestamp = datetime.strptime( + "2021/12/31 15:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/01 db.add(_utxo_5) _utxo_6 = UTXO() @@ -721,7 +742,9 @@ def test_normal_2(self, db): _utxo_6.token_address = token_address_1 _utxo_6.amount = 20 _utxo_6.block_number = 6 - _utxo_6.block_timestamp = datetime.strptime("2022/01/01 01:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/01 + _utxo_6.block_timestamp = datetime.strptime( + "2022/01/01 01:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/01 db.add(_utxo_6) _utxo_7 = UTXO() @@ -730,7 +753,9 @@ def test_normal_2(self, db): _utxo_7.token_address = token_address_1 _utxo_7.amount = 40 _utxo_7.block_number = 7 - _utxo_7.block_timestamp = datetime.strptime("2022/01/01 15:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/02 + _utxo_7.block_timestamp = datetime.strptime( + "2022/01/01 15:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/02 db.add(_utxo_7) _utxo_8 = UTXO() @@ -739,7 +764,9 @@ def test_normal_2(self, db): _utxo_8.token_address = token_address_1 _utxo_8.amount = 2 _utxo_8.block_number = 8 - _utxo_8.block_timestamp = datetime.strptime("2022/01/02 01:20:30", '%Y/%m/%d %H:%M:%S') # JST 2022/01/02 + _utxo_8.block_timestamp = datetime.strptime( + "2022/01/02 01:20:30", "%Y/%m/%d %H:%M:%S" + ) # JST 2022/01/02 db.add(_utxo_8) # Template @@ -761,12 +788,10 @@ def test_normal_2(self, db): "テスト項目B": "テスト値2B", }, "テスト項目3": { - "テスト項目A": { - "テスト項目a": "テスト値3Aa" - }, + "テスト項目A": {"テスト項目a": "テスト値3Aa"}, "テスト項目B": "テスト値3B", }, - } + }, ] _template.footers = [ { @@ -780,12 +805,10 @@ def test_normal_2(self, db): "f-テスト項目B": "f-テスト値2B", }, "f-テスト項目3": { - "f-テスト項目A": { - "f-テスト項目a": "f-テスト値3Aa" - }, + "f-テスト項目A": {"f-テスト項目a": "f-テスト値3Aa"}, "f-テスト項目B": "f-テスト値3B", }, - } + }, ] db.add(_template) @@ -803,7 +826,7 @@ def test_normal_2(self, db): "test項目2": { "test項目A": "test値2A", }, - } + }, ] _details_1.footers = [ { @@ -812,12 +835,8 @@ def test_normal_2(self, db): }, { "test-item1": "test-value1", - "test-item2": { - "test-itemA": { - "test-itema": "test-value2Aa" - } - }, - } + "test-item2": {"test-itemA": {"test-itema": "test-value2Aa"}}, + }, ] _details_1.data_type = LedgerDetailsDataType.IBET_FIN.value _details_1.data_source = token_address_1 @@ -835,7 +854,7 @@ def test_normal_2(self, db): { "d-test項目1": "d-test値1", "d-test項目2": "d-test値2", - } + }, ] _details_2.footers = [ { @@ -845,7 +864,7 @@ def test_normal_2(self, db): { "f-d-test項目1": "d-test値1", "f-d-test項目2": "d-test値2", - } + }, ] _details_2.data_type = LedgerDetailsDataType.DB.value _details_2.data_source = "data_id_2" @@ -890,7 +909,7 @@ def test_normal_2(self, db): assert _notification.metainfo == { "token_address": token_address_1, "token_type": TokenType.IBET_STRAIGHT_BOND.value, - "ledger_id": 1 + "ledger_id": 1, } _ledger = db.query(Ledger).first() assert _ledger.id == 1 @@ -912,12 +931,10 @@ def test_normal_2(self, db): "テスト項目B": "テスト値2B", }, "テスト項目3": { - "テスト項目A": { - "テスト項目a": "テスト値3Aa" - }, + "テスト項目A": {"テスト項目a": "テスト値3Aa"}, "テスト項目B": "テスト値3B", }, - } + }, ], "details": [ { @@ -932,7 +949,7 @@ def test_normal_2(self, db): "test項目2": { "test項目A": "test値2A", }, - } + }, ], "data": [ { @@ -980,12 +997,10 @@ def test_normal_2(self, db): { "test-item1": "test-value1", "test-item2": { - "test-itemA": { - "test-itema": "test-value2Aa" - } + "test-itemA": {"test-itema": "test-value2Aa"} }, - } - ] + }, + ], }, { "token_detail_type": "劣後受益権", @@ -997,7 +1012,7 @@ def test_normal_2(self, db): { "d-test項目1": "d-test値1", "d-test項目2": "d-test値2", - } + }, ], "data": [ { @@ -1027,8 +1042,8 @@ def test_normal_2(self, db): { "f-d-test項目1": "d-test値1", "f-d-test項目2": "d-test値2", - } - ] + }, + ], }, ], "footers": [ @@ -1043,13 +1058,11 @@ def test_normal_2(self, db): "f-テスト項目B": "f-テスト値2B", }, "f-テスト項目3": { - "f-テスト項目A": { - "f-テスト項目a": "f-テスト値3Aa" - }, + "f-テスト項目A": {"f-テスト項目a": "f-テスト値3Aa"}, "f-テスト項目B": "f-テスト値3B", }, - } - ] + }, + ], } # @@ -1058,13 +1071,14 @@ def test_normal_3(self, db): issuer = config_eth_account("user5") issuer_address = issuer["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=issuer["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=issuer["keyfile_json"], password="password".encode("utf-8") ) # prepare data # Token - token_address_1 = deploy_bond_token_contract(issuer_address, issuer_private_key, ZERO_ADDRESS) + token_address_1 = deploy_bond_token_contract( + issuer_address, issuer_private_key, ZERO_ADDRESS + ) _token_1 = Token() _token_1.type = TokenType.IBET_STRAIGHT_BOND.value _token_1.tx_hash = "" @@ -1088,13 +1102,14 @@ def test_normal_4(self, db): issuer = config_eth_account("user5") issuer_address = issuer["address"] issuer_private_key = decode_keyfile_json( - raw_keyfile_json=issuer["keyfile_json"], - password="password".encode("utf-8") + raw_keyfile_json=issuer["keyfile_json"], password="password".encode("utf-8") ) # prepare data # Token - token_address_1 = deploy_bond_token_contract(issuer_address, issuer_private_key, ZERO_ADDRESS) + token_address_1 = deploy_bond_token_contract( + issuer_address, issuer_private_key, ZERO_ADDRESS + ) _token_1 = Token() _token_1.type = "IbetCoupon" _token_1.tx_hash = "" diff --git a/tests/utils/contract_utils.py b/tests/utils/contract_utils.py index 08656d2f..9020e001 100644 --- a/tests/utils/contract_utils.py +++ b/tests/utils/contract_utils.py @@ -22,11 +22,7 @@ from web3.middleware import geth_poa_middleware from app.utils.contract_utils import ContractUtils -from config import ( - WEB3_HTTP_PROVIDER, - TX_GAS_LIMIT, - CHAIN_ID -) +from config import CHAIN_ID, TX_GAS_LIMIT, WEB3_HTTP_PROVIDER web3 = Web3(Web3.HTTPProvider(WEB3_HTTP_PROVIDER)) web3.middleware_onion.inject(geth_poa_middleware, layer=0) @@ -40,26 +36,18 @@ class PersonalInfoContractTestUtils: - @staticmethod def register(contract_address: str, tx_from: str, private_key: str, args: list): personal_info_contract = ContractUtils.get_contract( - contract_name="PersonalInfo", - contract_address=contract_address - ) - tx = personal_info_contract.functions. \ - register(*args). \ - build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + contract_name="PersonalInfo", contract_address=contract_address + ) + tx = personal_info_contract.functions.register(*args).build_transaction( + {"chainId": CHAIN_ID, "from": tx_from, "gas": TX_GAS_LIMIT, "gasPrice": 0} + ) ContractUtils.send_transaction(transaction=tx, private_key=private_key) class IbetStandardTokenUtils: - @staticmethod def issue(tx_from: str, private_key: str, args: Dict): """issue token @@ -76,17 +64,16 @@ def issue(tx_from: str, private_key: str, args: Dict): args["totalSupply"], args["tradableExchange"], args["contactInformation"], - args["privacyPolicy"] + args["privacyPolicy"], ] contract_address, abi, _ = ContractUtils.deploy_contract( contract_name="IbetStandardToken", args=arguments, deployer=tx_from, - private_key = private_key + private_key=private_key, ) contract = ContractUtils.get_contract( - contract_name="IbetStandardToken", - contract_address=contract_address + contract_name="IbetStandardToken", contract_address=contract_address ) return contract @@ -94,30 +81,24 @@ def issue(tx_from: str, private_key: str, args: Dict): def transfer(contract_address: str, tx_from: str, private_key: str, args: list): token_contract = ContractUtils.get_contract( contract_name="IbetStandardTokenInterface", - contract_address=contract_address - ) - tx = token_contract.functions.\ - transfer(*args).\ - build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + contract_address=contract_address, + ) + tx = token_contract.functions.transfer(*args).build_transaction( + {"chainId": CHAIN_ID, "from": tx_from, "gas": TX_GAS_LIMIT, "gasPrice": 0} + ) tx_hash, _ = ContractUtils.send_transaction( - transaction=tx, - private_key=private_key + transaction=tx, private_key=private_key ) return tx_hash -class IbetSecurityTokenContractTestUtils: +class IbetSecurityTokenContractTestUtils: @staticmethod def balance_of(contract_address: str, account_address: str): security_token_contract = ContractUtils.get_contract( contract_name="IbetSecurityTokenInterface", - contract_address=contract_address + contract_address=contract_address, ) return security_token_contract.functions.balanceOf(account_address).call() @@ -125,364 +106,281 @@ def balance_of(contract_address: str, account_address: str): def transfer(contract_address: str, tx_from: str, private_key: str, args: list): security_token_contract = ContractUtils.get_contract( contract_name="IbetSecurityTokenInterface", - contract_address=contract_address - ) - tx = security_token_contract.functions.\ - transfer(*args).\ - build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + contract_address=contract_address, + ) + tx = security_token_contract.functions.transfer(*args).build_transaction( + {"chainId": CHAIN_ID, "from": tx_from, "gas": TX_GAS_LIMIT, "gasPrice": 0} + ) ContractUtils.send_transaction(transaction=tx, private_key=private_key) @staticmethod - def bulk_transfer(contract_address: str, tx_from: str, private_key: str, args: list): + def bulk_transfer( + contract_address: str, tx_from: str, private_key: str, args: list + ): security_token_contract = ContractUtils.get_contract( contract_name="IbetSecurityTokenInterface", - contract_address=contract_address - ) - tx = security_token_contract.functions.\ - bulkTransfer(*args).\ - build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + contract_address=contract_address, + ) + tx = security_token_contract.functions.bulkTransfer(*args).build_transaction( + {"chainId": CHAIN_ID, "from": tx_from, "gas": TX_GAS_LIMIT, "gasPrice": 0} + ) ContractUtils.send_transaction(transaction=tx, private_key=private_key) @staticmethod def lock(contract_address: str, tx_from: str, private_key: str, args: list): security_token_contract = ContractUtils.get_contract( contract_name="IbetSecurityTokenInterface", - contract_address=contract_address - ) - tx = security_token_contract.functions.\ - lock(*args).\ - build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + contract_address=contract_address, + ) + tx = security_token_contract.functions.lock(*args).build_transaction( + {"chainId": CHAIN_ID, "from": tx_from, "gas": TX_GAS_LIMIT, "gasPrice": 0} + ) ContractUtils.send_transaction(transaction=tx, private_key=private_key) @staticmethod def unlock(contract_address: str, tx_from: str, private_key: str, args: list): security_token_contract = ContractUtils.get_contract( contract_name="IbetSecurityTokenInterface", - contract_address=contract_address - ) - tx = security_token_contract.functions.\ - unlock(*args).\ - build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + contract_address=contract_address, + ) + tx = security_token_contract.functions.unlock(*args).build_transaction( + {"chainId": CHAIN_ID, "from": tx_from, "gas": TX_GAS_LIMIT, "gasPrice": 0} + ) ContractUtils.send_transaction(transaction=tx, private_key=private_key) @staticmethod def issue_from(contract_address: str, tx_from: str, private_key: str, args: list): security_token_contract = ContractUtils.get_contract( contract_name="IbetSecurityTokenInterface", - contract_address=contract_address - ) - tx = security_token_contract.functions.\ - issueFrom(*args).\ - build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + contract_address=contract_address, + ) + tx = security_token_contract.functions.issueFrom(*args).build_transaction( + {"chainId": CHAIN_ID, "from": tx_from, "gas": TX_GAS_LIMIT, "gasPrice": 0} + ) ContractUtils.send_transaction(transaction=tx, private_key=private_key) @staticmethod def redeem_from(contract_address: str, tx_from: str, private_key: str, args: list): security_token_contract = ContractUtils.get_contract( contract_name="IbetSecurityTokenInterface", - contract_address=contract_address - ) - tx = security_token_contract.functions.\ - redeemFrom(*args).\ - build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + contract_address=contract_address, + ) + tx = security_token_contract.functions.redeemFrom(*args).build_transaction( + {"chainId": CHAIN_ID, "from": tx_from, "gas": TX_GAS_LIMIT, "gasPrice": 0} + ) ContractUtils.send_transaction(transaction=tx, private_key=private_key) @staticmethod - def set_transfer_approve_required(contract_address: str, tx_from: str, private_key: str, args: list): + def set_transfer_approve_required( + contract_address: str, tx_from: str, private_key: str, args: list + ): security_token_contract = ContractUtils.get_contract( contract_name="IbetSecurityTokenInterface", - contract_address=contract_address - ) - tx = security_token_contract.functions.\ - setTransferApprovalRequired(*args).\ - build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + contract_address=contract_address, + ) + tx = security_token_contract.functions.setTransferApprovalRequired( + *args + ).build_transaction( + {"chainId": CHAIN_ID, "from": tx_from, "gas": TX_GAS_LIMIT, "gasPrice": 0} + ) ContractUtils.send_transaction(transaction=tx, private_key=private_key) @staticmethod - def apply_for_transfer(contract_address: str, tx_from: str, private_key: str, args: list): + def apply_for_transfer( + contract_address: str, tx_from: str, private_key: str, args: list + ): security_token_contract = ContractUtils.get_contract( contract_name="IbetSecurityTokenInterface", - contract_address=contract_address - ) - tx = security_token_contract.functions.\ - applyForTransfer(*args).\ - build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + contract_address=contract_address, + ) + tx = security_token_contract.functions.applyForTransfer( + *args + ).build_transaction( + {"chainId": CHAIN_ID, "from": tx_from, "gas": TX_GAS_LIMIT, "gasPrice": 0} + ) ContractUtils.send_transaction(transaction=tx, private_key=private_key) @staticmethod - def cancel_transfer(contract_address: str, tx_from: str, private_key: str, args: list): + def cancel_transfer( + contract_address: str, tx_from: str, private_key: str, args: list + ): security_token_contract = ContractUtils.get_contract( contract_name="IbetSecurityTokenInterface", - contract_address=contract_address - ) - tx = security_token_contract.functions.\ - cancelTransfer(*args).\ - build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + contract_address=contract_address, + ) + tx = security_token_contract.functions.cancelTransfer(*args).build_transaction( + {"chainId": CHAIN_ID, "from": tx_from, "gas": TX_GAS_LIMIT, "gasPrice": 0} + ) ContractUtils.send_transaction(transaction=tx, private_key=private_key) @staticmethod - def approve_transfer(contract_address: str, tx_from: str, private_key: str, args: list): + def approve_transfer( + contract_address: str, tx_from: str, private_key: str, args: list + ): security_token_contract = ContractUtils.get_contract( contract_name="IbetSecurityTokenInterface", - contract_address=contract_address - ) - tx = security_token_contract.functions.\ - approveTransfer(*args).\ - build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + contract_address=contract_address, + ) + tx = security_token_contract.functions.approveTransfer(*args).build_transaction( + {"chainId": CHAIN_ID, "from": tx_from, "gas": TX_GAS_LIMIT, "gasPrice": 0} + ) ContractUtils.send_transaction(transaction=tx, private_key=private_key) class IbetExchangeContractTestUtils: - @staticmethod def balance_of(contract_address: str, account_address: str, token_address: str): exchange_contract = ContractUtils.get_contract( - contract_name="IbetExchange", - contract_address=contract_address + contract_name="IbetExchange", contract_address=contract_address ) - return exchange_contract.functions.balanceOf(account_address, token_address).call() + return exchange_contract.functions.balanceOf( + account_address, token_address + ).call() @staticmethod def create_order(contract_address: str, tx_from: str, private_key: str, args: list): exchange_contract = ContractUtils.get_contract( - contract_name="IbetExchange", - contract_address=contract_address - ) - tx = exchange_contract.functions.\ - createOrder(*args). \ - build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + contract_name="IbetExchange", contract_address=contract_address + ) + tx = exchange_contract.functions.createOrder(*args).build_transaction( + {"chainId": CHAIN_ID, "from": tx_from, "gas": TX_GAS_LIMIT, "gasPrice": 0} + ) ContractUtils.send_transaction(transaction=tx, private_key=private_key) @staticmethod def get_latest_order_id(contract_address: str): exchange_contract = ContractUtils.get_contract( - contract_name="IbetExchange", - contract_address=contract_address + contract_name="IbetExchange", contract_address=contract_address ) return exchange_contract.functions.latestOrderId().call() @staticmethod - def force_cancel_order(contract_address: str, tx_from: str, private_key: str, args: list): + def force_cancel_order( + contract_address: str, tx_from: str, private_key: str, args: list + ): exchange_contract = ContractUtils.get_contract( - contract_name="IbetExchange", - contract_address=contract_address - ) - tx = exchange_contract.functions. \ - forceCancelOrder(*args). \ - build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + contract_name="IbetExchange", contract_address=contract_address + ) + tx = exchange_contract.functions.forceCancelOrder(*args).build_transaction( + {"chainId": CHAIN_ID, "from": tx_from, "gas": TX_GAS_LIMIT, "gasPrice": 0} + ) ContractUtils.send_transaction(transaction=tx, private_key=private_key) @staticmethod def cancel_order(contract_address: str, tx_from: str, private_key: str, args: list): exchange_contract = ContractUtils.get_contract( - contract_name="IbetExchange", - contract_address=contract_address - ) - tx = exchange_contract.functions. \ - cancelOrder(*args). \ - build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + contract_name="IbetExchange", contract_address=contract_address + ) + tx = exchange_contract.functions.cancelOrder(*args).build_transaction( + {"chainId": CHAIN_ID, "from": tx_from, "gas": TX_GAS_LIMIT, "gasPrice": 0} + ) ContractUtils.send_transaction(transaction=tx, private_key=private_key) @staticmethod - def execute_order(contract_address: str, tx_from: str, private_key: str, args: list): + def execute_order( + contract_address: str, tx_from: str, private_key: str, args: list + ): exchange_contract = ContractUtils.get_contract( - contract_name="IbetExchange", - contract_address=contract_address - ) - tx = exchange_contract.functions. \ - executeOrder(*args). \ - build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + contract_name="IbetExchange", contract_address=contract_address + ) + tx = exchange_contract.functions.executeOrder(*args).build_transaction( + {"chainId": CHAIN_ID, "from": tx_from, "gas": TX_GAS_LIMIT, "gasPrice": 0} + ) ContractUtils.send_transaction(transaction=tx, private_key=private_key) @staticmethod def get_latest_agreementid(contract_address: str, order_id: int): exchange_contract = ContractUtils.get_contract( - contract_name="IbetExchange", - contract_address=contract_address + contract_name="IbetExchange", contract_address=contract_address ) return exchange_contract.functions.latestAgreementId(order_id).call() @staticmethod - def cancel_agreement(contract_address: str, tx_from: str, private_key: str, args: list): + def cancel_agreement( + contract_address: str, tx_from: str, private_key: str, args: list + ): exchange_contract = ContractUtils.get_contract( - contract_name="IbetExchange", - contract_address=contract_address - ) - tx = exchange_contract.functions. \ - cancelAgreement(*args). \ - build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + contract_name="IbetExchange", contract_address=contract_address + ) + tx = exchange_contract.functions.cancelAgreement(*args).build_transaction( + {"chainId": CHAIN_ID, "from": tx_from, "gas": TX_GAS_LIMIT, "gasPrice": 0} + ) ContractUtils.send_transaction(transaction=tx, private_key=private_key) @staticmethod - def confirm_agreement(contract_address: str, tx_from: str, private_key: str, args: list): + def confirm_agreement( + contract_address: str, tx_from: str, private_key: str, args: list + ): exchange_contract = ContractUtils.get_contract( - contract_name="IbetExchange", - contract_address=contract_address - ) - tx = exchange_contract.functions. \ - confirmAgreement(*args). \ - build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + contract_name="IbetExchange", contract_address=contract_address + ) + tx = exchange_contract.functions.confirmAgreement(*args).build_transaction( + {"chainId": CHAIN_ID, "from": tx_from, "gas": TX_GAS_LIMIT, "gasPrice": 0} + ) ContractUtils.send_transaction(transaction=tx, private_key=private_key) class IbetSecurityTokenEscrowContractTestUtils: - @staticmethod def balance_of(contract_address: str, account_address: str, token_address: str): escrow_contract = ContractUtils.get_contract( - contract_name="IbetSecurityTokenEscrow", - contract_address=contract_address + contract_name="IbetSecurityTokenEscrow", contract_address=contract_address ) - return escrow_contract.functions.balanceOf(account_address, token_address).call() + return escrow_contract.functions.balanceOf( + account_address, token_address + ).call() @staticmethod - def create_escrow(contract_address: str, tx_from: str, private_key: str, args: list): + def create_escrow( + contract_address: str, tx_from: str, private_key: str, args: list + ): escrow_contract = ContractUtils.get_contract( - contract_name="IbetSecurityTokenEscrow", - contract_address=contract_address - ) - tx = escrow_contract.functions.\ - createEscrow(*args). \ - build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + contract_name="IbetSecurityTokenEscrow", contract_address=contract_address + ) + tx = escrow_contract.functions.createEscrow(*args).build_transaction( + {"chainId": CHAIN_ID, "from": tx_from, "gas": TX_GAS_LIMIT, "gasPrice": 0} + ) ContractUtils.send_transaction(transaction=tx, private_key=private_key) @staticmethod - def cancel_escrow(contract_address: str, tx_from: str, private_key: str, args: list): + def cancel_escrow( + contract_address: str, tx_from: str, private_key: str, args: list + ): escrow_contract = ContractUtils.get_contract( - contract_name="IbetSecurityTokenEscrow", - contract_address=contract_address - ) - tx = escrow_contract.functions.\ - cancelEscrow(*args). \ - build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + contract_name="IbetSecurityTokenEscrow", contract_address=contract_address + ) + tx = escrow_contract.functions.cancelEscrow(*args).build_transaction( + {"chainId": CHAIN_ID, "from": tx_from, "gas": TX_GAS_LIMIT, "gasPrice": 0} + ) ContractUtils.send_transaction(transaction=tx, private_key=private_key) @staticmethod - def approve_transfer(contract_address: str, tx_from: str, private_key: str, args: list): + def approve_transfer( + contract_address: str, tx_from: str, private_key: str, args: list + ): escrow_contract = ContractUtils.get_contract( - contract_name="IbetSecurityTokenEscrow", - contract_address=contract_address - ) - tx = escrow_contract.functions.\ - approveTransfer(*args). \ - build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + contract_name="IbetSecurityTokenEscrow", contract_address=contract_address + ) + tx = escrow_contract.functions.approveTransfer(*args).build_transaction( + {"chainId": CHAIN_ID, "from": tx_from, "gas": TX_GAS_LIMIT, "gasPrice": 0} + ) ContractUtils.send_transaction(transaction=tx, private_key=private_key) @staticmethod - def finish_escrow(contract_address: str, tx_from: str, private_key: str, args: list): + def finish_escrow( + contract_address: str, tx_from: str, private_key: str, args: list + ): escrow_contract = ContractUtils.get_contract( - contract_name="IbetSecurityTokenEscrow", - contract_address=contract_address - ) - tx = escrow_contract.functions.\ - finishEscrow(*args). \ - build_transaction({ - "chainId": CHAIN_ID, - "from": tx_from, - "gas": TX_GAS_LIMIT, - "gasPrice": 0 - }) + contract_name="IbetSecurityTokenEscrow", contract_address=contract_address + ) + tx = escrow_contract.functions.finishEscrow(*args).build_transaction( + {"chainId": CHAIN_ID, "from": tx_from, "gas": TX_GAS_LIMIT, "gasPrice": 0} + ) ContractUtils.send_transaction(transaction=tx, private_key=private_key) @staticmethod def get_latest_escrow_id(contract_address: str): escrow_contract = ContractUtils.get_contract( - contract_name="IbetSecurityTokenEscrow", - contract_address=contract_address + contract_name="IbetSecurityTokenEscrow", contract_address=contract_address ) return escrow_contract.functions.latestEscrowId().call()