[test] add tests for lnbits funding source (#2460)

This commit is contained in:
Vlad Stan
2024-04-24 09:31:23 +03:00
committed by GitHub
parent 8d3b156738
commit b2ff2d8cee
2 changed files with 501 additions and 66 deletions
+87 -58
View File
@@ -9,7 +9,6 @@ from lnbits.settings import settings
from .base import (
InvoiceResponse,
PaymentFailedStatus,
PaymentPendingStatus,
PaymentResponse,
PaymentStatus,
@@ -48,22 +47,21 @@ class LNbitsWallet(Wallet):
async def status(self) -> StatusResponse:
try:
r = await self.client.get(url="/api/v1/wallet", timeout=15)
except Exception as exc:
return StatusResponse(
f"Failed to connect to {self.endpoint} due to: {exc}", 0
)
try:
r.raise_for_status()
data = r.json()
except Exception:
return StatusResponse(
f"Failed to connect to {self.endpoint}, got: '{r.text[:200]}...'", 0
)
if r.is_error:
return StatusResponse(data["detail"], 0)
if len(data) == 0:
return StatusResponse("no data", 0)
return StatusResponse(None, data["balance"])
if r.is_error or "balance" not in data:
return StatusResponse(f"Server error: '{r.text}'", 0)
return StatusResponse(None, data["balance"])
except json.JSONDecodeError:
return StatusResponse("Server error: 'invalid json response'", 0)
except Exception as exc:
logger.warning(exc)
return StatusResponse(f"Unable to connect to {self.endpoint}.", 0)
async def create_invoice(
self,
@@ -81,41 +79,72 @@ class LNbitsWallet(Wallet):
if unhashed_description:
data["unhashed_description"] = unhashed_description.hex()
r = await self.client.post(url="/api/v1/payments", json=data)
ok, checking_id, payment_request, error_message = (
not r.is_error,
None,
None,
None,
)
if r.is_error:
error_message = r.json()["detail"]
else:
try:
r = await self.client.post(url="/api/v1/payments", json=data)
r.raise_for_status()
data = r.json()
checking_id, payment_request = data["checking_id"], data["payment_request"]
return InvoiceResponse(ok, checking_id, payment_request, error_message)
if r.is_error or "payment_request" not in data:
error_message = data["detail"] if "detail" in data else r.text
return InvoiceResponse(
False, None, None, f"Server error: '{error_message}'"
)
return InvoiceResponse(
True, data["checking_id"], data["payment_request"], None
)
except json.JSONDecodeError:
return InvoiceResponse(
False, None, None, "Server error: 'invalid json response'"
)
except KeyError as exc:
logger.warning(exc)
return InvoiceResponse(
False, None, None, "Server error: 'missing required fields'"
)
except Exception as exc:
logger.warning(exc)
return InvoiceResponse(
False, None, None, f"Unable to connect to {self.endpoint}."
)
async def pay_invoice(self, bolt11: str, fee_limit_msat: int) -> PaymentResponse:
r = await self.client.post(
url="/api/v1/payments",
json={"out": True, "bolt11": bolt11},
timeout=None,
)
ok = not r.is_error
if r.is_error:
error_message = r.json()["detail"]
return PaymentResponse(False, None, None, None, error_message)
else:
try:
r = await self.client.post(
url="/api/v1/payments",
json={"out": True, "bolt11": bolt11},
timeout=None,
)
r.raise_for_status()
data = r.json()
if r.is_error or "payment_hash" not in data:
error_message = data["detail"] if "detail" in data else r.text
return PaymentResponse(False, None, None, None, error_message)
checking_id = data["payment_hash"]
# we do this to get the fee and preimage
payment: PaymentStatus = await self.get_payment_status(checking_id)
# we do this to get the fee and preimage
payment: PaymentStatus = await self.get_payment_status(checking_id)
return PaymentResponse(ok, checking_id, payment.fee_msat, payment.preimage)
success = True if payment.success else None
return PaymentResponse(
success, checking_id, payment.fee_msat, payment.preimage
)
except json.JSONDecodeError:
return PaymentResponse(
False, None, None, None, "Server error: 'invalid json response'"
)
except KeyError:
return PaymentResponse(
False, None, None, None, "Server error: 'missing required fields'"
)
except Exception as exc:
logger.info(f"Failed to pay invoice {bolt11}")
logger.warning(exc)
return PaymentResponse(
False, None, None, None, f"Unable to connect to {self.endpoint}."
)
async def get_invoice_status(self, checking_id: str) -> PaymentStatus:
try:
@@ -125,32 +154,32 @@ class LNbitsWallet(Wallet):
r.raise_for_status()
data = r.json()
details = data.get("details", None)
if details and details.get("pending", False) is True:
return PaymentPendingStatus()
if data.get("paid", False) is True:
return PaymentSuccessStatus()
return PaymentFailedStatus()
return PaymentPendingStatus()
except Exception:
return PaymentPendingStatus()
async def get_payment_status(self, checking_id: str) -> PaymentStatus:
r = await self.client.get(url=f"/api/v1/payments/{checking_id}")
try:
r = await self.client.get(url=f"/api/v1/payments/{checking_id}")
if r.is_error:
if r.is_error:
return PaymentPendingStatus()
data = r.json()
if "paid" not in data or not data["paid"]:
return PaymentPendingStatus()
if "details" not in data:
return PaymentPendingStatus()
return PaymentSuccessStatus(
fee_msat=data["details"]["fee"], preimage=data["preimage"]
)
except Exception:
return PaymentPendingStatus()
data = r.json()
if "paid" not in data or not data["paid"]:
return PaymentPendingStatus()
if "details" not in data:
return PaymentPendingStatus()
return PaymentSuccessStatus(
fee_msat=data["details"]["fee"], preimage=data["preimage"]
)
async def paid_invoices_stream(self) -> AsyncGenerator[str, None]:
url = f"{self.endpoint}/api/v1/payments/sse"