From 025a8c0445ccafc057d7e4dc920629400a3c55e0 Mon Sep 17 00:00:00 2001 From: GLEF1X Date: Mon, 11 Jul 2022 16:10:49 +0300 Subject: [PATCH] Combine `PlainAmount` and `AmountWithCurrency` into `Amount` to simplify API --- .../core/event_fetching/class_based/bill.py | 4 +- .../event_fetching/class_based/transaction.py | 4 +- glQiwiApi/qiwi/clients/p2p/client.py | 6 +-- .../qiwi/clients/p2p/methods/refund_bill.py | 6 +-- glQiwiApi/qiwi/clients/p2p/types.py | 10 ++--- glQiwiApi/qiwi/clients/wallet/client.py | 6 +-- .../wallet/methods/detect_mobile_number.py | 2 +- .../wallet/methods/payment_by_details.py | 4 +- .../qiwi/clients/wallet/types/account_info.py | 5 +-- .../qiwi/clients/wallet/types/balance.py | 5 +-- .../qiwi/clients/wallet/types/commission.py | 8 ++-- glQiwiApi/qiwi/clients/wallet/types/limit.py | 2 +- .../clients/wallet/types/mobile_operator.py | 2 +- glQiwiApi/qiwi/clients/wallet/types/other.py | 2 +- .../qiwi/clients/wallet/types/payment_info.py | 6 +-- .../qiwi/clients/wallet/types/qiwi_master.py | 10 ++--- glQiwiApi/qiwi/clients/wallet/types/stats.py | 6 +-- .../qiwi/clients/wallet/types/transaction.py | 8 ++-- .../qiwi/clients/wallet/types/webhooks.py | 8 ++-- glQiwiApi/qiwi/clients/wrapper.py | 8 ++-- glQiwiApi/types/amount.py | 37 ++++++++++--------- glQiwiApi/types/currency.py | 22 ----------- tests/conftest.py | 8 ++-- .../test_qiwi/test_clients/test_p2p_client.py | 4 +- .../test_qiwi/test_clients/test_wallet.py | 4 +- tests/unit/test_utils/test_currencies.py | 2 +- 26 files changed, 84 insertions(+), 105 deletions(-) delete mode 100644 glQiwiApi/types/currency.py diff --git a/glQiwiApi/core/event_fetching/class_based/bill.py b/glQiwiApi/core/event_fetching/class_based/bill.py index e9fa31e8..0c9560fd 100644 --- a/glQiwiApi/core/event_fetching/class_based/bill.py +++ b/glQiwiApi/core/event_fetching/class_based/bill.py @@ -5,7 +5,7 @@ from glQiwiApi.core.event_fetching.class_based.base import Handler from glQiwiApi.qiwi.clients.p2p.types import Bill -from glQiwiApi.types.amount import PlainAmount +from glQiwiApi.types.amount import Amount if TYPE_CHECKING: from glQiwiApi.qiwi.clients.p2p.client import QiwiP2PClient @@ -21,7 +21,7 @@ def bill_id(self) -> str: return self.event.id @property - def bill_sum(self) -> PlainAmount: + def bill_sum(self) -> Amount: return self.event.amount @property diff --git a/glQiwiApi/core/event_fetching/class_based/transaction.py b/glQiwiApi/core/event_fetching/class_based/transaction.py index d2295bfa..18ef74d8 100644 --- a/glQiwiApi/core/event_fetching/class_based/transaction.py +++ b/glQiwiApi/core/event_fetching/class_based/transaction.py @@ -4,7 +4,7 @@ from typing import TYPE_CHECKING, cast from glQiwiApi.qiwi.clients.wallet.types.transaction import Transaction -from glQiwiApi.types.amount import AmountWithCurrency +from glQiwiApi.types.amount import Amount from .base import Handler @@ -22,5 +22,5 @@ def transaction_id(self) -> int: return self.event.id @property - def transaction_sum(self) -> AmountWithCurrency: + def transaction_sum(self) -> Amount: return self.event.sum diff --git a/glQiwiApi/qiwi/clients/p2p/client.py b/glQiwiApi/qiwi/clients/p2p/client.py index 3076aef9..d64c1f7d 100644 --- a/glQiwiApi/qiwi/clients/p2p/client.py +++ b/glQiwiApi/qiwi/clients/p2p/client.py @@ -11,7 +11,7 @@ from glQiwiApi.qiwi.clients.p2p.methods.refund_bill import RefundBill from glQiwiApi.qiwi.clients.p2p.methods.reject_p2p_bill import RejectP2PBill from glQiwiApi.qiwi.clients.p2p.types import Bill, Customer, PairOfP2PKeys, RefundedBill -from glQiwiApi.types.amount import PlainAmount +from glQiwiApi.types.amount import Amount from glQiwiApi.utils.compat import remove_suffix from glQiwiApi.utils.deprecated import warn_deprecated from glQiwiApi.utils.validators import String @@ -105,7 +105,7 @@ async def get_bill_status(self, bill_id: str) -> str: :param bill_id: :return: status of bill """ - return (await self.get_bill_by_id(bill_id)).status.value + return (await self.get_bill_by_id(bill_id)).status.amount async def create_p2p_bill( self, @@ -175,7 +175,7 @@ async def refund_bill( self, bill_id: Union[str, int], refund_id: Union[str, int], - json_bill_data: Union[PlainAmount, Dict[str, Union[str, int]]], + json_bill_data: Union[Amount, Dict[str, Union[str, int]]], ) -> RefundedBill: """ The method allows you to make a refund on a paid invoice. diff --git a/glQiwiApi/qiwi/clients/p2p/methods/refund_bill.py b/glQiwiApi/qiwi/clients/p2p/methods/refund_bill.py index b7067834..9851d632 100644 --- a/glQiwiApi/qiwi/clients/p2p/methods/refund_bill.py +++ b/glQiwiApi/qiwi/clients/p2p/methods/refund_bill.py @@ -5,7 +5,7 @@ from glQiwiApi.core.abc.api_method import Request from glQiwiApi.qiwi.base import QiwiAPIMethod from glQiwiApi.qiwi.clients.p2p.types import RefundedBill -from glQiwiApi.types.amount import PlainAmount +from glQiwiApi.types.amount import Amount class RefundBill(QiwiAPIMethod[RefundedBill]): @@ -15,11 +15,11 @@ class RefundBill(QiwiAPIMethod[RefundedBill]): bill_id: str = Field(..., path_runtime_value=True) refund_id: str = Field(..., path_runtime_value=True) - json_bill_data: Union[PlainAmount, Dict[str, Union[str, int]]] + json_bill_data: Union[Amount, Dict[str, Union[str, int]]] def build_request(self, **url_format_kw: Any) -> 'Request': json_payload = self.json_bill_data - if isinstance(self.json_bill_data, PlainAmount): + if isinstance(self.json_bill_data, Amount): json_payload = self.json_bill_data.json(encoder=self.Config.json_dumps) # type: ignore return Request( diff --git a/glQiwiApi/qiwi/clients/p2p/types.py b/glQiwiApi/qiwi/clients/p2p/types.py index a84dcc79..f28489ea 100644 --- a/glQiwiApi/qiwi/clients/p2p/types.py +++ b/glQiwiApi/qiwi/clients/p2p/types.py @@ -8,7 +8,7 @@ from pydantic import BaseConfig, Extra, Field -from glQiwiApi.types.amount import HashablePlainAmount, PlainAmount +from glQiwiApi.types.amount import Amount, HashableAmount from glQiwiApi.types.base import HashableBase from glQiwiApi.types.exceptions import WebhookSignatureUnverifiedError @@ -20,7 +20,7 @@ class Customer(HashableBase): class BillStatus(HashableBase): - value: str + amount: str changed_datetime: Optional[datetime] = Field(None, alias='changedDateTime') @@ -39,7 +39,7 @@ class BillError(HashableBase): class Bill(HashableBase): - amount: HashablePlainAmount + amount: HashableAmount status: BillStatus site_id: str = Field(..., alias='siteId') id: str = Field(..., alias='billId') @@ -61,7 +61,7 @@ def invoice_uid(self) -> str: class RefundedBill(HashableBase): """object: RefundedBill""" - amount: PlainAmount + amount: Amount datetime: datetime refund_id: str = Field(..., alias='refundId') status: str @@ -85,7 +85,7 @@ def verify_signature(self, sha256_signature: str, secret_p2p_key: str) -> None: webhook_key = base64.b64decode(bytes(secret_p2p_key, 'utf-8')) bill = self.bill - invoice_params = f'{bill.amount.currency}|{bill.amount.value}|{bill.id}|{bill.site_id}|{bill.status.value}' + invoice_params = f'{bill.amount.currency}|{bill.amount.amount}|{bill.id}|{bill.site_id}|{bill.status.amount}' generated_signature = hmac.new( webhook_key, invoice_params.encode('utf-8'), hashlib.sha256 ).hexdigest() diff --git a/glQiwiApi/qiwi/clients/wallet/client.py b/glQiwiApi/qiwi/clients/wallet/client.py index 3acbb581..4aae2f6d 100644 --- a/glQiwiApi/qiwi/clients/wallet/client.py +++ b/glQiwiApi/qiwi/clients/wallet/client.py @@ -49,7 +49,7 @@ from glQiwiApi.qiwi.clients.wallet.methods.webhook.send_test_notification import ( SendTestWebhookNotification, ) -from glQiwiApi.types.amount import AmountWithCurrency +from glQiwiApi.types.amount import Amount from glQiwiApi.types.arbitrary import File from glQiwiApi.utils.validators import PhoneNumber, String @@ -381,7 +381,7 @@ async def get_list_of_balances(self) -> List[Balance]: GetBalances(), phone_number=self.phone_number_without_plus_sign ) - async def get_balance(self, *, account_number: int = 1) -> AmountWithCurrency: + async def get_balance(self, *, account_number: int = 1) -> Amount: resp: List[Balance] = await self._request_service.execute_api_method( GetBalances(), phone_number=self._phone_number, @@ -506,7 +506,7 @@ async def get_cross_rates(self) -> List[CrossRate]: async def payment_by_payment_details( self, - payment_sum: AmountWithCurrency, + payment_sum: Amount, payment_method: PaymentMethod, fields: PaymentDetails, payment_id: Optional[str] = None, diff --git a/glQiwiApi/qiwi/clients/wallet/methods/detect_mobile_number.py b/glQiwiApi/qiwi/clients/wallet/methods/detect_mobile_number.py index cd0f5013..4b1607d3 100644 --- a/glQiwiApi/qiwi/clients/wallet/methods/detect_mobile_number.py +++ b/glQiwiApi/qiwi/clients/wallet/methods/detect_mobile_number.py @@ -18,7 +18,7 @@ class DetectMobileNumber(QiwiAPIMethod[MobileOperator]): @classmethod def parse_http_response(cls, response: HTTPResponse) -> ReturningType: mobile_operator: MobileOperator = super().parse_http_response(response) - if mobile_operator.code.value == '2' or mobile_operator.code.name == 'ERROR': + if mobile_operator.code.amount == '2' or mobile_operator.code.name == 'ERROR': raise MobileOperatorCannotBeDeterminedError( response, custom_message=mobile_operator.message ) diff --git a/glQiwiApi/qiwi/clients/wallet/methods/payment_by_details.py b/glQiwiApi/qiwi/clients/wallet/methods/payment_by_details.py index e70558f0..520d0983 100644 --- a/glQiwiApi/qiwi/clients/wallet/methods/payment_by_details.py +++ b/glQiwiApi/qiwi/clients/wallet/methods/payment_by_details.py @@ -6,7 +6,7 @@ from glQiwiApi.core.abc.api_method import RuntimeValue from glQiwiApi.qiwi.base import QiwiAPIMethod from glQiwiApi.qiwi.clients.wallet.types import PaymentDetails, PaymentInfo, PaymentMethod -from glQiwiApi.types.amount import AmountWithCurrency +from glQiwiApi.types.amount import Amount class MakePaymentByDetails(QiwiAPIMethod[PaymentInfo]): @@ -20,7 +20,7 @@ class MakePaymentByDetails(QiwiAPIMethod[PaymentInfo]): 'fields': RuntimeValue(), } - payment_sum: AmountWithCurrency = Field(..., scheme_path='sum') + payment_sum: Amount = Field(..., scheme_path='sum') payment_method: PaymentMethod = Field(..., scheme_path='paymentMethod') details: PaymentDetails = Field(..., scheme_path='fields') payment_id: Optional[str] = Field(None, scheme_path='id') diff --git a/glQiwiApi/qiwi/clients/wallet/types/account_info.py b/glQiwiApi/qiwi/clients/wallet/types/account_info.py index 1191e094..34c64f5a 100644 --- a/glQiwiApi/qiwi/clients/wallet/types/account_info.py +++ b/glQiwiApi/qiwi/clients/wallet/types/account_info.py @@ -4,9 +4,8 @@ from pydantic import Field -from glQiwiApi.types.amount import AmountWithCurrency +from glQiwiApi.types.amount import Amount, Currency from glQiwiApi.types.base import Base -from glQiwiApi.types.currency import Currency class PassInfo(Base): @@ -48,7 +47,7 @@ class AuthInfo(Base): class SmsNotification(Base): """object: SmsNotification""" - price: AmountWithCurrency + price: Amount enabled: bool active: bool end_date: Optional[datetime] = Field(None, alias='endDate') diff --git a/glQiwiApi/qiwi/clients/wallet/types/balance.py b/glQiwiApi/qiwi/clients/wallet/types/balance.py index 4b06a64e..6666dc5f 100644 --- a/glQiwiApi/qiwi/clients/wallet/types/balance.py +++ b/glQiwiApi/qiwi/clients/wallet/types/balance.py @@ -2,9 +2,8 @@ from pydantic import Field -from glQiwiApi.types.amount import AmountWithCurrency +from glQiwiApi.types.amount import Amount, Currency from glQiwiApi.types.base import HashableBase -from glQiwiApi.types.currency import Currency class AvailableBalance(HashableBase): @@ -20,7 +19,7 @@ class Balance(HashableBase): fs_alias: str = Field(alias='fsAlias') bank_alias: str = Field(alias='bankAlias') has_balance: bool = Field(alias='hasBalance') - balance: Optional[AmountWithCurrency] = None + balance: Optional[Amount] = None currency: Currency account_type: Optional[Dict[str, Any]] = Field(None, alias='type') is_default_account: bool = Field(alias='defaultAccount') diff --git a/glQiwiApi/qiwi/clients/wallet/types/commission.py b/glQiwiApi/qiwi/clients/wallet/types/commission.py index 18228928..1d6aab28 100644 --- a/glQiwiApi/qiwi/clients/wallet/types/commission.py +++ b/glQiwiApi/qiwi/clients/wallet/types/commission.py @@ -1,12 +1,12 @@ from pydantic import Field -from glQiwiApi.types.amount import AmountWithCurrency +from glQiwiApi.types.amount import Amount from glQiwiApi.types.base import Base class Commission(Base): provider_id: int = Field(alias='providerId') - withdraw_sum: AmountWithCurrency = Field(alias='withdrawSum') - enrollment_sum: AmountWithCurrency = Field(alias='enrollmentSum') - qiwi_commission: AmountWithCurrency = Field(alias='qwCommission') + withdraw_sum: Amount = Field(alias='withdrawSum') + enrollment_sum: Amount = Field(alias='enrollmentSum') + qiwi_commission: Amount = Field(alias='qwCommission') withdraw_to_enrollment_rate: int = Field(alias='withdrawToEnrollmentRate') diff --git a/glQiwiApi/qiwi/clients/wallet/types/limit.py b/glQiwiApi/qiwi/clients/wallet/types/limit.py index 8827c859..a0505836 100644 --- a/glQiwiApi/qiwi/clients/wallet/types/limit.py +++ b/glQiwiApi/qiwi/clients/wallet/types/limit.py @@ -3,8 +3,8 @@ from pydantic import Field +from glQiwiApi.types.amount import Currency from glQiwiApi.types.base import Base -from glQiwiApi.types.currency import Currency class Interval(Base): diff --git a/glQiwiApi/qiwi/clients/wallet/types/mobile_operator.py b/glQiwiApi/qiwi/clients/wallet/types/mobile_operator.py index 2d80781b..efa4ee2a 100644 --- a/glQiwiApi/qiwi/clients/wallet/types/mobile_operator.py +++ b/glQiwiApi/qiwi/clients/wallet/types/mobile_operator.py @@ -6,7 +6,7 @@ class Code(Base): - value: str + amount: str name: str = Field(..., alias='_name') diff --git a/glQiwiApi/qiwi/clients/wallet/types/other.py b/glQiwiApi/qiwi/clients/wallet/types/other.py index c4f40875..55e35a9f 100644 --- a/glQiwiApi/qiwi/clients/wallet/types/other.py +++ b/glQiwiApi/qiwi/clients/wallet/types/other.py @@ -1,7 +1,7 @@ from pydantic import Field +from glQiwiApi.types.amount import Currency from glQiwiApi.types.base import Base, HashableBase -from glQiwiApi.types.currency import Currency class CrossRate(HashableBase): diff --git a/glQiwiApi/qiwi/clients/wallet/types/payment_info.py b/glQiwiApi/qiwi/clients/wallet/types/payment_info.py index 279443fd..ab9c89c5 100644 --- a/glQiwiApi/qiwi/clients/wallet/types/payment_info.py +++ b/glQiwiApi/qiwi/clients/wallet/types/payment_info.py @@ -2,7 +2,7 @@ from pydantic import Field -from glQiwiApi.types.amount import AmountWithCurrency +from glQiwiApi.types.amount import Amount from glQiwiApi.types.base import Base @@ -29,7 +29,7 @@ class PaymentInfo(Base): """object: PaymentInfo""" id: int - amount: AmountWithCurrency = Field(..., alias='sum') + amount: Amount = Field(..., alias='sum') terms: str fields: Fields source: str @@ -44,7 +44,7 @@ class PaymentMethod(Base): class QiwiPayment(Base): id: int - sum: AmountWithCurrency + sum: Amount method: PaymentMethod = Field(..., alias='paymentMethod') fields: Dict[Any, Any] comment: Optional[str] = None diff --git a/glQiwiApi/qiwi/clients/wallet/types/qiwi_master.py b/glQiwiApi/qiwi/clients/wallet/types/qiwi_master.py index 6204ac9c..315ee391 100644 --- a/glQiwiApi/qiwi/clients/wallet/types/qiwi_master.py +++ b/glQiwiApi/qiwi/clients/wallet/types/qiwi_master.py @@ -5,7 +5,7 @@ from pydantic import Field -from glQiwiApi.types.amount import AmountWithCurrency +from glQiwiApi.types.amount import Amount from glQiwiApi.types.base import Base, HashableBase @@ -19,7 +19,7 @@ class OrderDetails(Base): order_id: str = Field(..., alias='id') card_alias: str = Field(..., alias='cardAlias') status: str - price: Optional[AmountWithCurrency] = None + price: Optional[Amount] = None card_id: Optional[str] = Field(alias='cardId', default=None) @@ -42,7 +42,7 @@ class CardCredentials(Base): class Requisite(Base): name: str - value: str + amount: str class Details(Base): @@ -58,7 +58,7 @@ class CardInfo(Base): id_: int = Field(..., alias='id') name: str alias: str - price: AmountWithCurrency + price: Amount period: str type_: str = Field(..., alias='type') details: Details @@ -66,5 +66,5 @@ class CardInfo(Base): class Card(HashableBase): details: CardCredentials = Field(..., alias='qvx') - balance: Optional[AmountWithCurrency] = None + balance: Optional[Amount] = None info: CardInfo diff --git a/glQiwiApi/qiwi/clients/wallet/types/stats.py b/glQiwiApi/qiwi/clients/wallet/types/stats.py index aa29834a..b4c1fe39 100644 --- a/glQiwiApi/qiwi/clients/wallet/types/stats.py +++ b/glQiwiApi/qiwi/clients/wallet/types/stats.py @@ -2,15 +2,15 @@ from pydantic import Field -from glQiwiApi.types.amount import AmountWithCurrency +from glQiwiApi.types.amount import Amount from glQiwiApi.types.base import Base class Statistic(Base): """object: Statistic""" - incoming: List[AmountWithCurrency] = Field(alias='incomingTotal') - out: List[AmountWithCurrency] = Field(alias='outgoingTotal') + incoming: List[Amount] = Field(alias='incomingTotal') + out: List[Amount] = Field(alias='outgoingTotal') __all__ = ['Statistic'] diff --git a/glQiwiApi/qiwi/clients/wallet/types/transaction.py b/glQiwiApi/qiwi/clients/wallet/types/transaction.py index b450efd8..2fc1f006 100644 --- a/glQiwiApi/qiwi/clients/wallet/types/transaction.py +++ b/glQiwiApi/qiwi/clients/wallet/types/transaction.py @@ -6,7 +6,7 @@ from pydantic import Field -from glQiwiApi.types.amount import AmountWithCurrency +from glQiwiApi.types.amount import Amount from glQiwiApi.types.base import Base @@ -100,13 +100,13 @@ class Transaction(Base): Для пополнений - номер отправителя, терминала или название агента пополнения кошелька """ - sum: AmountWithCurrency + sum: Amount """Данные о сумме платежа или пополнения.""" - commission: AmountWithCurrency + commission: Amount """Данные о комиссии""" - total: AmountWithCurrency + total: Amount """Общие данные о платеже в формате объекта Sum""" provider: Provider diff --git a/glQiwiApi/qiwi/clients/wallet/types/webhooks.py b/glQiwiApi/qiwi/clients/wallet/types/webhooks.py index 3dd7f887..9def24b4 100644 --- a/glQiwiApi/qiwi/clients/wallet/types/webhooks.py +++ b/glQiwiApi/qiwi/clients/wallet/types/webhooks.py @@ -7,7 +7,7 @@ from pydantic import Field, root_validator -from glQiwiApi.types.amount import HashableSum +from glQiwiApi.types.amount import HashableAmount from glQiwiApi.types.base import Base, HashableBase from glQiwiApi.types.exceptions import WebhookSignatureUnverifiedError @@ -25,9 +25,9 @@ class WebhookPayment(HashableBase): status: str = Field(..., alias='status') txn_id: str = Field(..., alias='txnId') type: str = Field(..., alias='type') - commission: Optional[HashableSum] = Field(default=None, alias='calc_commission') - sum: HashableSum = Field(..., alias='sum') - total: HashableSum = Field(..., alias='total') + commission: Optional[HashableAmount] = Field(default=None, alias='calc_commission') + sum: HashableAmount = Field(..., alias='sum') + total: HashableAmount = Field(..., alias='total') class TransactionWebhook(HashableBase): diff --git a/glQiwiApi/qiwi/clients/wrapper.py b/glQiwiApi/qiwi/clients/wrapper.py index b78036f0..ee0fa914 100644 --- a/glQiwiApi/qiwi/clients/wrapper.py +++ b/glQiwiApi/qiwi/clients/wrapper.py @@ -35,7 +35,7 @@ from glQiwiApi.qiwi.clients.wallet.types.balance import AvailableBalance from glQiwiApi.qiwi.clients.wallet.types.mobile_operator import MobileOperator from glQiwiApi.qiwi.clients.wallet.types.nickname import NickName -from glQiwiApi.types.amount import AmountWithCurrency, PlainAmount +from glQiwiApi.types.amount import Amount from glQiwiApi.types.arbitrary import File from glQiwiApi.utils.deprecated import deprecated @@ -58,7 +58,7 @@ def __init__( self._qiwi_wallet = QiwiWallet(api_access_token or '', phone_number) self._p2p_client = QiwiP2PClient(secret_p2p or '', shim_server_url=shim_server_url) - async def get_balance(self, *, account_number: int = 1) -> AmountWithCurrency: + async def get_balance(self, *, account_number: int = 1) -> Amount: return await self._qiwi_wallet.get_balance(account_number=account_number) async def get_nickname(self) -> NickName: @@ -394,7 +394,7 @@ async def get_cross_rates(self) -> List[CrossRate]: async def payment_by_payment_details( self, - payment_sum: AmountWithCurrency, + payment_sum: Amount, payment_method: PaymentMethod, fields: PaymentDetails, payment_id: Optional[str] = None, @@ -605,7 +605,7 @@ async def refund_bill( self, bill_id: Union[str, int], refund_id: Union[str, int], - json_bill_data: Union[PlainAmount, Dict[str, Union[str, int]]], + json_bill_data: Union[Amount, Dict[str, Union[str, int]]], ) -> RefundedBill: """ The method allows you to make a refund on a paid invoice. diff --git a/glQiwiApi/types/amount.py b/glQiwiApi/types/amount.py index e14b35ea..9b2133d3 100644 --- a/glQiwiApi/types/amount.py +++ b/glQiwiApi/types/amount.py @@ -1,27 +1,30 @@ -from pydantic import BaseModel +import inspect +from typing import Any, Dict, cast + +from iso4217 import Currency as _Currency +from iso4217 import find_currency +from pydantic import root_validator from glQiwiApi.types.base import Base, HashableBase -from glQiwiApi.types.currency import Currency -class AmountWithCurrency(Base): - amount: float - currency: Currency +class Currency(HashableBase, _Currency): + __root__: int - -class HashableSum(HashableBase, AmountWithCurrency): - pass + @root_validator(skip_on_failure=True) + def humanize(cls, values: Dict[str, Any]) -> Dict[str, Any]: + currency_numeric_code: int = cast(int, values.get('__root__')) + # inspect.getfullargspec(_Currency.__init__) will contain `self`, + # so we cut it off and get original currency cls's constructor input names + args = inspect.getfullargspec(_Currency.__init__).args[1:] + currency = find_currency(numeric_code=currency_numeric_code) + return {k: getattr(currency, k, None) for k in args} -class PlainAmount(BaseModel): - value: float - currency: str +class Amount(Base): + amount: float + currency: Currency -class HashablePlainAmount(HashableBase, PlainAmount): +class HashableAmount(Amount, HashableBase): pass - - -class Type(BaseModel): - id: str - title: str diff --git a/glQiwiApi/types/currency.py b/glQiwiApi/types/currency.py deleted file mode 100644 index ebfb39e6..00000000 --- a/glQiwiApi/types/currency.py +++ /dev/null @@ -1,22 +0,0 @@ -import inspect -from typing import Any, Dict, cast - -from iso4217 import Currency as _Currency -from iso4217 import find_currency -from pydantic import root_validator - -from glQiwiApi.types.base import HashableBase - - -class Currency(HashableBase, _Currency): - __root__: int - - @root_validator(skip_on_failure=True) - def humanize(cls, values: Dict[str, Any]) -> Dict[str, Any]: - currency_numeric_code: int = cast(int, values.get('__root__')) - # inspect.getfullargspec(_Currency.__init__) will contain `self`, so we cut it off - orig_currency_cls_dunder_init_arg_names = inspect.getfullargspec(_Currency.__init__).args[ - 1: - ] - currency = find_currency(numeric_code=currency_numeric_code) - return {k: getattr(currency, k, None) for k in orig_currency_cls_dunder_init_arg_names} diff --git a/tests/conftest.py b/tests/conftest.py index f22f5256..b64ae5c5 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -4,7 +4,7 @@ from glQiwiApi.qiwi.clients.wallet.types import Transaction, TransactionStatus, TransactionWebhook from glQiwiApi.qiwi.clients.wallet.types.transaction import Provider, TransactionType -from glQiwiApi.types.amount import AmountWithCurrency +from glQiwiApi.types.amount import Amount @pytest.fixture() @@ -17,10 +17,10 @@ def transaction() -> Transaction: statusText='hello', trmTxnId='world', account='+38908234234', - sum=AmountWithCurrency(amount=999, currency='643'), - total=AmountWithCurrency(amount=999, currency='643'), + sum=Amount(amount=999, currency='643'), + total=Amount(amount=999, currency='643'), provider=Provider(), - commission=AmountWithCurrency(amount=999, currency='643'), + commission=Amount(amount=999, currency='643'), currencyRate=643, type=TransactionType.OUT, comment='my_comment', diff --git a/tests/integration/test_qiwi/test_clients/test_p2p_client.py b/tests/integration/test_qiwi/test_clients/test_p2p_client.py index a95286a0..656d49d3 100644 --- a/tests/integration/test_qiwi/test_clients/test_p2p_client.py +++ b/tests/integration/test_qiwi/test_clients/test_p2p_client.py @@ -38,7 +38,7 @@ async def api_fixture() -> AsyncIterator[QiwiP2PClient]: async def test_create_p2p_bill(api: QiwiP2PClient, payload: Dict[str, Any]) -> None: result = await api.create_p2p_bill(**payload) assert isinstance(result, Bill) - assert payload['amount'] == result.amount.value + assert payload['amount'] == result.amount.amount async def test_check_p2p_bill_status(api: QiwiP2PClient) -> None: @@ -69,7 +69,7 @@ async def test_reject_p2p_bill(api: QiwiP2PClient) -> None: async def test_reject_bill_alias(api: QiwiP2PClient) -> None: b = await api.create_p2p_bill(amount=1) rejected_bill = await api.reject_bill(b) - assert rejected_bill.status.value == 'REJECTED' + assert rejected_bill.status.amount == 'REJECTED' async def test_check_bill_status_alias(api: QiwiP2PClient) -> None: diff --git a/tests/integration/test_qiwi/test_clients/test_wallet.py b/tests/integration/test_qiwi/test_clients/test_wallet.py index fef99695..1580fef3 100644 --- a/tests/integration/test_qiwi/test_clients/test_wallet.py +++ b/tests/integration/test_qiwi/test_clients/test_wallet.py @@ -28,7 +28,7 @@ from glQiwiApi.qiwi.clients.wallet.types.balance import AvailableBalance from glQiwiApi.qiwi.clients.wallet.types.nickname import NickName from glQiwiApi.qiwi.exceptions import MobileOperatorCannotBeDeterminedError, ObjectNotFoundError -from glQiwiApi.types.amount import AmountWithCurrency, CurrencyModel +from glQiwiApi.types.amount import Amount, CurrencyModel from glQiwiApi.types.arbitrary import File from tests.settings import QIWI_WALLET_CREDENTIALS @@ -50,7 +50,7 @@ async def api_fixture() -> AsyncIterator[QiwiWallet]: async def test_get_balance(api: QiwiWallet) -> None: result = await api.get_balance() - assert isinstance(result, AmountWithCurrency) + assert isinstance(result, Amount) assert isinstance(result.currency, CurrencyModel) diff --git a/tests/unit/test_utils/test_currencies.py b/tests/unit/test_utils/test_currencies.py index 660ed2e9..20b86584 100644 --- a/tests/unit/test_utils/test_currencies.py +++ b/tests/unit/test_utils/test_currencies.py @@ -1,7 +1,7 @@ import pytest from iso4217 import CurrencyNotFoundError -from glQiwiApi.types.currency import Currency +from glQiwiApi.types.amount import Currency def test_currency_from_code() -> None: