-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Check input params of fetch_quote and add tests #58
Merged
yunyuyunyu
merged 2 commits into
main
from
08-14-Check_input_params_of_fetch_quote_and_add_tests
Aug 15, 2024
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,92 @@ | ||
# Copyright ©, 2022, Lightspark Group, Inc. - All Rights Reserved | ||
# pyre-strict | ||
|
||
import json | ||
from datetime import datetime, timedelta, timezone | ||
from secrets import token_hex | ||
from unittest.mock import ANY, AsyncMock, Mock, patch | ||
|
||
import aiohttp | ||
import pytest | ||
|
||
from nwc_backend.event_handlers.fetch_quote_handler import fetch_quote | ||
from nwc_backend.exceptions import InvalidInputException, NotImplementedException | ||
from nwc_backend.models.nip47_request import Nip47Request | ||
|
||
|
||
@patch.object(aiohttp.ClientSession, "get") | ||
async def test_fetch_quote_success(mock_get: Mock) -> None: | ||
now = datetime.now(timezone.utc) | ||
vasp_response = { | ||
"sending_currency_code": "SAT", | ||
"receiving_currency_code": "USD", | ||
"payment_hash": token_hex(), | ||
"expires_at": int((now + timedelta(minutes=5)).timestamp()), | ||
"multiplier": 15351.4798, | ||
"fees": 10, | ||
"total_sending_amount": 1_000_000, | ||
"total_receiving_amount": 65, | ||
"created_at": int(now.timestamp()), | ||
} | ||
mock_response = AsyncMock() | ||
mock_response.text = AsyncMock(return_value=json.dumps(vasp_response)) | ||
mock_response.raise_for_status = Mock() | ||
mock_get.return_value.__aenter__.return_value = mock_response | ||
|
||
receiver_address = "$alice@uma.me" | ||
params = { | ||
"receiver": {"lud16": receiver_address}, | ||
"sending_currency_code": "SAT", | ||
"receiving_currency_code": "USD", | ||
"locked_currency_amount": 1_000_000, | ||
"locked_currency_side": "sending", | ||
} | ||
quote = await fetch_quote( | ||
access_token=token_hex(), | ||
request=Nip47Request(params=params), | ||
) | ||
|
||
params.pop("receiver") | ||
params["receiver_address"] = receiver_address | ||
mock_get.assert_called_once_with(url="/quote/lud16", params=params, headers=ANY) | ||
|
||
assert quote.sending_currency_code == vasp_response["sending_currency_code"] | ||
assert quote.receiving_currency_code == vasp_response["receiving_currency_code"] | ||
assert quote.payment_hash == vasp_response["payment_hash"] | ||
assert quote.expires_at == vasp_response["expires_at"] | ||
assert quote.multiplier == vasp_response["multiplier"] | ||
assert quote.fees == vasp_response["fees"] | ||
assert quote.total_sending_amount == vasp_response["total_sending_amount"] | ||
assert quote.created_at == vasp_response["created_at"] | ||
|
||
|
||
async def test_fetch_quote_failure__invalid_input() -> None: | ||
with pytest.raises(InvalidInputException): | ||
await fetch_quote( | ||
access_token=token_hex(), | ||
request=Nip47Request( | ||
params={ | ||
"receiver": {"lud16": "$alice@uma.me"}, | ||
"sending_currency_code": "SAT", | ||
"receiving_currency_code": "USD", | ||
"locked_currency_amount": 1_000_000, | ||
"locked_currency_side": "send", # wrong enum value | ||
} | ||
), | ||
) | ||
|
||
|
||
async def test_fetch_quote_failure__unsupported_bolt12() -> None: | ||
with pytest.raises(NotImplementedException): | ||
await fetch_quote( | ||
access_token=token_hex(), | ||
request=Nip47Request( | ||
params={ | ||
"receiver": {"bolt12": "$alice@uma.me"}, # bolt12 not supported | ||
"sending_currency_code": "SAT", | ||
"receiving_currency_code": "USD", | ||
"locked_currency_amount": 1_000_000, | ||
"locked_currency_side": "sending", | ||
} | ||
), | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,59 +1,38 @@ | ||
# Copyright ©, 2022, Lightspark Group, Inc. - All Rights Reserved | ||
# pyre-strict | ||
|
||
import logging | ||
from typing import Any | ||
|
||
from aiohttp import ClientResponseError | ||
from nostr_sdk import ErrorCode, Nip47Error | ||
from uma_auth.models.quote import Quote | ||
|
||
from nwc_backend.exceptions import InvalidInputException | ||
from nwc_backend.event_handlers.input_validator import get_required_field | ||
from nwc_backend.models.nip47_request import Nip47Request | ||
from nwc_backend.vasp_client import ( | ||
AddressType, | ||
LockedCurrencySide, | ||
ReceivingAddress, | ||
vasp_uma_client, | ||
) | ||
|
||
|
||
async def fetch_quote( | ||
access_token: str, request: Nip47Request | ||
) -> dict[str, Any] | Nip47Error: | ||
try: | ||
locked_currency_side = LockedCurrencySide( | ||
request.params["locked_currency_side"].lower() | ||
) | ||
except ValueError: | ||
return Nip47Error( | ||
code=ErrorCode.OTHER, | ||
message="Expect locked_currency_side to be either sending or receiving.", | ||
) | ||
|
||
try: | ||
receiving_address = ReceivingAddress.from_dict(request.params["receiver"]) | ||
except InvalidInputException as ex: | ||
return Nip47Error( | ||
code=ErrorCode.OTHER, | ||
message=ex.error_message, | ||
) | ||
if receiving_address.type == AddressType.BOLT12: | ||
return Nip47Error( | ||
code=ErrorCode.NOT_IMPLEMENTED, | ||
message="Bolt12 is not yet supported.", | ||
) | ||
|
||
try: | ||
response = await vasp_uma_client.fetch_quote( | ||
access_token=access_token, | ||
sending_currency_code=request.params["sending_currency_code"], | ||
receiving_currency_code=request.params["receiving_currency_code"], | ||
locked_currency_amount=request.params["locked_currency_amount"], | ||
locked_currency_side=locked_currency_side, | ||
receiving_address=receiving_address, | ||
) | ||
return response.to_dict() | ||
except ClientResponseError as ex: | ||
logging.exception("Request fetch_quote %s failed", str(request.id)) | ||
# TODO: more granular error code | ||
return Nip47Error(code=ErrorCode.OTHER, message=ex.message) | ||
async def fetch_quote(access_token: str, request: Nip47Request) -> Quote: | ||
sending_currency_code = get_required_field( | ||
request.params, "sending_currency_code", str | ||
) | ||
receiving_currency_code = get_required_field( | ||
request.params, "receiving_currency_code", str | ||
) | ||
locked_currency_amount = get_required_field( | ||
request.params, "locked_currency_amount", int | ||
) | ||
locked_currency_side = get_required_field( | ||
request.params, "locked_currency_side", LockedCurrencySide | ||
) | ||
receiver = get_required_field(request.params, "receiver", dict) | ||
receiving_address = ReceivingAddress.from_dict(receiver) | ||
return await vasp_uma_client.fetch_quote( | ||
access_token=access_token, | ||
sending_currency_code=sending_currency_code, | ||
receiving_currency_code=receiving_currency_code, | ||
locked_currency_amount=locked_currency_amount, | ||
locked_currency_side=locked_currency_side, | ||
receiver_address=receiving_address, | ||
) | ||
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm finally happy with how clean request handler looks like now. Will keep refactoring while adding tests.