#![cfg(feature = "client")]
use delopay::{
Delopay, DelopayError, PaymentCreateRequest, PaymentListParams, RefundCreateRequest,
};
use serde_json::json;
use wiremock::matchers::{body_json, body_partial_json, header, method, path, query_param};
use wiremock::{Mock, MockServer, ResponseTemplate};
fn client(server: &MockServer) -> Delopay {
Delopay::builder("snd_test")
.base_url(server.uri())
.no_proxy()
.build()
}
#[tokio::test]
async fn create_sends_auth_header_and_parses_response() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/payments"))
.and(header("api-key", "snd_test"))
.and(header("content-type", "application/json"))
.and(body_partial_json(
json!({"amount": 1999, "currency": "EUR"}),
))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"payment_id": "pay_1", "merchant_id": "mer_1",
"status": "requires_payment_method", "amount": 1999, "currency": "EUR",
"client_secret": "secret_x"
})))
.expect(1)
.mount(&server)
.await;
let p = client(&server)
.payments()
.create(&PaymentCreateRequest::new(1999, "EUR"))
.await
.unwrap();
assert_eq!(p.payment_id, "pay_1");
assert_eq!(p.merchant_id, "mer_1");
assert_eq!(p.client_secret.as_deref(), Some("secret_x"));
}
#[tokio::test]
async fn create_idempotent_sends_idempotency_key_header() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/payments"))
.and(header("idempotency-key", "order_9"))
.and(body_partial_json(json!({"amount": 1, "currency": "EUR"})))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"payment_id": "pay_1", "merchant_id": "m", "status": "x", "amount": 1, "currency": "EUR"
})))
.expect(1)
.mount(&server)
.await;
client(&server)
.payments()
.create_idempotent(&PaymentCreateRequest::new(1, "EUR"), "order_9")
.await
.unwrap();
}
#[tokio::test]
async fn maps_401_to_authentication_error() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/payments/pay_x"))
.respond_with(ResponseTemplate::new(401).set_body_json(json!({
"error": { "type": "authentication_error", "code": "AUTH_01", "message": "invalid api key" }
})))
.mount(&server)
.await;
let err = client(&server)
.payments()
.retrieve("pay_x")
.await
.unwrap_err();
match err {
DelopayError::Authentication(e) => assert_eq!(e.code, "AUTH_01"),
other => panic!("expected authentication error, got {other:?}"),
}
}
#[tokio::test]
async fn parses_error_envelope_with_request_id() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/payments"))
.and(body_partial_json(json!({"amount": 1, "currency": "EUR"})))
.respond_with(
ResponseTemplate::new(400)
.insert_header("x-request-id", "req_123")
.set_body_json(json!({
"error": { "type": "invalid_request", "code": "IR_01", "message": "amount too small" }
})),
)
.mount(&server)
.await;
let err = client(&server)
.payments()
.create(&PaymentCreateRequest::new(1, "EUR"))
.await
.unwrap_err();
match err {
DelopayError::Api(e) => {
assert_eq!(e.status, 400);
assert_eq!(e.code, "IR_01");
assert_eq!(e.error_type, "invalid_request");
assert_eq!(e.request_id.as_deref(), Some("req_123"));
}
other => panic!("expected api error, got {other:?}"),
}
}
#[tokio::test]
async fn retries_idempotent_get_on_429_then_succeeds() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/payments/pay_1"))
.respond_with(ResponseTemplate::new(429).insert_header("retry-after", "0"))
.up_to_n_times(1)
.expect(1)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/payments/pay_1"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"payment_id": "pay_1", "merchant_id": "m", "status": "succeeded",
"amount": 500, "currency": "EUR"
})))
.mount(&server)
.await;
let p = client(&server).payments().retrieve("pay_1").await.unwrap();
assert_eq!(p.status, "succeeded");
}
#[tokio::test]
async fn list_sends_query_and_parses_envelope() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/payments/list"))
.and(query_param("limit", "10"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"data": [{
"payment_id": "pay_1", "merchant_id": "m", "status": "succeeded",
"amount": 1, "currency": "EUR"
}],
"total_count": 1
})))
.mount(&server)
.await;
let params = PaymentListParams {
limit: Some(10),
..Default::default()
};
let list = client(&server)
.payments()
.list(Some(¶ms))
.await
.unwrap();
assert_eq!(list.data.len(), 1);
assert_eq!(list.data[0].payment_id, "pay_1");
assert_eq!(list.total_count, Some(1));
}
#[tokio::test]
async fn refund_create_hits_refunds_endpoint() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/refunds"))
.and(body_partial_json(
json!({"payment_id": "pay_1", "amount": 500}),
))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"refund_id": "ref_1", "payment_id": "pay_1", "amount": 500,
"currency": "EUR", "status": "pending", "connector": "stripe"
})))
.expect(1)
.mount(&server)
.await;
let r = client(&server)
.refunds()
.create(&RefundCreateRequest::new("pay_1").amount(500))
.await
.unwrap();
assert_eq!(r.refund_id, "ref_1");
assert_eq!(r.status, "pending");
}
#[tokio::test]
async fn create_sends_exact_body_with_only_set_fields_present() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/payments"))
.and(body_json(json!({
"amount": 1999,
"currency": "EUR",
"payment_link": true
})))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"payment_id": "pay_1", "merchant_id": "m", "status": "x",
"amount": 1999, "currency": "EUR"
})))
.expect(1)
.mount(&server)
.await;
client(&server)
.payments()
.create(&PaymentCreateRequest::new(1999, "EUR").payment_link(true))
.await
.unwrap();
}
#[tokio::test]
async fn create_with_colliding_extra_key_is_rejected_before_any_request_is_sent() {
let server = MockServer::start().await;
let mut params = PaymentCreateRequest::new(1999, "EUR");
params.extra.insert("amount".to_string(), json!(999));
let err = client(&server)
.payments()
.create(¶ms)
.await
.unwrap_err();
assert!(
matches!(err, DelopayError::InvalidRequest(_)),
"expected InvalidRequest, got {err:?}"
);
}
#[tokio::test]
async fn payment_link_retrieve_decodes_the_typed_response() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/payment-link/plink_1"))
.and(header("api-key", "snd_test"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"payment_link_id": "plink_1",
"merchant_id": "mer_1",
"link_to_pay": "https://checkout.test/pay/plink_1",
"amount": 1999,
"created_at": "2026-09-01T00:00:00Z",
"expiry": "2026-09-03T00:00:00Z",
"description": "Order 1001",
"status": "active",
"currency": "EUR",
"secure_link": "https://checkout.test/s/abc"
})))
.expect(1)
.mount(&server)
.await;
let link = client(&server)
.payment_links()
.retrieve("plink_1")
.await
.unwrap();
assert_eq!(link.payment_link_id, "plink_1");
assert_eq!(link.merchant_id, "mer_1");
assert_eq!(link.link_to_pay, "https://checkout.test/pay/plink_1");
assert_eq!(link.status, "active");
assert_eq!(
link.secure_link.as_deref(),
Some("https://checkout.test/s/abc")
);
}
#[tokio::test]
async fn subscription_create_and_confirm_sends_profile_header_and_decodes_redirect() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/subscriptions"))
.and(header("x-profile-id", "pro_1"))
.and(body_partial_json(json!({
"item_price_id": "price_1",
"customer_id": "cus_1",
"payment_details": {"payment_method": "card"}
})))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"id": "sub_1", "status": "pending",
"redirect_url": "https://paypal.test/approve"
})))
.expect(1)
.mount(&server)
.await;
let req = delopay::CreateAndConfirmSubscriptionRequest {
item_price_id: Some("price_1".to_string()),
customer_id: "cus_1".to_string(),
payment_details: delopay::SubscriptionPaymentDetails {
payment_method: Some("card".to_string()),
..Default::default()
},
..Default::default()
};
let sub = client(&server)
.subscriptions()
.with_profile_id("pro_1")
.create_and_confirm(&req)
.await
.unwrap();
assert_eq!(sub.id, "sub_1");
assert_eq!(
sub.redirect_url.as_deref(),
Some("https://paypal.test/approve")
);
}
#[tokio::test]
async fn dispute_attach_evidence_is_a_put_with_a_json_body() {
let server = MockServer::start().await;
Mock::given(method("PUT"))
.and(path("/disputes/evidence"))
.and(body_json(json!({
"receipt": "file_receipt",
"dispute_id": "dp_1"
})))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"dispute_id": "dp_1", "payment_id": "pay_1", "attempt_id": "att_1",
"amount": "500", "currency": "EUR", "dispute_stage": "dispute",
"dispute_status": "dispute_challenged", "connector": "stripe",
"connector_status": "under_review", "connector_dispute_id": "du_1",
"is_already_refunded": false
})))
.expect(1)
.mount(&server)
.await;
let mut req = delopay::DisputeEvidenceRequest {
receipt: Some("file_receipt".to_string()),
..Default::default()
};
req.extra.insert("dispute_id".to_string(), json!("dp_1"));
let dispute = client(&server)
.disputes()
.attach_evidence(&req)
.await
.unwrap();
assert_eq!(dispute.dispute_status, "dispute_challenged");
}
#[tokio::test]
async fn payout_update_is_a_put_to_the_payout_path() {
let server = MockServer::start().await;
Mock::given(method("PUT"))
.and(path("/payouts/po_1"))
.and(body_partial_json(json!({"amount": 900})))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"payout_id": "po_1", "merchant_id": "mer_1", "amount": 900,
"currency": "EUR", "status": "requires_confirmation"
})))
.expect(1)
.mount(&server)
.await;
let req = delopay::PayoutUpdateRequest {
amount: Some(900),
..Default::default()
};
let payout = client(&server)
.payouts()
.update("po_1", &req)
.await
.unwrap();
assert_eq!(payout.amount, 900);
}
#[tokio::test]
async fn payment_attempts_list_decodes_the_envelope() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/payments/pay_1/attempts"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"size": 2,
"data": [
{"attempt_id": "att_1", "status": "failure",
"connector": "stripe", "unified_message": "Insufficient funds"},
{"attempt_id": "att_2", "status": "charged", "connector": "adyen"}
]
})))
.expect(1)
.mount(&server)
.await;
let attempts = client(&server)
.payments()
.list_attempts("pay_1")
.await
.unwrap();
assert_eq!(attempts.size, Some(2));
assert_eq!(
attempts.data[0].unified_message.as_deref(),
Some("Insufficient funds")
);
assert_eq!(attempts.data[1].connector.as_deref(), Some("adyen"));
}
#[tokio::test]
async fn ephemeral_key_create_round_trips() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/ephemeral-keys"))
.and(body_json(json!({"customer_id": "cus_1"})))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"customer_id": "cus_1", "created_at": 1700000000i64,
"expires": 1700003600i64, "secret": "epk_secret"
})))
.expect(1)
.mount(&server)
.await;
let key = client(&server)
.ephemeral_keys()
.create("cus_1")
.await
.unwrap();
assert_eq!(key.secret, "epk_secret");
}
#[tokio::test]
async fn panes_catalog_propagates_404_rather_than_degrading_for_the_caller() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/account/mer_1/connectors/native-panes/catalog"))
.respond_with(ResponseTemplate::new(404).set_body_json(json!({
"error": {"type": "invalid_request", "code": "HE_02",
"message": "Unrecognized request URL"}
})))
.expect(1)
.mount(&server)
.await;
let err = client(&server)
.connectors()
.panes_catalog("mer_1")
.await
.expect_err("a 404 must reach the caller, who decides whether to degrade");
match err {
DelopayError::Api(api) => assert_eq!(api.status, 404),
other => panic!("expected an API error carrying the status, got {other:?}"),
}
assert!(
!delopay::panes::STRIPE_FALLBACK_PANE_CATALOG
.methods
.is_empty()
);
}