Skip to content

Commit

Permalink
Refactor #28
Browse files Browse the repository at this point in the history
  • Loading branch information
GLEF1X committed Jul 11, 2022
1 parent ea9d3f7 commit 547c3b9
Show file tree
Hide file tree
Showing 31 changed files with 46 additions and 49 deletions.
5 changes: 4 additions & 1 deletion benchmarks/p2p/test_performance.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# pip install pytest-benchmark pyqiwip2p
import os
from typing import Any, Callable, Dict, Tuple

import pytest
from pyqiwip2p.AioQiwip2p import AioQiwiP2P
Expand All @@ -26,7 +27,9 @@ async def create_bill_with_pyQiwiP2P():


@pytest.fixture()
def aio_benchmark(benchmark: BenchmarkFixture) -> BenchmarkFixture:
def aio_benchmark(
benchmark: BenchmarkFixture,
) -> Callable[[Any, Tuple[Any, ...], Dict[str, Any]], None]:
import asyncio
import threading

Expand Down
2 changes: 1 addition & 1 deletion glQiwiApi/core/event_fetching/class_based/bill.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def bill_id(self) -> str:

@property
def bill_sum(self) -> Amount:
return self.event.amount
return self.event.value

@property
def pay_url(self) -> str:
Expand Down
2 changes: 1 addition & 1 deletion glQiwiApi/core/event_fetching/dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def __init__(self) -> None:

async def process_event(self, event: Event, *args: Any) -> None:
"""
Feed handlers withf\\ event.
Feed handlers with event.
:param event: any object that will be propagated to handlers
"""
Expand Down
2 changes: 1 addition & 1 deletion glQiwiApi/core/event_fetching/webhooks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@
from . import app # noqa
from .views import QiwiBillWebhookView, QiwiTransactionWebhookView

__all__ = ('QiwiBillWebhookView', 'QiwiTransactionWebhookView', 'BaseWebhookView', 'app.py')
__all__ = ('QiwiBillWebhookView', 'QiwiTransactionWebhookView', 'BaseWebhookView', 'app')
2 changes: 1 addition & 1 deletion glQiwiApi/core/session/holder.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import abc
from dataclasses import dataclass
from types import TracebackType
from typing import Any, Dict, Generic, Mapping, Optional, Set, Type, TypeVar, cast
from typing import Any, Dict, Generic, Mapping, Optional, Type, TypeVar, cast

import aiohttp
from aiohttp import ClientResponse
Expand Down
2 changes: 1 addition & 1 deletion glQiwiApi/qiwi/clients/p2p/methods/create_p2p_bill.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import uuid
from datetime import datetime, timedelta
from typing import Any, ClassVar, Dict, List, Optional, Union
from typing import Any, ClassVar, Dict, List, Optional

from pydantic import Field, validator

Expand Down
10 changes: 5 additions & 5 deletions glQiwiApi/qiwi/clients/p2p/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class Customer(HashableBase):


class BillStatus(HashableBase):
amount: str
value: str
changed_datetime: Optional[datetime] = Field(None, alias='changedDateTime')


Expand Down Expand Up @@ -61,13 +61,13 @@ def invoice_uid(self) -> str:
class RefundedBill(HashableBase):
"""object: RefundedBill"""

amount: Amount
value: Amount
datetime: datetime
refund_id: str = Field(..., alias='refundId')
status: str

def __str__(self) -> str:
return f'№{self.refund_id} {self.status} {self.amount} {self.datetime}'
return f'№{self.refund_id} {self.status} {self.value} {self.datetime}'


class BillWebhookPayload(Bill):
Expand All @@ -79,13 +79,13 @@ class BillWebhook(HashableBase):
bill: BillWebhookPayload = Field(..., alias='bill')

def __repr__(self) -> str:
return f'#{self.bill.id} {self.bill.amount} {self.bill.status} '
return f'#{self.bill.id} {self.bill.value} {self.bill.status} '

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.amount}|{bill.id}|{bill.site_id}|{bill.status.amount}'
invoice_params = f'{bill.value.currency}|{bill.value.value}|{bill.id}|{bill.site_id}|{bill.status.value}'
generated_signature = hmac.new(
webhook_key, invoice_params.encode('utf-8'), hashlib.sha256
).hexdigest()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, ClassVar, Dict, Optional
from typing import Any, ClassVar, Dict

from pydantic import Field

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.amount == '2' or mobile_operator.code.name == 'ERROR':
if mobile_operator.code.value == '2' or mobile_operator.code.name == 'ERROR':
raise MobileOperatorCannotBeDeterminedError(
response, custom_message=mobile_operator.message
)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from typing import ClassVar, List

from glQiwiApi.qiwi.base import QiwiAPIMethod
from glQiwiApi.qiwi.clients.wallet.types import Balance
from glQiwiApi.qiwi.clients.wallet.types.balance import AvailableBalance


Expand Down
1 change: 0 additions & 1 deletion glQiwiApi/qiwi/clients/wallet/methods/get_balances.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

from pydantic import parse_obj_as

from glQiwiApi.core.abc.api_method import ReturningType
from glQiwiApi.core.session.holder import HTTPResponse
from glQiwiApi.qiwi.base import QiwiAPIMethod
from glQiwiApi.qiwi.clients.wallet.types import Balance
Expand Down
1 change: 0 additions & 1 deletion glQiwiApi/qiwi/clients/wallet/methods/get_cross_rates.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

from pydantic import parse_obj_as

from glQiwiApi.core.abc.api_method import ReturningType
from glQiwiApi.core.session.holder import HTTPResponse
from glQiwiApi.qiwi.base import QiwiAPIMethod
from glQiwiApi.qiwi.clients.wallet.types import CrossRate
Expand Down
4 changes: 2 additions & 2 deletions glQiwiApi/qiwi/clients/wallet/methods/get_limits.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from typing import Any, ClassVar, Dict, List, Sequence
from typing import Any, ClassVar, Dict, Sequence

from glQiwiApi.core.abc.api_method import Request, ReturningType
from glQiwiApi.core.abc.api_method import Request
from glQiwiApi.core.session.holder import HTTPResponse
from glQiwiApi.qiwi.base import QiwiAPIMethod
from glQiwiApi.qiwi.clients.wallet.types import Limit
Expand Down
2 changes: 1 addition & 1 deletion glQiwiApi/qiwi/clients/wallet/methods/predict_comission.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, ClassVar, Dict, Optional, Union
from typing import Any, ClassVar, Dict, Union

from pydantic import Field

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

from pydantic import Field

from glQiwiApi.core.abc.api_method import ReturningType
from glQiwiApi.core.session.holder import HTTPResponse
from glQiwiApi.qiwi.base import QiwiAPIMethod

Expand Down
4 changes: 1 addition & 3 deletions glQiwiApi/qiwi/clients/wallet/methods/reveal_card_id.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
from json import JSONDecodeError
from typing import Any, ClassVar

from pydantic import Field

from glQiwiApi.core.abc.api_method import Request, ReturningType
from glQiwiApi.core.abc.api_method import Request
from glQiwiApi.core.session.holder import HTTPResponse
from glQiwiApi.qiwi.base import QiwiAPIMethod
from glQiwiApi.qiwi.exceptions import QiwiAPIError

try:
from orjson import JSONDecodeError as OrjsonDecodeError
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import time
from typing import Any, ClassVar, Dict, Union
from typing import Any, ClassVar, Dict

from pydantic import Field

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

from pydantic import Field

from glQiwiApi.core.abc.api_method import ReturningType
from glQiwiApi.core.session.holder import HTTPResponse
from glQiwiApi.qiwi.base import QiwiAPIMethod

Expand Down
2 changes: 1 addition & 1 deletion glQiwiApi/qiwi/clients/wallet/types/mobile_operator.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@


class Code(Base):
amount: str
value: str
name: str = Field(..., alias='_name')


Expand Down
2 changes: 1 addition & 1 deletion glQiwiApi/qiwi/clients/wallet/types/payment_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class PaymentInfo(Base):
"""object: PaymentInfo"""

id: int
amount: Amount = Field(..., alias='sum')
value: Amount = Field(..., alias='sum')
terms: str
fields: Fields
source: str
Expand Down
4 changes: 2 additions & 2 deletions glQiwiApi/qiwi/clients/wallet/types/qiwi_master.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ class CardCredentials(Base):


class Requisite(Base):
name: str
amount: str
value: str
value: str


class Details(Base):
Expand Down
2 changes: 1 addition & 1 deletion glQiwiApi/qiwi/clients/wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ async def check_transaction(
"""

def obsolete_check_transaction(txn: Transaction) -> bool:
if txn.sum.amount < amount or txn.type != transaction_type.value:
if txn.sum.value < amount or txn.type != transaction_type.value:
return False
if txn.comment == comment and txn.to_account == sender:
return True
Expand Down
2 changes: 1 addition & 1 deletion glQiwiApi/types/amount.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def humanize(cls, values: Dict[str, Any]) -> Dict[str, Any]:


class Amount(Base):
amount: float
value: float
currency: Currency


Expand Down
1 change: 0 additions & 1 deletion glQiwiApi/utils/certificates.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
from dataclasses import dataclass
from datetime import datetime, timedelta
from io import BytesIO
from os import PathLike
from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Union, cast

if TYPE_CHECKING:
Expand Down
2 changes: 1 addition & 1 deletion glQiwiApi/yoo_money/methods/get_access_token.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from typing import ClassVar, Optional

from glQiwiApi.core.abc.api_method import APIMethod, ReturningType
from glQiwiApi.core.abc.api_method import APIMethod
from glQiwiApi.core.session.holder import HTTPResponse


Expand Down
2 changes: 1 addition & 1 deletion glQiwiApi/yoo_money/types/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ def _extract_amount_and_comment_by_operation_type(

id: str = Field(..., alias='operation_id')
status: str
amount: float
value: float
amount_due: Optional[float] = None
currency: str = Field(..., alias='amount_currency')
operation_date: datetime = Field(..., alias='datetime')
Expand Down
6 changes: 3 additions & 3 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ def transaction() -> Transaction:
statusText='hello',
trmTxnId='world',
account='+38908234234',
sum=Amount(amount=999, currency='643'),
total=Amount(amount=999, currency='643'),
sum=Amount(value=999, currency='643'),
total=Amount(value=999, currency='643'),
provider=Provider(),
commission=Amount(amount=999, currency='643'),
commission=Amount(value=999, currency='643'),
currencyRate=643,
type=TransactionType.OUT,
comment='my_comment',
Expand Down
4 changes: 2 additions & 2 deletions tests/integration/test_qiwi/test_clients/test_p2p_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.amount
assert payload['amount'] == result.value.value


async def test_check_p2p_bill_status(api: QiwiP2PClient) -> None:
Expand Down Expand Up @@ -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.amount == 'REJECTED'
assert rejected_bill.status.value == 'REJECTED'


async def test_check_bill_status_alias(api: QiwiP2PClient) -> None:
Expand Down
4 changes: 2 additions & 2 deletions tests/integration/test_qiwi/test_clients/test_wallet.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 Amount, CurrencyModel
from glQiwiApi.types.amount import Amount, Currency
from glQiwiApi.types.arbitrary import File
from tests.settings import QIWI_WALLET_CREDENTIALS

Expand All @@ -51,7 +51,7 @@ async def api_fixture() -> AsyncIterator[QiwiWallet]:
async def test_get_balance(api: QiwiWallet) -> None:
result = await api.get_balance()
assert isinstance(result, Amount)
assert isinstance(result.currency, CurrencyModel)
assert isinstance(result.currency, Currency)


def test_create_request_service() -> None:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import asyncio
import json
import logging
from asyncio import AbstractEventLoop

Expand Down Expand Up @@ -83,11 +82,11 @@ async def test_with_invalid_payload(
**txn.payment.dict(by_alias=True),
'sum': {
'currency': txn.payment.sum.currency.numeric_code,
'amount': txn.payment.sum.amount,
'amount': txn.payment.sum.value,
},
'total': {
'currency': txn.payment.sum.currency.numeric_code,
'amount': txn.payment.sum.amount,
'amount': txn.payment.sum.value,
},
},
'hookId': txn.id,
Expand Down
13 changes: 8 additions & 5 deletions tests/unit/test_utils/test_certificates.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import pathlib
import ssl

from py.path import local
Expand All @@ -10,7 +11,9 @@ def test_generate_self_signed_certificates(tmpdir: local) -> None:
path_to_cert = tmpdir.join('cert.pem')
path_to_pkey = tmpdir.join('pkey.pem')
get_or_generate_self_signed_certificate(
hostname='45.138.24.80', cert_path=path_to_cert, pkey_path=path_to_pkey
hostname='45.138.24.80',
cert_path=pathlib.Path(path_to_cert),
pkey_path=pathlib.Path(path_to_pkey),
)
assert path_to_cert.isfile() is True
assert path_to_pkey.isfile() is True
Expand All @@ -20,8 +23,8 @@ def test_get_ssl_context(tmpdir: local) -> None:
tmpdir.mkdir('certificates')
ssl_certificate = get_or_generate_self_signed_certificate(
hostname='45.138.24.80',
cert_path=tmpdir.join('cert.pem'),
pkey_path=tmpdir.join('pkey.pem'),
cert_path=pathlib.Path(tmpdir.join('cert.pem')),
pkey_path=pathlib.Path(tmpdir.join('pkey.pem')),
)
context = ssl_certificate.as_ssl_context()
assert isinstance(context, ssl.SSLContext)
Expand All @@ -31,8 +34,8 @@ def test_get_input_file(tmpdir: local) -> None:
tmpdir.mkdir('certificates')
ssl_certificate = get_or_generate_self_signed_certificate(
hostname='45.138.24.80',
cert_path=tmpdir.join('cert.pem'),
pkey_path=tmpdir.join('pkey.pem'),
cert_path=pathlib.Path(tmpdir.join('cert.pem')),
pkey_path=pathlib.Path(tmpdir.join('pkey.pem')),
)
input_file = ssl_certificate.as_input_file()
assert input_file.get_file().read() == tmpdir.join('cert.pem').read().encode('utf-8')

0 comments on commit 547c3b9

Please sign in to comment.