repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/elavon.rs
crates/router/tests/connectors/elavon.rs
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct ElavonTest; impl ConnectorActions for ElavonTest {} impl utils::Connector for ElavonTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Elavon; utils::construct_connector_data_old( Box::new(Elavon::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) // api::ConnectorData { // connector: Box::new(Elavon::new()), // connector_name: types::Connector::Elavon, // get_token: types::api::GetToken::Connector, // merchant_connector_id: None, // } } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .elavon .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "elavon".to_string() } } static CONNECTOR: ElavonTest = ElavonTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/payjustnow.rs
crates/router/tests/connectors/payjustnow.rs
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct PayjustnowTest; impl ConnectorActions for PayjustnowTest {} impl utils::Connector for PayjustnowTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Payjustnow; utils::construct_connector_data_old( Box::new(Payjustnow::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .payjustnow .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "payjustnow".to_string() } } static CONNECTOR: PayjustnowTest = PayjustnowTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/opennode.rs
crates/router/tests/connectors/opennode.rs
use hyperswitch_domain_models::address::{Address, AddressDetails, PhoneDetails}; use masking::Secret; use router::types::{self, api, domain, storage::enums}; use crate::{ connector_auth, utils::{self, ConnectorActions}, }; #[derive(Clone, Copy)] struct OpennodeTest; impl ConnectorActions for OpennodeTest {} impl utils::Connector for OpennodeTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Opennode; utils::construct_connector_data_old( Box::new(Opennode::new()), types::Connector::Opennode, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .opennode .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "opennode".to_string() } } static CONNECTOR: OpennodeTest = OpennodeTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: Some(types::PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("first".to_string())), last_name: Some(Secret::new("last".to_string())), line1: Some(Secret::new("line1".to_string())), line2: Some(Secret::new("line2".to_string())), city: Some("city".to_string()), zip: Some(Secret::new("zip".to_string())), country: Some(api_models::enums::CountryAlpha2::IN), ..Default::default() }), phone: Some(PhoneDetails { number: Some(Secret::new("9123456789".to_string())), country_code: Some("+91".to_string()), }), email: None, }), None, None, )), ..Default::default() }) } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { amount: 1, currency: enums::Currency::USD, payment_method_data: domain::PaymentMethodData::Crypto(domain::CryptoData { pay_currency: None, network: None, }), confirm: true, setup_future_usage: None, mandate_id: None, off_session: None, setup_mandate_details: None, // capture_method: Some(capture_method), browser_info: None, order_details: None, order_category: None, email: None, customer_name: None, payment_experience: None, payment_method_type: None, session_token: None, enrolled_for_3ds: false, related_transaction_id: None, router_return_url: Some(String::from("https://google.com/")), webhook_url: Some(String::from("https://google.com/")), complete_authorize_url: None, capture_method: None, customer_id: None, surcharge_details: None, request_incremental_authorization: false, metadata: None, authentication_data: None, customer_acceptance: None, billing_descriptor: None, ..utils::PaymentAuthorizeType::default().0 }) } // Creates a payment using the manual capture flow #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::AuthenticationPending); let resp = response.response.ok().unwrap(); let endpoint = match resp { types::PaymentsResponseData::TransactionResponse { redirection_data, .. } => Some(redirection_data), _ => None, }; assert!(endpoint.is_some()) } // Synchronizes a successful transaction. #[actix_web::test] async fn should_sync_authorized_payment() { let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( "5adebfb1-802e-432b-8b42-5db4b754b2eb".to_string(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a unresolved(underpaid) transaction. #[actix_web::test] async fn should_sync_unresolved_payment() { let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( "4cf63e6b-5135-49cb-997f-6e0b30fecebc".to_string(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Unresolved); } // Synchronizes a expired transaction. #[actix_web::test] async fn should_sync_expired_payment() { let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( "c36a097a-5091-4317-8749-80343a71c1c4".to_string(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Failure); }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/payeezy.rs
crates/router/tests/connectors/payeezy.rs
use std::str::FromStr; use cards::CardNumber; use hyperswitch_domain_models::address::{Address, AddressDetails}; use masking::Secret; use router::{ core::errors, types::{self, storage::enums, PaymentsAuthorizeData}, }; use crate::{ connector_auth, utils::{self, ConnectorActions, PaymentInfo}, }; #[derive(Clone, Copy)] struct PayeezyTest; impl ConnectorActions for PayeezyTest {} static CONNECTOR: PayeezyTest = PayeezyTest {}; impl utils::Connector for PayeezyTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Payeezy; utils::construct_connector_data_old( Box::new(&Payeezy), // Remove `dummy_connector` feature gate from module in `main.rs` when updating this to use actual connector variant types::Connector::DummyConnector1, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .payeezy .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "payeezy".to_string() } } impl PayeezyTest { fn get_payment_data() -> Option<PaymentsAuthorizeData> { Some(PaymentsAuthorizeData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: CardNumber::from_str("4012000033330026").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }) } fn get_payment_info() -> Option<PaymentInfo> { Some(PaymentInfo { address: Some(types::PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { ..Default::default() }), phone: None, email: None, }), None, None, )), ..Default::default() }) } fn get_request_interval(self) -> u64 { 20 } } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(PayeezyTest::get_payment_data(), None) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_payment(PayeezyTest::get_payment_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized); let connector_payment_id = utils::get_connector_transaction_id(response.response.clone()).unwrap_or_default(); let connector_meta = utils::get_connector_metadata(response.response); let capture_data = types::PaymentsCaptureData { connector_meta, ..utils::PaymentCaptureType::default().0 }; let capture_response = CONNECTOR .capture_payment(connector_payment_id, Some(capture_data), None) .await .unwrap(); assert_eq!(capture_response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_payment(PayeezyTest::get_payment_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized); let connector_payment_id = utils::get_connector_transaction_id(response.response.clone()).unwrap_or_default(); let connector_meta = utils::get_connector_metadata(response.response); let capture_data = types::PaymentsCaptureData { connector_meta, amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }; let capture_response = CONNECTOR .capture_payment(connector_payment_id, Some(capture_data), None) .await .unwrap(); assert_eq!(capture_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] #[ignore] async fn should_sync_authorized_payment() {} // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_payment(PayeezyTest::get_payment_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized); let connector_payment_id = utils::get_connector_transaction_id(response.response.clone()).unwrap_or_default(); let connector_meta = utils::get_connector_metadata(response.response); tokio::time::sleep(std::time::Duration::from_secs( CONNECTOR.get_request_interval(), )) .await; // to avoid 404 error let response = CONNECTOR .void_payment( connector_payment_id, Some(types::PaymentsCancelData { connector_meta, amount: Some(100), currency: Some(diesel_models::enums::Currency::USD), ..utils::PaymentCancelType::default().0 }), None, ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let authorize_response = CONNECTOR .authorize_payment( PayeezyTest::get_payment_data(), PayeezyTest::get_payment_info(), ) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); let capture_connector_meta = utils::get_connector_metadata(authorize_response.response); let capture_response = CONNECTOR .capture_payment( txn_id.clone(), Some(types::PaymentsCaptureData { connector_meta: capture_connector_meta, ..utils::PaymentCaptureType::default().0 }), PayeezyTest::get_payment_info(), ) .await .expect("Capture payment response"); let capture_txn_id = utils::get_connector_transaction_id(capture_response.response.clone()).unwrap(); let refund_connector_metadata = utils::get_connector_metadata(capture_response.response); let response = CONNECTOR .refund_payment( capture_txn_id.clone(), Some(types::RefundsData { connector_transaction_id: capture_txn_id, connector_metadata: refund_connector_metadata, ..utils::PaymentRefundType::default().0 }), PayeezyTest::get_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let authorize_response = CONNECTOR .authorize_payment( PayeezyTest::get_payment_data(), PayeezyTest::get_payment_info(), ) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); let capture_connector_meta = utils::get_connector_metadata(authorize_response.response); let capture_response = CONNECTOR .capture_payment( txn_id.clone(), Some(types::PaymentsCaptureData { connector_meta: capture_connector_meta, ..utils::PaymentCaptureType::default().0 }), PayeezyTest::get_payment_info(), ) .await .expect("Capture payment response"); let capture_txn_id = utils::get_connector_transaction_id(capture_response.response.clone()).unwrap(); let refund_connector_metadata = utils::get_connector_metadata(capture_response.response); let response = CONNECTOR .refund_payment( capture_txn_id.clone(), Some(types::RefundsData { refund_amount: 50, connector_transaction_id: capture_txn_id, connector_metadata: refund_connector_metadata, ..utils::PaymentRefundType::default().0 }), PayeezyTest::get_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] #[ignore] async fn should_sync_manually_captured_refund() {} // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment( PayeezyTest::get_payment_data(), PayeezyTest::get_payment_info(), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] #[ignore] async fn should_sync_auto_captured_payment() {} // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let captured_response = CONNECTOR.make_payment(None, None).await.unwrap(); assert_eq!(captured_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(captured_response.response.clone()); let connector_meta = utils::get_connector_metadata(captured_response.response); let response = CONNECTOR .refund_payment( txn_id.clone().unwrap(), Some(types::RefundsData { refund_amount: 100, connector_transaction_id: txn_id.unwrap(), connector_metadata: connector_meta, ..utils::PaymentRefundType::default().0 }), PayeezyTest::get_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let captured_response = CONNECTOR.make_payment(None, None).await.unwrap(); assert_eq!(captured_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(captured_response.response.clone()); let connector_meta = utils::get_connector_metadata(captured_response.response); let response = CONNECTOR .refund_payment( txn_id.clone().unwrap(), Some(types::RefundsData { refund_amount: 50, connector_transaction_id: txn_id.unwrap(), connector_metadata: connector_meta, ..utils::PaymentRefundType::default().0 }), PayeezyTest::get_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { let captured_response = CONNECTOR.make_payment(None, None).await.unwrap(); assert_eq!(captured_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(captured_response.response.clone()); let connector_meta = utils::get_connector_metadata(captured_response.response); for _x in 0..2 { let refund_response = CONNECTOR .refund_payment( txn_id.clone().unwrap(), Some(types::RefundsData { connector_metadata: connector_meta.clone(), connector_transaction_id: txn_id.clone().unwrap(), refund_amount: 50, ..utils::PaymentRefundType::default().0 }), PayeezyTest::get_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] #[ignore] async fn should_sync_refund() {} // Cards Negative scenarios // Creates a payment with incorrect card issuer. #[actix_web::test] async fn should_throw_not_implemented_for_unsupported_issuer() { let authorize_data = Some(PaymentsAuthorizeData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: CardNumber::from_str("630495060000000000").unwrap(), ..utils::CCardType::default().0 }), capture_method: Some(enums::CaptureMethod::Automatic), ..utils::PaymentAuthorizeType::default().0 }); let response = CONNECTOR .make_payment(authorize_data, PayeezyTest::get_payment_info()) .await; assert_eq!( *response.unwrap_err().current_context(), errors::ConnectorError::NotSupported { message: "card".to_string(), connector: "Payeezy", } ) } // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(PaymentsAuthorizeData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_cvc: Secret::new("12345d".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); assert_eq!( *response.response.unwrap_err().message, "The cvv provided must be numeric".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(PaymentsAuthorizeData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); assert_eq!( *response.response.unwrap_err().message, "Bad Request (25) - Invalid Expiry Date".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(PaymentsAuthorizeData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Expiry Date is invalid".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] #[ignore] async fn should_fail_void_payment_for_auto_capture() {} // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let connector_payment_id = "12345678".to_string(); let capture_response = CONNECTOR .capture_payment( connector_payment_id, Some(types::PaymentsCaptureData { connector_meta: Some( serde_json::json!({"transaction_tag" : "10069306640".to_string()}), ), amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), None, ) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("Bad Request (69) - Invalid Transaction Tag") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let captured_response = CONNECTOR.make_payment(None, None).await.unwrap(); assert_eq!(captured_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(captured_response.response.clone()); let connector_meta = utils::get_connector_metadata(captured_response.response); let response = CONNECTOR .refund_payment( txn_id.clone().unwrap(), Some(types::RefundsData { refund_amount: 1500, connector_transaction_id: txn_id.unwrap(), connector_metadata: connector_meta, ..utils::PaymentRefundType::default().0 }), PayeezyTest::get_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, String::from("Bad Request (64) - Invalid Refund"), ); }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/sift.rs
crates/router/tests/connectors/sift.rs
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct SiftTest; impl ConnectorActions for SiftTest {} impl utils::Connector for SiftTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Sift; utils::construct_connector_data_old( Box::new(Sift::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .sift .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "sift".to_string() } } static CONNECTOR: SiftTest = SiftTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/razorpay.rs
crates/router/tests/connectors/razorpay.rs
use masking::Secret; use router::types::{self, domain, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct RazorpayTest; impl ConnectorActions for RazorpayTest {} impl utils::Connector for RazorpayTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Razorpay; utils::construct_connector_data_old( Box::new(Razorpay::new()), types::Connector::Razorpay, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .razorpay .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "razorpay".to_string() } } static CONNECTOR: RazorpayTest = RazorpayTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/payjustnowinstore.rs
crates/router/tests/connectors/payjustnowinstore.rs
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct PayjustnowinstoreTest; impl ConnectorActions for PayjustnowinstoreTest {} impl utils::Connector for PayjustnowinstoreTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Payjustnowinstore; utils::construct_connector_data_old( Box::new(Payjustnowinstore::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .payjustnowinstore .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "payjustnowinstore".to_string() } } static CONNECTOR: PayjustnowinstoreTest = PayjustnowinstoreTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/stripebilling.rs
crates/router/tests/connectors/stripebilling.rs
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct StripebillingTest; impl ConnectorActions for StripebillingTest {} impl utils::Connector for StripebillingTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Stripebilling; utils::construct_connector_data_old( Box::new(Stripebilling::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .stripebilling .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "stripebilling".to_string() } } static CONNECTOR: StripebillingTest = StripebillingTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/placetopay.rs
crates/router/tests/connectors/placetopay.rs
use masking::Secret; use router::types::{self, domain, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct PlacetopayTest; impl ConnectorActions for PlacetopayTest {} impl utils::Connector for PlacetopayTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Placetopay; utils::construct_connector_data_old( Box::new(Placetopay::new()), types::Connector::Placetopay, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .placetopay .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "placetopay".to_string() } } static CONNECTOR: PlacetopayTest = PlacetopayTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/hyperwallet.rs
crates/router/tests/connectors/hyperwallet.rs
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct HyperwalletTest; impl ConnectorActions for HyperwalletTest {} impl utils::Connector for HyperwalletTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Hyperwallet; utils::construct_connector_data_old( Box::new(Hyperwallet::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .hyperwallet .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "hyperwallet".to_string() } } static CONNECTOR: HyperwalletTest = HyperwalletTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/utils.rs
crates/router/tests/connectors/utils.rs
use std::{fmt::Debug, marker::PhantomData, str::FromStr, sync::Arc, time::Duration}; use async_trait::async_trait; use common_utils::{id_type::GenerateId, pii::Email}; use error_stack::Report; use hyperswitch_domain_models::router_data_v2::flow_common_types::PaymentFlowData; use masking::Secret; use router::{ configs::settings::Settings, core::{errors::ConnectorError, payments}, db::StorageImpl, routes, services::{ self, connector_integration_interface::{BoxedConnectorIntegrationInterface, ConnectorEnum}, }, types::{self, storage::enums, AccessToken, MinorUnit, PaymentAddress, RouterData}, }; use test_utils::connector_auth::ConnectorAuthType; use tokio::sync::oneshot; use wiremock::{Mock, MockServer}; pub trait Connector { fn get_data(&self) -> types::api::ConnectorData; fn get_auth_token(&self) -> types::ConnectorAuthType; fn get_name(&self) -> String; fn get_connector_meta(&self) -> Option<serde_json::Value> { None } /// interval in seconds to be followed when making the subsequent request whenever needed fn get_request_interval(&self) -> u64 { 5 } #[cfg(feature = "payouts")] fn get_payout_data(&self) -> Option<types::api::ConnectorData> { None } } pub fn construct_connector_data_old( connector: types::api::BoxedConnector, connector_name: types::Connector, get_token: types::api::GetToken, merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, ) -> types::api::ConnectorData { types::api::ConnectorData { connector: ConnectorEnum::Old(connector), connector_name, get_token, merchant_connector_id, } } #[derive(Debug, Default, Clone)] pub struct PaymentInfo { pub address: Option<PaymentAddress>, pub auth_type: Option<enums::AuthenticationType>, pub access_token: Option<AccessToken>, pub connector_meta_data: Option<serde_json::Value>, pub connector_customer: Option<String>, pub payment_method_token: Option<String>, #[cfg(feature = "payouts")] pub payout_method_data: Option<types::api::PayoutMethodData>, #[cfg(feature = "payouts")] pub currency: Option<enums::Currency>, } impl PaymentInfo { pub fn with_default_billing_name() -> Self { Self { address: Some(PaymentAddress::new( None, None, Some(hyperswitch_domain_models::address::Address { address: Some(hyperswitch_domain_models::address::AddressDetails { first_name: Some(Secret::new("John".to_string())), last_name: Some(Secret::new("Doe".to_string())), ..Default::default() }), phone: None, email: None, }), None, )), ..Default::default() } } } #[async_trait] pub trait ConnectorActions: Connector { /// For initiating payments when `CaptureMethod` is set to `Manual` /// This doesn't complete the transaction, `PaymentsCapture` needs to be done manually async fn authorize_payment( &self, payment_data: Option<types::PaymentsAuthorizeData>, payment_info: Option<PaymentInfo>, ) -> Result<types::PaymentsAuthorizeRouterData, Report<ConnectorError>> { let integration = self.get_data().connector.get_connector_integration(); let request = self.generate_data( types::PaymentsAuthorizeData { confirm: true, capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..(payment_data.unwrap_or(PaymentAuthorizeType::default().0)) }, payment_info, ); Box::pin(call_connector(request, integration)).await } async fn create_connector_customer( &self, payment_data: Option<types::ConnectorCustomerData>, payment_info: Option<PaymentInfo>, ) -> Result<types::ConnectorCustomerRouterData, Report<ConnectorError>> { let integration: BoxedConnectorIntegrationInterface<_, PaymentFlowData, _, _> = self.get_data().connector.get_connector_integration(); let request = self.generate_data( types::ConnectorCustomerData { ..(payment_data.unwrap_or(CustomerType::default().0)) }, payment_info, ); Box::pin(call_connector(request, integration)).await } async fn create_connector_pm_token( &self, payment_data: Option<types::PaymentMethodTokenizationData>, payment_info: Option<PaymentInfo>, ) -> Result<types::TokenizationRouterData, Report<ConnectorError>> { let integration = self.get_data().connector.get_connector_integration(); let request = self.generate_data( types::PaymentMethodTokenizationData { ..(payment_data.unwrap_or(TokenType::default().0)) }, payment_info, ); Box::pin(call_connector(request, integration)).await } /// For initiating payments when `CaptureMethod` is set to `Automatic` /// This does complete the transaction without user intervention to Capture the payment async fn make_payment( &self, payment_data: Option<types::PaymentsAuthorizeData>, payment_info: Option<PaymentInfo>, ) -> Result<types::PaymentsAuthorizeRouterData, Report<ConnectorError>> { let integration = self.get_data().connector.get_connector_integration(); let request = self.generate_data( types::PaymentsAuthorizeData { confirm: true, capture_method: Some(diesel_models::enums::CaptureMethod::Automatic), ..(payment_data.unwrap_or(PaymentAuthorizeType::default().0)) }, payment_info, ); Box::pin(call_connector(request, integration)).await } async fn sync_payment( &self, payment_data: Option<types::PaymentsSyncData>, payment_info: Option<PaymentInfo>, ) -> Result<types::PaymentsSyncRouterData, Report<ConnectorError>> { let integration = self.get_data().connector.get_connector_integration(); let request = self.generate_data( payment_data.unwrap_or_else(|| PaymentSyncType::default().0), payment_info, ); Box::pin(call_connector(request, integration)).await } /// will retry the psync till the given status matches or retry max 3 times async fn psync_retry_till_status_matches( &self, status: enums::AttemptStatus, payment_data: Option<types::PaymentsSyncData>, payment_info: Option<PaymentInfo>, ) -> Result<types::PaymentsSyncRouterData, Report<ConnectorError>> { let max_tries = 3; for curr_try in 0..max_tries { let sync_res = self .sync_payment(payment_data.clone(), payment_info.clone()) .await .unwrap(); if (sync_res.status == status) || (curr_try == max_tries - 1) { return Ok(sync_res); } tokio::time::sleep(Duration::from_secs(self.get_request_interval())).await; } Err(ConnectorError::ProcessingStepFailed(None).into()) } async fn capture_payment( &self, transaction_id: String, payment_data: Option<types::PaymentsCaptureData>, payment_info: Option<PaymentInfo>, ) -> Result<types::PaymentsCaptureRouterData, Report<ConnectorError>> { let integration = self.get_data().connector.get_connector_integration(); let request = self.generate_data( types::PaymentsCaptureData { connector_transaction_id: transaction_id, ..payment_data.unwrap_or(PaymentCaptureType::default().0) }, payment_info, ); Box::pin(call_connector(request, integration)).await } async fn authorize_and_capture_payment( &self, authorize_data: Option<types::PaymentsAuthorizeData>, capture_data: Option<types::PaymentsCaptureData>, payment_info: Option<PaymentInfo>, ) -> Result<types::PaymentsCaptureRouterData, Report<ConnectorError>> { let authorize_response = self .authorize_payment(authorize_data, payment_info.clone()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); let txn_id = get_connector_transaction_id(authorize_response.response); let response = self .capture_payment(txn_id.unwrap(), capture_data, payment_info) .await .unwrap(); return Ok(response); } async fn void_payment( &self, transaction_id: String, payment_data: Option<types::PaymentsCancelData>, payment_info: Option<PaymentInfo>, ) -> Result<types::PaymentsCancelRouterData, Report<ConnectorError>> { let integration = self.get_data().connector.get_connector_integration(); let request = self.generate_data( types::PaymentsCancelData { connector_transaction_id: transaction_id, ..payment_data.unwrap_or(PaymentCancelType::default().0) }, payment_info, ); Box::pin(call_connector(request, integration)).await } async fn authorize_and_void_payment( &self, authorize_data: Option<types::PaymentsAuthorizeData>, void_data: Option<types::PaymentsCancelData>, payment_info: Option<PaymentInfo>, ) -> Result<types::PaymentsCancelRouterData, Report<ConnectorError>> { let authorize_response = self .authorize_payment(authorize_data, payment_info.clone()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); let txn_id = get_connector_transaction_id(authorize_response.response); tokio::time::sleep(Duration::from_secs(self.get_request_interval())).await; // to avoid 404 error let response = self .void_payment(txn_id.unwrap(), void_data, payment_info) .await .unwrap(); return Ok(response); } async fn refund_payment( &self, transaction_id: String, refund_data: Option<types::RefundsData>, payment_info: Option<PaymentInfo>, ) -> Result<types::RefundExecuteRouterData, Report<ConnectorError>> { let integration = self.get_data().connector.get_connector_integration(); let request = self.generate_data( types::RefundsData { connector_transaction_id: transaction_id, ..refund_data.unwrap_or(PaymentRefundType::default().0) }, payment_info, ); Box::pin(call_connector(request, integration)).await } async fn capture_payment_and_refund( &self, authorize_data: Option<types::PaymentsAuthorizeData>, capture_data: Option<types::PaymentsCaptureData>, refund_data: Option<types::RefundsData>, payment_info: Option<PaymentInfo>, ) -> Result<types::RefundExecuteRouterData, Report<ConnectorError>> { //make a successful payment let response = self .authorize_and_capture_payment(authorize_data, capture_data, payment_info.clone()) .await .unwrap(); let txn_id = self.get_connector_transaction_id_from_capture_data(response); //try refund for previous payment tokio::time::sleep(Duration::from_secs(self.get_request_interval())).await; // to avoid 404 error Ok(self .refund_payment(txn_id.unwrap(), refund_data, payment_info) .await .unwrap()) } async fn make_payment_and_refund( &self, authorize_data: Option<types::PaymentsAuthorizeData>, refund_data: Option<types::RefundsData>, payment_info: Option<PaymentInfo>, ) -> Result<types::RefundExecuteRouterData, Report<ConnectorError>> { //make a successful payment let response = self .make_payment(authorize_data, payment_info.clone()) .await .unwrap(); //try refund for previous payment let transaction_id = get_connector_transaction_id(response.response).unwrap(); tokio::time::sleep(Duration::from_secs(self.get_request_interval())).await; // to avoid 404 error Ok(self .refund_payment(transaction_id, refund_data, payment_info) .await .unwrap()) } async fn auth_capture_and_refund( &self, authorize_data: Option<types::PaymentsAuthorizeData>, refund_data: Option<types::RefundsData>, payment_info: Option<PaymentInfo>, ) -> Result<types::RefundExecuteRouterData, Report<ConnectorError>> { //make a successful payment let response = self .authorize_and_capture_payment(authorize_data, None, payment_info.clone()) .await .unwrap(); //try refund for previous payment let transaction_id = get_connector_transaction_id(response.response).unwrap(); tokio::time::sleep(Duration::from_secs(self.get_request_interval())).await; // to avoid 404 error Ok(self .refund_payment(transaction_id, refund_data, payment_info) .await .unwrap()) } async fn make_payment_and_multiple_refund( &self, authorize_data: Option<types::PaymentsAuthorizeData>, refund_data: Option<types::RefundsData>, payment_info: Option<PaymentInfo>, ) { //make a successful payment let response = self .make_payment(authorize_data, payment_info.clone()) .await .unwrap(); //try refund for previous payment let transaction_id = get_connector_transaction_id(response.response).unwrap(); for _x in 0..2 { tokio::time::sleep(Duration::from_secs(self.get_request_interval())).await; // to avoid 404 error let refund_response = self .refund_payment( transaction_id.clone(), refund_data.clone(), payment_info.clone(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } } async fn sync_refund( &self, refund_id: String, payment_data: Option<types::RefundsData>, payment_info: Option<PaymentInfo>, ) -> Result<types::RefundSyncRouterData, Report<ConnectorError>> { let integration = self.get_data().connector.get_connector_integration(); let request = self.generate_data( payment_data.unwrap_or_else(|| types::RefundsData { payment_amount: 1000, minor_payment_amount: MinorUnit::new(1000), currency: enums::Currency::USD, refund_id: uuid::Uuid::new_v4().to_string(), connector_transaction_id: "".to_string(), webhook_url: None, refund_amount: 100, minor_refund_amount: MinorUnit::new(100), connector_metadata: None, refund_connector_metadata: None, reason: None, connector_refund_id: Some(refund_id), browser_info: None, split_refunds: None, integrity_object: None, refund_status: enums::RefundStatus::Pending, merchant_account_id: None, merchant_config_currency: None, capture_method: None, additional_payment_method_data: None, }), payment_info, ); Box::pin(call_connector(request, integration)).await } /// will retry the rsync till the given status matches or retry max 3 times async fn rsync_retry_till_status_matches( &self, status: enums::RefundStatus, refund_id: String, payment_data: Option<types::RefundsData>, payment_info: Option<PaymentInfo>, ) -> Result<types::RefundSyncRouterData, Report<ConnectorError>> { let max_tries = 3; for curr_try in 0..max_tries { let sync_res = self .sync_refund( refund_id.clone(), payment_data.clone(), payment_info.clone(), ) .await .unwrap(); if (sync_res.clone().response.unwrap().refund_status == status) || (curr_try == max_tries - 1) { return Ok(sync_res); } tokio::time::sleep(Duration::from_secs(self.get_request_interval())).await; } Err(ConnectorError::ProcessingStepFailed(None).into()) } #[cfg(feature = "payouts")] fn get_payout_request<Flow, Res>( &self, connector_payout_id: Option<String>, payout_type: enums::PayoutType, payment_info: Option<PaymentInfo>, ) -> RouterData<Flow, types::PayoutsData, Res> { self.generate_data( types::PayoutsData { payout_id: common_utils::id_type::PayoutId::generate(), amount: 1, minor_amount: MinorUnit::new(1), connector_payout_id, destination_currency: payment_info.to_owned().map_or(enums::Currency::EUR, |pi| { pi.currency.map_or(enums::Currency::EUR, |c| c) }), source_currency: payment_info.to_owned().map_or(enums::Currency::EUR, |pi| { pi.currency.map_or(enums::Currency::EUR, |c| c) }), entity_type: enums::PayoutEntityType::Individual, payout_type: Some(payout_type), customer_details: Some(payments::CustomerDetails { customer_id: Some(common_utils::generate_customer_id_of_default_length()), name: Some(Secret::new("John Doe".to_string())), email: Email::from_str("john.doe@example").ok(), phone: Some(Secret::new("620874518".to_string())), phone_country_code: Some("+31".to_string()), tax_registration_id: Some("1232343243".to_string().into()), }), vendor_details: None, priority: None, connector_transfer_method_id: None, webhook_url: None, browser_info: None, payout_connector_metadata: None, additional_payout_method_data: None, }, payment_info, ) } fn generate_data<Flow, Req: From<Req>, Res>( &self, req: Req, info: Option<PaymentInfo>, ) -> RouterData<Flow, Req, Res> { let merchant_id = common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from(self.get_name())) .unwrap(); RouterData { flow: PhantomData, merchant_id, customer_id: Some(common_utils::generate_customer_id_of_default_length()), connector: self.get_name(), tenant_id: common_utils::id_type::TenantId::try_from_string("public".to_string()) .unwrap(), payment_id: uuid::Uuid::new_v4().to_string(), attempt_id: uuid::Uuid::new_v4().to_string(), status: enums::AttemptStatus::default(), auth_type: info .clone() .map_or(enums::AuthenticationType::NoThreeDs, |a| { a.auth_type .map_or(enums::AuthenticationType::NoThreeDs, |a| a) }), payment_method: enums::PaymentMethod::Card, payment_method_type: None, connector_auth_type: self.get_auth_token(), description: Some("This is a test".to_string()), payment_method_status: None, request: req, response: Err(types::ErrorResponse::default()), address: info .clone() .and_then(|a| a.address) .or_else(|| Some(PaymentAddress::default())) .unwrap(), connector_meta_data: info .clone() .and_then(|a| a.connector_meta_data.map(Secret::new)), connector_wallets_details: None, amount_captured: None, minor_amount_captured: None, access_token: info.clone().and_then(|a| a.access_token), session_token: None, reference_id: None, payment_method_token: info.clone().and_then(|a| { a.payment_method_token .map(|token| types::PaymentMethodToken::Token(Secret::new(token))) }), connector_customer: info.clone().and_then(|a| a.connector_customer), recurring_mandate_payment_data: None, preprocessing_id: None, connector_request_reference_id: uuid::Uuid::new_v4().to_string(), #[cfg(feature = "payouts")] payout_method_data: info.and_then(|p| p.payout_method_data), #[cfg(feature = "payouts")] quote_id: None, test_mode: None, payment_method_balance: None, connector_api_version: None, connector_http_status_code: None, apple_pay_flow: None, external_latency: None, frm_metadata: None, refund_id: None, dispute_id: None, payout_id: None, connector_response: None, integrity_check: Ok(()), additional_merchant_data: None, header_payload: None, connector_mandate_request_reference_id: None, psd2_sca_exemption_type: None, authentication_id: None, raw_connector_response: None, is_payment_id_from_merchant: None, l2_l3_data: None, minor_amount_capturable: None, authorized_amount: None, } } fn get_connector_transaction_id_from_capture_data( &self, response: types::PaymentsCaptureRouterData, ) -> Option<String> { match response.response { Ok(types::PaymentsResponseData::TransactionResponse { resource_id, .. }) => { resource_id.get_connector_transaction_id().ok() } Ok(types::PaymentsResponseData::SessionResponse { .. }) => None, Ok(types::PaymentsResponseData::SessionTokenResponse { .. }) => None, Ok(types::PaymentsResponseData::TokenizationResponse { .. }) => None, Ok(types::PaymentsResponseData::TransactionUnresolvedResponse { .. }) => None, Ok(types::PaymentsResponseData::ConnectorCustomerResponse(..)) => None, Ok(types::PaymentsResponseData::PreProcessingResponse { .. }) => None, Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. }) => None, Ok(types::PaymentsResponseData::MultipleCaptureResponse { .. }) => None, Ok(types::PaymentsResponseData::IncrementalAuthorizationResponse { .. }) => None, Ok(types::PaymentsResponseData::PostProcessingResponse { .. }) => None, Ok(types::PaymentsResponseData::PaymentResourceUpdateResponse { .. }) => None, Ok(types::PaymentsResponseData::PaymentsCreateOrderResponse { .. }) => None, Err(_) => None, } } #[cfg(feature = "payouts")] async fn verify_payout_eligibility( &self, payout_type: enums::PayoutType, payment_info: Option<PaymentInfo>, ) -> Result<types::PayoutsResponseData, Report<ConnectorError>> { let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< types::api::PoEligibility, types::PayoutsData, types::PayoutsResponseData, > = self .get_payout_data() .ok_or(ConnectorError::FailedToObtainPreferredConnector)? .connector .get_connector_integration(); let request = self.get_payout_request(None, payout_type, payment_info); let tx: oneshot::Sender<()> = oneshot::channel().0; let app_state = Box::pin(routes::AppState::with_storage( Settings::new().unwrap(), StorageImpl::PostgresqlTest, tx, Box::new(services::MockApiClient), )) .await; let state = Arc::new(app_state) .get_session_state( &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), None, || {}, ) .unwrap(); let res = services::api::execute_connector_processing_step( &state, connector_integration, &request, payments::CallConnectorAction::Trigger, None, None, ) .await?; Ok(res.response.unwrap()) } #[cfg(feature = "payouts")] async fn fulfill_payout( &self, connector_payout_id: Option<String>, payout_type: enums::PayoutType, payment_info: Option<PaymentInfo>, ) -> Result<types::PayoutsResponseData, Report<ConnectorError>> { let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< types::api::PoFulfill, types::PayoutsData, types::PayoutsResponseData, > = self .get_payout_data() .ok_or(ConnectorError::FailedToObtainPreferredConnector)? .connector .get_connector_integration(); let request = self.get_payout_request(connector_payout_id, payout_type, payment_info); let tx: oneshot::Sender<()> = oneshot::channel().0; let app_state = Box::pin(routes::AppState::with_storage( Settings::new().unwrap(), StorageImpl::PostgresqlTest, tx, Box::new(services::MockApiClient), )) .await; let state = Arc::new(app_state) .get_session_state( &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), None, || {}, ) .unwrap(); let res = services::api::execute_connector_processing_step( &state, connector_integration, &request, payments::CallConnectorAction::Trigger, None, None, ) .await?; Ok(res.response.unwrap()) } #[cfg(feature = "payouts")] async fn create_payout( &self, connector_customer: Option<String>, payout_type: enums::PayoutType, payment_info: Option<PaymentInfo>, ) -> Result<types::PayoutsResponseData, Report<ConnectorError>> { let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< types::api::PoCreate, types::PayoutsData, types::PayoutsResponseData, > = self .get_payout_data() .ok_or(ConnectorError::FailedToObtainPreferredConnector)? .connector .get_connector_integration(); let mut request = self.get_payout_request(None, payout_type, payment_info); request.connector_customer = connector_customer; let tx: oneshot::Sender<()> = oneshot::channel().0; let app_state = Box::pin(routes::AppState::with_storage( Settings::new().unwrap(), StorageImpl::PostgresqlTest, tx, Box::new(services::MockApiClient), )) .await; let state = Arc::new(app_state) .get_session_state( &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), None, || {}, ) .unwrap(); let res = services::api::execute_connector_processing_step( &state, connector_integration, &request, payments::CallConnectorAction::Trigger, None, None, ) .await?; Ok(res.response.unwrap()) } #[cfg(feature = "payouts")] async fn cancel_payout( &self, connector_payout_id: String, payout_type: enums::PayoutType, payment_info: Option<PaymentInfo>, ) -> Result<types::PayoutsResponseData, Report<ConnectorError>> { let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< types::api::PoCancel, types::PayoutsData, types::PayoutsResponseData, > = self .get_payout_data() .ok_or(ConnectorError::FailedToObtainPreferredConnector)? .connector .get_connector_integration(); let request = self.get_payout_request(Some(connector_payout_id), payout_type, payment_info); let tx: oneshot::Sender<()> = oneshot::channel().0; let app_state = Box::pin(routes::AppState::with_storage( Settings::new().unwrap(), StorageImpl::PostgresqlTest, tx, Box::new(services::MockApiClient), )) .await; let state = Arc::new(app_state) .get_session_state( &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), None, || {}, ) .unwrap(); let res = services::api::execute_connector_processing_step( &state, connector_integration, &request, payments::CallConnectorAction::Trigger, None, None, ) .await?; Ok(res.response.unwrap()) } #[cfg(feature = "payouts")] async fn create_and_fulfill_payout( &self, connector_customer: Option<String>, payout_type: enums::PayoutType, payment_info: Option<PaymentInfo>, ) -> Result<types::PayoutsResponseData, Report<ConnectorError>> { let create_res = self .create_payout(connector_customer, payout_type, payment_info.to_owned()) .await?; assert_eq!( create_res.status.unwrap(), enums::PayoutStatus::RequiresFulfillment ); let fulfill_res = self .fulfill_payout( create_res.connector_payout_id, payout_type, payment_info.to_owned(), ) .await?; Ok(fulfill_res) } #[cfg(feature = "payouts")] async fn create_and_cancel_payout( &self, connector_customer: Option<String>, payout_type: enums::PayoutType, payment_info: Option<PaymentInfo>, ) -> Result<types::PayoutsResponseData, Report<ConnectorError>> { let create_res = self .create_payout(connector_customer, payout_type, payment_info.to_owned()) .await?; assert_eq!( create_res.status.unwrap(), enums::PayoutStatus::RequiresFulfillment ); let cancel_res = self .cancel_payout( create_res .connector_payout_id .ok_or(ConnectorError::MissingRequiredField { field_name: "connector_payout_id", })?, payout_type, payment_info.to_owned(), ) .await?; Ok(cancel_res) } #[cfg(feature = "payouts")] async fn create_payout_recipient( &self, payout_type: enums::PayoutType, payment_info: Option<PaymentInfo>, ) -> Result<types::PayoutsResponseData, Report<ConnectorError>> { let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< types::api::PoRecipient, types::PayoutsData, types::PayoutsResponseData, > = self .get_payout_data() .ok_or(ConnectorError::FailedToObtainPreferredConnector)? .connector .get_connector_integration();
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
true
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/cryptopay.rs
crates/router/tests/connectors/cryptopay.rs
use hyperswitch_domain_models::address::{Address, AddressDetails, PhoneDetails}; use masking::Secret; use router::types::{self, api, domain, storage::enums, PaymentAddress}; use crate::{ connector_auth, utils::{self, ConnectorActions}, }; #[derive(Clone, Copy)] struct CryptopayTest; impl ConnectorActions for CryptopayTest {} impl utils::Connector for CryptopayTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Cryptopay; utils::construct_connector_data_old( Box::new(Cryptopay::new()), types::Connector::Cryptopay, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .cryptopay .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "cryptopay".to_string() } } static CONNECTOR: CryptopayTest = CryptopayTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: Some(PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("first".to_string())), last_name: Some(Secret::new("last".to_string())), line1: Some(Secret::new("line1".to_string())), line2: Some(Secret::new("line2".to_string())), city: Some("city".to_string()), zip: Some(Secret::new("zip".to_string())), country: Some(api_models::enums::CountryAlpha2::IN), ..Default::default() }), phone: Some(PhoneDetails { number: Some(Secret::new("9123456789".to_string())), country_code: Some("+91".to_string()), }), email: None, }), None, None, )), ..Default::default() }) } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { amount: 1, currency: enums::Currency::USD, payment_method_data: domain::PaymentMethodData::Crypto(domain::CryptoData { pay_currency: Some("XRP".to_string()), network: None, }), confirm: true, setup_future_usage: None, mandate_id: None, off_session: None, setup_mandate_details: None, browser_info: None, order_details: None, order_category: None, email: None, customer_name: None, payment_experience: None, payment_method_type: None, session_token: None, enrolled_for_3ds: false, related_transaction_id: None, router_return_url: Some(String::from("https://google.com/")), webhook_url: None, complete_authorize_url: None, capture_method: None, customer_id: None, surcharge_details: None, request_incremental_authorization: false, metadata: None, authentication_data: None, customer_acceptance: None, billing_descriptor: None, ..utils::PaymentAuthorizeType::default().0 }) } // Creates a payment using the manual capture flow #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::AuthenticationPending); let resp = response.response.ok().unwrap(); let endpoint = match resp { types::PaymentsResponseData::TransactionResponse { redirection_data, .. } => Some(redirection_data), _ => None, }; assert!(endpoint.is_some()) } // Synchronizes a successful transaction. #[actix_web::test] async fn should_sync_authorized_payment() { let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( "ea684036-2b54-44fa-bffe-8256650dce7c".to_string(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a unresolved(underpaid) transaction. #[actix_web::test] async fn should_sync_unresolved_payment() { let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( "7993d4c2-efbc-4360-b8ce-d1e957e6f827".to_string(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Unresolved); }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/bankofamerica.rs
crates/router/tests/connectors/bankofamerica.rs
use masking::Secret; use router::types::{self, domain, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct BankofamericaTest; impl ConnectorActions for BankofamericaTest {} impl utils::Connector for BankofamericaTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Bankofamerica; utils::construct_connector_data_old( Box::new(Bankofamerica::new()), // Remove `dummy_connector` feature gate from module in `main.rs` when updating this to use actual connector variant types::Connector::DummyConnector1, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .bankofamerica .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "bankofamerica".to_string() } } static CONNECTOR: BankofamericaTest = BankofamericaTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/globalpay.rs
crates/router/tests/connectors/globalpay.rs
use std::str::FromStr; use hyperswitch_domain_models::address::{Address, AddressDetails}; use masking::Secret; use router::types::{self, api, domain, storage::enums, AccessToken, ConnectorAuthType}; use serde_json::json; use crate::{ connector_auth, utils::{self, Connector, ConnectorActions, PaymentInfo}, }; struct Globalpay; impl ConnectorActions for Globalpay {} static CONNECTOR: Globalpay = Globalpay {}; impl Connector for Globalpay { fn get_data(&self) -> api::ConnectorData { use router::connector::Globalpay; utils::construct_connector_data_old( Box::new(Globalpay::new()), types::Connector::Globalpay, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .globalpay .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "globalpay".to_string() } fn get_connector_meta(&self) -> Option<serde_json::Value> { Some(json!({"account_name": "transaction_processing"})) } } fn get_access_token() -> Option<AccessToken> { match Connector::get_auth_token(&CONNECTOR) { ConnectorAuthType::BodyKey { api_key, key1: _ } => Some(AccessToken { token: api_key, expires: 18600, }), _ => None, } } impl Globalpay { fn get_request_interval(&self) -> u64 { 5 } fn get_payment_info() -> Option<PaymentInfo> { Some(PaymentInfo { address: Some(types::PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { country: Some(api_models::enums::CountryAlpha2::US), ..Default::default() }), phone: None, ..Default::default() }), None, None, )), access_token: get_access_token(), connector_meta_data: CONNECTOR.get_connector_meta(), ..Default::default() }) } } #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(None, Globalpay::get_payment_info()) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized); } #[actix_web::test] async fn should_make_payment() { let response = CONNECTOR .make_payment(None, Globalpay::get_payment_info()) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged); } #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( None, Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), Globalpay::get_payment_info(), ) .await; assert_eq!(response.unwrap().status, enums::AttemptStatus::Charged); } #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .authorize_payment(None, Globalpay::get_payment_info()) .await .unwrap(); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), Globalpay::get_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4024007134364842").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), Globalpay::get_payment_info(), ) .await .unwrap(); let x = response.status; assert_eq!(x, enums::AttemptStatus::Failure); } #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(None, None, Globalpay::get_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment(None, None, Globalpay::get_payment_info()) .await; assert_eq!(response.unwrap().status, enums::AttemptStatus::Voided); } #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(None, None, Globalpay::get_payment_info()) .await .unwrap(); tokio::time::sleep(std::time::Duration::from_secs( CONNECTOR.get_request_interval(), )) .await; let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, Globalpay::get_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( None, Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), Globalpay::get_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( None, None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), Globalpay::get_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let authorize_response = CONNECTOR .make_payment(None, Globalpay::get_payment_info()) .await .unwrap(); let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); let refund_response = CONNECTOR .refund_payment( txn_id, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), Globalpay::get_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund(None, None, None, Globalpay::get_payment_info()) .await .unwrap(); tokio::time::sleep(std::time::Duration::from_secs( CONNECTOR.get_request_interval(), )) .await; let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, Globalpay::get_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( None, Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), Globalpay::get_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "You may only refund up to 115% of the original amount ", ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123ddsa12".to_string(), None, Globalpay::get_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("Transaction 123ddsa12 not found at this location.") ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] #[ignore] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(None, Globalpay::get_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, Globalpay::get_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), Globalpay::get_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Expiry date invalid".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), Globalpay::get_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Invalid Expiry Date".to_string(), ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), Globalpay::get_payment_info(), ) .await; } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(None, Globalpay::get_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), Globalpay::get_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund(None, None, None, Globalpay::get_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/noon.rs
crates/router/tests/connectors/noon.rs
use std::str::FromStr; use masking::Secret; use router::types::{self, storage::enums}; use crate::{ connector_auth, utils::{self, ConnectorActions}, }; #[derive(Clone, Copy)] struct NoonTest; impl ConnectorActions for NoonTest {} impl utils::Connector for NoonTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Noon; utils::construct_connector_data_old( Box::new(Noon::new()), types::Connector::Noon, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .noon .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "noon".to_string() } } static CONNECTOR: NoonTest = NoonTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { currency: enums::Currency::AED, ..utils::PaymentAuthorizeType::default().0 }) } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect card number. #[actix_web::test] async fn should_fail_payment_for_incorrect_card_number() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str("1234567891011").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card number is incorrect.".to_string(), ); } // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/envoy.rs
crates/router/tests/connectors/envoy.rs
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct EnvoyTest; impl ConnectorActions for EnvoyTest {} impl utils::Connector for EnvoyTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Envoy; utils::construct_connector_data_old( Box::new(Envoy::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .envoy .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "envoy".to_string() } } static CONNECTOR: EnvoyTest = EnvoyTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/barclaycard.rs
crates/router/tests/connectors/barclaycard.rs
use masking::Secret; use router::types::{self, api, domain, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct BarclaycardTest; impl ConnectorActions for BarclaycardTest {} impl utils::Connector for BarclaycardTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Barclaycard; utils::construct_connector_data_old( Box::new(Barclaycard::new()), types::Connector::DummyConnector1, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .barclaycard .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "barclaycard".to_string() } } static CONNECTOR: BarclaycardTest = BarclaycardTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/billwerk.rs
crates/router/tests/connectors/billwerk.rs
use masking::Secret; use router::types::{self, domain, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct BillwerkTest; impl ConnectorActions for BillwerkTest {} impl utils::Connector for BillwerkTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Billwerk; utils::construct_connector_data_old( Box::new(Billwerk::new()), // Added as Dummy connector as template code is added for future usage types::Connector::DummyConnector1, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .billwerk .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "billwerk".to_string() } } static CONNECTOR: BillwerkTest = BillwerkTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/payload.rs
crates/router/tests/connectors/payload.rs
use masking::Secret; use router::types::{self, api, domain, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct PayloadTest; impl ConnectorActions for PayloadTest {} impl utils::Connector for PayloadTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Payload; utils::construct_connector_data_old( Box::new(Payload::new()), types::Connector::DummyConnector1, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .payload .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "payload".to_string() } } static CONNECTOR: PayloadTest = PayloadTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/wellsfargopayout.rs
crates/router/tests/connectors/wellsfargopayout.rs
use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct WellsfargopayoutTest; impl ConnectorActions for WellsfargopayoutTest {} impl utils::Connector for WellsfargopayoutTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Wellsfargopayout; api::ConnectorData { connector: Box::new(Wellsfargopayout::new()), connector_name: types::Connector::Wellsfargopayout, get_token: types::api::GetToken::Connector, merchant_connector_id: None, } } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .wellsfargopayout .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "wellsfargopayout".to_string() } } static CONNECTOR: WellsfargopayoutTest = WellsfargopayoutTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: api::PaymentMethodData::Card(api::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: api::PaymentMethodData::Card(api::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/forte.rs
crates/router/tests/connectors/forte.rs
use std::{str::FromStr, time::Duration}; use cards::CardNumber; use common_utils::types::MinorUnit; use hyperswitch_domain_models::address::{Address, AddressDetails, PhoneDetails}; use masking::Secret; use router::types::{self, api, domain, storage::enums}; use crate::{ connector_auth, utils::{self, ConnectorActions}, }; #[derive(Clone, Copy)] struct ForteTest; impl ConnectorActions for ForteTest {} impl utils::Connector for ForteTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Forte; utils::construct_connector_data_old( Box::new(Forte::new()), types::Connector::Forte, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .forte .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "forte".to_string() } } static CONNECTOR: ForteTest = ForteTest {}; fn get_payment_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: CardNumber::from_str("4111111111111111").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }) } fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: Some(types::PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("first".to_string())), last_name: Some(Secret::new("last".to_string())), line1: Some(Secret::new("line1".to_string())), line2: Some(Secret::new("line2".to_string())), city: Some("city".to_string()), zip: Some(Secret::new("zip".to_string())), country: Some(api_models::enums::CountryAlpha2::IN), ..Default::default() }), phone: Some(PhoneDetails { number: Some(Secret::new("9123456789".to_string())), country_code: Some("+91".to_string()), }), email: None, }), None, None, )), ..Default::default() }) } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(get_payment_data(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(get_payment_data(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); let connector_meta = utils::get_connector_metadata(authorize_response.response); let response = CONNECTOR .capture_payment( txn_id, Some(types::PaymentsCaptureData { connector_meta, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); //Status of the Payments is always in Pending State, Forte has to settle the sandbox transaction manually assert_eq!(response.status, enums::AttemptStatus::Pending); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(get_payment_data(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); let connector_meta = utils::get_connector_metadata(authorize_response.response); let response = CONNECTOR .capture_payment( txn_id, Some(types::PaymentsCaptureData { connector_meta, amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); //Status of the Payments is always in Pending State, Forte has to settle the sandbox transactions manually assert_eq!(response.status, enums::AttemptStatus::Pending); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(get_payment_data(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), encoded_data: None, capture_method: None, sync_type: types::SyncRequestType::SinglePaymentSync, connector_meta: None, mandate_id: None, payment_method_type: None, currency: enums::Currency::USD, payment_experience: None, integrity_object: None, amount: MinorUnit::new(100), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(get_payment_data(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); let connector_meta = utils::get_connector_metadata(authorize_response.response); let response = CONNECTOR .void_payment( txn_id, Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), connector_meta, ..Default::default() }), None, ) .await .expect("Void payment response"); //Forte doesnot send status in response, so setting it to pending so later it will be synced assert_eq!(response.status, enums::AttemptStatus::Pending); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] #[ignore = "Since Payment status is always in pending, cannot refund"] async fn should_refund_manually_captured_payment() { let authorize_response = CONNECTOR .authorize_payment(get_payment_data(), None) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); let capture_connector_meta = utils::get_connector_metadata(authorize_response.response); let capture_response = CONNECTOR .capture_payment( txn_id.clone(), Some(types::PaymentsCaptureData { connector_meta: capture_connector_meta, ..utils::PaymentCaptureType::default().0 }), None, ) .await .expect("Capture payment response"); let refund_connector_metadata = utils::get_connector_metadata(capture_response.response); let response = CONNECTOR .refund_payment( txn_id, Some(types::RefundsData { connector_metadata: refund_connector_metadata, ..utils::PaymentRefundType::default().0 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] #[ignore = "Since Payment status is always in pending, cannot refund"] async fn should_partially_refund_manually_captured_payment() { let authorize_response = CONNECTOR .authorize_payment(get_payment_data(), None) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); let capture_connector_meta = utils::get_connector_metadata(authorize_response.response); let capture_response = CONNECTOR .capture_payment( txn_id.clone(), Some(types::PaymentsCaptureData { connector_meta: capture_connector_meta, ..utils::PaymentCaptureType::default().0 }), None, ) .await .expect("Capture payment response"); let refund_connector_metadata = utils::get_connector_metadata(capture_response.response); let response = CONNECTOR .refund_payment( txn_id, Some(types::RefundsData { connector_metadata: refund_connector_metadata, refund_amount: 50, ..utils::PaymentRefundType::default().0 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] #[ignore = "Since Payment status is always in pending, cannot refund"] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund(None, None, None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let response = CONNECTOR .make_payment(get_payment_data(), get_default_payment_info()) .await .unwrap(); //Status of the Payments is always in Pending State, Forte has to settle the sandbox transaction manually assert_eq!(response.status, enums::AttemptStatus::Pending); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(get_payment_data(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Pending); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), encoded_data: None, capture_method: None, ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); //Status of the Payments is always in Pending State, Forte has to settle the sandbox transaction manually assert_eq!(response.status, enums::AttemptStatus::Pending,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] #[ignore = "Since Payment status is always in pending, cannot refund"] async fn should_refund_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(get_payment_data(), get_default_payment_info()) .await .unwrap(); let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); tokio::time::sleep(Duration::from_secs(10)).await; let refund_connector_metadata = utils::get_connector_metadata(authorize_response.response); let response = CONNECTOR .refund_payment( txn_id, Some(types::RefundsData { connector_metadata: refund_connector_metadata, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Pending, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] #[ignore = "Since Payment status is always in pending, cannot refund"] async fn should_partially_refund_succeeded_payment() { let authorize_response = CONNECTOR .make_payment(get_payment_data(), get_default_payment_info()) .await .unwrap(); let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); tokio::time::sleep(Duration::from_secs(10)).await; let refund_connector_metadata = utils::get_connector_metadata(authorize_response.response); let response = CONNECTOR .refund_payment( txn_id, Some(types::RefundsData { refund_amount: 50, connector_metadata: refund_connector_metadata, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Pending, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] #[ignore = "Since Payment status is always in pending, cannot refund"] async fn should_refund_succeeded_payment_multiple_times() { let authorize_response = CONNECTOR .make_payment(get_payment_data(), get_default_payment_info()) .await .unwrap(); let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); tokio::time::sleep(Duration::from_secs(10)).await; let refund_connector_metadata = utils::get_connector_metadata(authorize_response.response); for _x in 0..2 { let refund_response = CONNECTOR .refund_payment( txn_id.clone(), Some(types::RefundsData { connector_metadata: refund_connector_metadata.clone(), refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Pending, ); } } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] #[ignore = "Since Payment status is always in pending, cannot refund"] async fn should_sync_refund() { let authorize_response = CONNECTOR .make_payment(get_payment_data(), get_default_payment_info()) .await .unwrap(); let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); tokio::time::sleep(Duration::from_secs(10)).await; let refund_connector_metadata = utils::get_connector_metadata(authorize_response.response); let refund_response = CONNECTOR .refund_payment( txn_id, Some(types::RefundsData { connector_metadata: refund_connector_metadata, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Pending, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "INVALID CVV DATA".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "INVALID EXPIRATION DATE".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] #[ignore] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .authorize_payment(get_payment_data(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); let capture_connector_meta = utils::get_connector_metadata(authorize_response.response); let capture_response = CONNECTOR .capture_payment( txn_id, Some(types::PaymentsCaptureData { connector_meta: capture_connector_meta, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); let txn_id = utils::get_connector_transaction_id(capture_response.clone().response).unwrap(); let connector_meta = utils::get_connector_metadata(capture_response.response); let void_response = CONNECTOR .void_payment( txn_id, Some(types::PaymentsCancelData { cancellation_reason: Some("requested_by_customer".to_string()), connector_meta, ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!( void_response.response.unwrap_err().message, "ORIG TRANS NOT FOUND" ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let connector_meta = Some(serde_json::json!({ "auth_id": "56YH8TZ", })); let capture_response = CONNECTOR .capture_payment( "123456789".to_string(), Some(types::PaymentsCaptureData { connector_meta, ..utils::PaymentCaptureType::default().0 }), None, ) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, "Error[1]: The value for field transaction_id is invalid. Check for possible formatting issues. Error[2]: The value for field transaction_id is invalid. Check for possible formatting issues.", ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] #[ignore] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let authorize_response = CONNECTOR .make_payment(get_payment_data(), None) .await .unwrap(); let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap(); tokio::time::sleep(Duration::from_secs(10)).await; let refund_connector_metadata = utils::get_connector_metadata(authorize_response.response); let response = CONNECTOR .refund_payment( txn_id, Some(types::RefundsData { refund_amount: 1500, connector_metadata: refund_connector_metadata, ..utils::PaymentRefundType::default().0 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests // Cards Negative scenarios // Creates a payment with incorrect card issuer. #[actix_web::test] async fn should_throw_not_implemented_for_unsupported_issuer() { let authorize_data = Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: CardNumber::from_str("6759649826438453").unwrap(), ..utils::CCardType::default().0 }), capture_method: Some(enums::CaptureMethod::Automatic), ..utils::PaymentAuthorizeType::default().0 }); let response = CONNECTOR.make_payment(authorize_data, None).await; assert_eq!( *response.unwrap_err().current_context(), router::core::errors::ConnectorError::NotSupported { message: "Maestro".to_string(), connector: "Forte", } ) }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/nexixpay.rs
crates/router/tests/connectors/nexixpay.rs
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct NexixpayTest; impl ConnectorActions for NexixpayTest {} impl utils::Connector for NexixpayTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Nexixpay; utils::construct_connector_data_old( Box::new(Nexixpay::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .nexixpay .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "nexixpay".to_string() } } static CONNECTOR: NexixpayTest = NexixpayTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/wellsfargo.rs
crates/router/tests/connectors/wellsfargo.rs
use masking::Secret; use router::types::{self, api, domain, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct WellsfargoTest; impl ConnectorActions for WellsfargoTest {} impl utils::Connector for WellsfargoTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Wellsfargo; utils::construct_connector_data_old( Box::new(Wellsfargo::new()), types::Connector::Wellsfargo, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .wellsfargo .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "wellsfargo".to_string() } } static CONNECTOR: WellsfargoTest = WellsfargoTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/coinbase.rs
crates/router/tests/connectors/coinbase.rs
use hyperswitch_domain_models::address::{Address, AddressDetails, PhoneDetails}; use masking::Secret; use router::types::{self, api, domain, storage::enums, PaymentAddress}; use serde_json::json; use crate::{ connector_auth, utils::{self, ConnectorActions}, }; #[derive(Clone, Copy)] struct CoinbaseTest; impl ConnectorActions for CoinbaseTest {} impl utils::Connector for CoinbaseTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Coinbase; utils::construct_connector_data_old( Box::new(Coinbase::new()), types::Connector::Coinbase, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .coinbase .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "coinbase".to_string() } } static CONNECTOR: CoinbaseTest = CoinbaseTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: Some(PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("first".to_string())), last_name: Some(Secret::new("last".to_string())), line1: Some(Secret::new("line1".to_string())), line2: Some(Secret::new("line2".to_string())), city: Some("city".to_string()), zip: Some(Secret::new("zip".to_string())), country: Some(api_models::enums::CountryAlpha2::IN), ..Default::default() }), phone: Some(PhoneDetails { number: Some(Secret::new("9123456789".to_string())), country_code: Some("+91".to_string()), }), email: None, }), None, None, )), connector_meta_data: Some(json!({"pricing_type": "fixed_price"})), ..Default::default() }) } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { amount: 1, currency: enums::Currency::USD, payment_method_data: domain::PaymentMethodData::Crypto(domain::CryptoData { pay_currency: None, network: None, }), confirm: true, setup_future_usage: None, mandate_id: None, off_session: None, setup_mandate_details: None, // capture_method: Some(capture_method), browser_info: None, order_details: None, order_category: None, email: None, customer_name: None, payment_experience: None, payment_method_type: None, session_token: None, enrolled_for_3ds: false, related_transaction_id: None, router_return_url: Some(String::from("https://google.com/")), webhook_url: None, complete_authorize_url: None, capture_method: None, customer_id: None, surcharge_details: None, request_incremental_authorization: false, metadata: None, authentication_data: None, customer_acceptance: None, billing_descriptor: None, ..utils::PaymentAuthorizeType::default().0 }) } // Creates a payment using the manual capture flow #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::AuthenticationPending); let resp = response.response.ok().unwrap(); let endpoint = match resp { types::PaymentsResponseData::TransactionResponse { redirection_data, .. } => Some(redirection_data), _ => None, }; assert!(endpoint.is_some()) } // Synchronizes a successful transaction. #[actix_web::test] async fn should_sync_authorized_payment() { let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( "ADFY3789".to_string(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a unresolved(underpaid) transaction. #[actix_web::test] async fn should_sync_unresolved_payment() { let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( "YJ6RFZXZ".to_string(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Unresolved); } // Synchronizes a expired transaction. #[actix_web::test] async fn should_sync_expired_payment() { let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( "FZ89KDDB".to_string(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Failure); } // Synchronizes a cancelled transaction. #[actix_web::test] async fn should_sync_cancelled_payment() { let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( "C35AAXKF".to_string(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Voided); }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/gocardless.rs
crates/router/tests/connectors/gocardless.rs
use masking::Secret; use router::types::{self, domain, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct GocardlessTest; impl ConnectorActions for GocardlessTest {} impl utils::Connector for GocardlessTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Gocardless; utils::construct_connector_data_old( Box::new(Gocardless::new()), types::Connector::Gocardless, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .gocardless .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "gocardless".to_string() } } static CONNECTOR: GocardlessTest = GocardlessTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/adyen.rs
crates/router/tests/connectors/adyen.rs
use std::str::FromStr; use hyperswitch_domain_models::address::{Address, AddressDetails, PhoneDetails}; use masking::Secret; use router::types::{self, storage::enums, PaymentAddress}; use crate::{ connector_auth, utils::{self, ConnectorActions, PaymentInfo}, }; #[derive(Clone, Copy)] struct AdyenTest; impl ConnectorActions for AdyenTest {} impl utils::Connector for AdyenTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Adyen; utils::construct_connector_data_old( Box::new(Adyen::new()), types::Connector::Adyen, types::api::GetToken::Connector, None, ) } #[cfg(feature = "payouts")] fn get_payout_data(&self) -> Option<types::api::ConnectorData> { use router::connector::Adyen; Some(utils::construct_connector_data_old( Box::new(Adyen::new()), types::Connector::Adyen, types::api::GetToken::Connector, None, )) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .adyen_uk .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "adyen".to_string() } } impl AdyenTest { fn get_payment_info() -> Option<PaymentInfo> { Some(PaymentInfo { address: Some(PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { country: Some(api_models::enums::CountryAlpha2::US), state: Some(Secret::new("California".to_string())), city: Some("San Francisco".to_string()), zip: Some(Secret::new("94122".to_string())), line1: Some(Secret::new("1467".to_string())), line2: Some(Secret::new("Harrison Street".to_string())), line3: None, first_name: Some(Secret::new("John".to_string())), last_name: Some(Secret::new("Dough".to_string())), origin_zip: None, }), phone: Some(PhoneDetails { number: Some(Secret::new("9123456789".to_string())), country_code: Some("+351".to_string()), }), email: None, }), None, None, )), ..Default::default() }) } #[cfg(feature = "payouts")] fn get_payout_info(payout_type: enums::PayoutType) -> Option<PaymentInfo> { use common_utils::pii::Email; Some(PaymentInfo { currency: Some(enums::Currency::EUR), address: Some(PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { country: Some(api_models::enums::CountryAlpha2::US), state: Some(Secret::new("California".to_string())), city: Some("San Francisco".to_string()), zip: Some(Secret::new("94122".to_string())), line1: Some(Secret::new("1467".to_string())), line2: Some(Secret::new("Harrison Street".to_string())), ..Default::default() }), phone: None, email: None, }), None, None, )), payout_method_data: match payout_type { enums::PayoutType::Card => Some(types::api::PayoutMethodData::Card( types::api::payouts::CardPayout { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), expiry_month: Secret::new("3".to_string()), expiry_year: Secret::new("2030".to_string()), card_holder_name: Some(Secret::new("John Doe".to_string())), card_network: None, }, )), enums::PayoutType::Bank => Some(types::api::PayoutMethodData::Bank( types::api::payouts::BankPayout::Sepa(types::api::SepaBankTransfer { iban: "NL46TEST0136169112".to_string().into(), bic: Some("ABNANL2A".to_string().into()), bank_name: Some("Deutsche Bank".to_string()), bank_country_code: Some(enums::CountryAlpha2::NL), bank_city: Some("Amsterdam".to_string()), }), )), enums::PayoutType::Wallet => Some(types::api::PayoutMethodData::Wallet( types::api::payouts::WalletPayout::Paypal(api_models::payouts::Paypal { email: Email::from_str("EmailUsedForPayPalAccount@example.com").ok(), telephone_number: None, paypal_id: None, }), )), enums::PayoutType::BankRedirect => { Some(types::api::PayoutMethodData::BankRedirect( types::api::payouts::BankRedirectPayout::Interac( api_models::payouts::Interac { email: Email::from_str("EmailUsedForPayPalAccount@example.com") .ok()?, }, ), )) } }, ..Default::default() }) } fn get_payment_authorize_data( card_number: &str, card_exp_month: &str, card_exp_year: &str, card_cvc: &str, capture_method: enums::CaptureMethod, ) -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { amount: 3500, currency: enums::Currency::USD, payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str(card_number).unwrap(), card_exp_month: Secret::new(card_exp_month.to_string()), card_exp_year: Secret::new(card_exp_year.to_string()), card_cvc: Secret::new(card_cvc.to_string()), card_issuer: None, card_network: None, card_type: None, card_issuing_country: None, card_issuing_country_code: None, bank_code: None, nick_name: Some(Secret::new("nick_name".into())), card_holder_name: Some(Secret::new("card holder name".into())), co_badged_card_data: None, }), confirm: true, setup_future_usage: None, mandate_id: None, off_session: None, setup_mandate_details: None, capture_method: Some(capture_method), browser_info: None, order_details: None, order_category: None, email: None, customer_name: None, payment_experience: None, payment_method_type: None, session_token: None, enrolled_for_3ds: false, related_transaction_id: None, router_return_url: Some(String::from("http://localhost:8080")), webhook_url: None, complete_authorize_url: None, customer_id: None, surcharge_details: None, request_incremental_authorization: false, metadata: None, authentication_data: None, customer_acceptance: None, locale: None, billing_descriptor: None, ..utils::PaymentAuthorizeType::default().0 }) } } static CONNECTOR: AdyenTest = AdyenTest {}; // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment( AdyenTest::get_payment_authorize_data( "4111111111111111", "03", "2030", "737", enums::CaptureMethod::Manual, ), AdyenTest::get_payment_info(), ) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( AdyenTest::get_payment_authorize_data( "370000000000002", "03", "2030", "7373", enums::CaptureMethod::Manual, ), None, AdyenTest::get_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Pending); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( AdyenTest::get_payment_authorize_data( "4293189100000008", "03", "2030", "737", enums::CaptureMethod::Manual, ), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), AdyenTest::get_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Pending); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( AdyenTest::get_payment_authorize_data( "4293189100000008", "03", "2030", "737", enums::CaptureMethod::Manual, ), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), AdyenTest::get_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( AdyenTest::get_payment_authorize_data( "370000000000002", "03", "2030", "7373", enums::CaptureMethod::Manual, ), None, Some(types::RefundsData { refund_amount: 1500, reason: Some("CUSTOMER REQUEST".to_string()), ..utils::PaymentRefundType::default().0 }), AdyenTest::get_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Pending, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( AdyenTest::get_payment_authorize_data( "2222400070000005", "03", "2030", "737", enums::CaptureMethod::Manual, ), None, Some(types::RefundsData { refund_amount: 1500, reason: Some("CUSTOMER REQUEST".to_string()), ..utils::PaymentRefundType::default().0 }), AdyenTest::get_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Pending, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment( AdyenTest::get_payment_authorize_data( "2222400070000005", "03", "2030", "737", enums::CaptureMethod::Manual, ), AdyenTest::get_payment_info(), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund( AdyenTest::get_payment_authorize_data( "2222400070000005", "03", "2030", "737", enums::CaptureMethod::Automatic, ), Some(types::RefundsData { refund_amount: 1000, reason: Some("CUSTOMER REQUEST".to_string()), ..utils::PaymentRefundType::default().0 }), AdyenTest::get_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Pending, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( AdyenTest::get_payment_authorize_data( "4293189100000008", "03", "2030", "737", enums::CaptureMethod::Automatic, ), Some(types::RefundsData { refund_amount: 500, reason: Some("CUSTOMER REQUEST".to_string()), ..utils::PaymentRefundType::default().0 }), AdyenTest::get_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Pending, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { let payment_info = AdyenTest::get_payment_info(); //make a successful payment let response = CONNECTOR .make_payment( AdyenTest::get_payment_authorize_data( "2222400070000005", "03", "2030", "737", enums::CaptureMethod::Automatic, ), payment_info.clone(), ) .await .unwrap(); //try refund for previous payment let transaction_id = utils::get_connector_transaction_id(response.response).unwrap(); for _x in 0..2 { let refund_response = CONNECTOR .refund_payment( transaction_id.clone(), Some(types::RefundsData { refund_amount: 100, reason: Some("CUSTOMER REQUEST".to_string()), ..utils::PaymentRefundType::default().0 }), payment_info.clone(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Pending, ); } } // Cards Negative scenarios // Creates a payment with incorrect card number. #[actix_web::test] async fn should_fail_payment_for_incorrect_card_number() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { router_return_url: Some(String::from("http://localhost:8080")), payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str("4024007134364842").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), AdyenTest::get_payment_info(), ) .await .unwrap(); assert_eq!(response.response.unwrap_err().message, "Refused"); } // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { router_return_url: Some(String::from("http://localhost:8080")), payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), AdyenTest::get_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "CVC is not the right length", ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { router_return_url: Some(String::from("http://localhost:8080")), payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), AdyenTest::get_payment_info(), ) .await .unwrap(); let errors = ["The provided Expiry Date is not valid.: Expiry month should be between 1 and 12 inclusive: 20","Refused"]; assert!(errors.contains(&response.response.unwrap_err().message.as_str())) } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { router_return_url: Some(String::from("http://localhost:8080")), payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), AdyenTest::get_payment_info(), ) .await .unwrap(); assert_eq!(response.response.unwrap_err().message, "Expired Card"); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, AdyenTest::get_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("Original pspReference required for this operation") ); } /******************** Payouts test cases ********************/ // Create SEPA payout #[ignore] #[cfg(feature = "payouts")] #[actix_web::test] async fn should_create_sepa_payout() { let payout_type = enums::PayoutType::Bank; let payout_info = AdyenTest::get_payout_info(payout_type); let response = CONNECTOR .create_payout(None, payout_type, payout_info) .await .expect("Payout bank creation response"); assert_eq!( response.status.unwrap(), enums::PayoutStatus::RequiresFulfillment ); } // Create and fulfill SEPA payout #[ignore] #[cfg(feature = "payouts")] #[actix_web::test] async fn should_create_and_fulfill_sepa_payout() { let payout_type = enums::PayoutType::Bank; let payout_info = AdyenTest::get_payout_info(payout_type); let response = CONNECTOR .create_and_fulfill_payout(None, payout_type, payout_info) .await .expect("Payout bank creation and fulfill response"); assert_eq!(response.status.unwrap(), enums::PayoutStatus::Success); } // Verifies if card is eligible for payout #[ignore] #[cfg(feature = "payouts")] #[actix_web::test] async fn should_verify_payout_eligibility() { let payout_type = enums::PayoutType::Card; let payout_info = AdyenTest::get_payout_info(payout_type); let response = CONNECTOR .verify_payout_eligibility(payout_type, payout_info) .await .expect("Payout eligibility response"); assert_eq!( response.status.unwrap(), enums::PayoutStatus::RequiresFulfillment ); } // Fulfills card payout #[ignore] #[cfg(feature = "payouts")] #[actix_web::test] async fn should_fulfill_card_payout() { let payout_type = enums::PayoutType::Card; let payout_info: Option<PaymentInfo> = AdyenTest::get_payout_info(payout_type); let response = CONNECTOR .fulfill_payout(None, payout_type, payout_info) .await .expect("Payout fulfill response"); assert_eq!(response.status.unwrap(), enums::PayoutStatus::Success); } // Cancels a created bank payout #[ignore] #[cfg(feature = "payouts")] #[actix_web::test] async fn should_create_and_cancel_created_payout() { let payout_type = enums::PayoutType::Bank; let payout_info = AdyenTest::get_payout_info(payout_type); let response = CONNECTOR .create_and_cancel_payout(None, payout_type, payout_info) .await .expect("Payout cancel response"); assert_eq!(response.status.unwrap(), enums::PayoutStatus::Cancelled); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/fiuu.rs
crates/router/tests/connectors/fiuu.rs
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct FiuuTest; impl ConnectorActions for FiuuTest {} impl utils::Connector for FiuuTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Fiuu; utils::construct_connector_data_old( Box::new(Fiuu::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .fiuu .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "fiuu".to_string() } } static CONNECTOR: FiuuTest = FiuuTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/thunes.rs
crates/router/tests/connectors/thunes.rs
use masking::Secret; // use router::{ // types::{self, api, storage::enums, // }}; use crate::utils::{self, ConnectorActions}; use test_utils::connector_auth; #[derive(Clone, Copy)] struct ThunesTest; impl ConnectorActions for ThunesTest {} impl utils::Connector for ThunesTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Thunes; api::ConnectorData { connector: Box::new(Thunes::new()), connector_name: types::Connector::Thunes, get_token: types::api::GetToken::Connector, merchant_connector_id: None, } } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .thunes .expect("Missing connector authentication configuration").into(), ) } fn get_name(&self) -> String { "thunes".to_string() } } static CONNECTOR: ThunesTest = ThunesTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund(payment_method_details(), None, None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund(payment_method_details(), None, None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: api::PaymentMethodData::Card(api::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: api::PaymentMethodData::Card(api::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/ebanx.rs
crates/router/tests/connectors/ebanx.rs
use masking::Secret; use router::types::{self, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct EbanxTest; impl ConnectorActions for EbanxTest {} impl utils::Connector for EbanxTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Ebanx; utils::construct_connector_data_old( Box::new(Ebanx::new()), types::Connector::Ebanx, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .ebanx .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "ebanx".to_string() } } static CONNECTOR: EbanxTest = EbanxTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/celero.rs
crates/router/tests/connectors/celero.rs
use masking::Secret; use router::types::{self, api, domain, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct CeleroTest; impl ConnectorActions for CeleroTest {} impl utils::Connector for CeleroTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Celero; utils::construct_connector_data_old( Box::new(Celero::new()), types::Connector::Celero, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .celero .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "celero".to_string() } } static CONNECTOR: CeleroTest = CeleroTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/zift.rs
crates/router/tests/connectors/zift.rs
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct ZiftTest; impl ConnectorActions for ZiftTest {} impl utils::Connector for ZiftTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Zift; utils::construct_connector_data_old( Box::new(Zift::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .zift .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "zift".to_string() } } static CONNECTOR: ZiftTest = ZiftTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/cybersource.rs
crates/router/tests/connectors/cybersource.rs
use std::str::FromStr; use common_utils::pii::Email; use hyperswitch_domain_models::address::{Address, AddressDetails, PhoneDetails}; use masking::Secret; use router::types::{self, api, domain, storage::enums}; use crate::{ connector_auth, utils::{self, ConnectorActions, PaymentAuthorizeType}, }; struct Cybersource; impl ConnectorActions for Cybersource {} impl utils::Connector for Cybersource { fn get_data(&self) -> api::ConnectorData { use router::connector::Cybersource; utils::construct_connector_data_old( Box::new(Cybersource::new()), types::Connector::Cybersource, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .cybersource .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "cybersource".to_string() } } fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: Some(types::PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("first".to_string())), last_name: Some(Secret::new("last".to_string())), line1: Some(Secret::new("line1".to_string())), line2: Some(Secret::new("line2".to_string())), city: Some("city".to_string()), zip: Some(Secret::new("zip".to_string())), country: Some(api_models::enums::CountryAlpha2::IN), ..Default::default() }), phone: Some(PhoneDetails { number: Some(Secret::new("9123456789".to_string())), country_code: Some("+91".to_string()), }), email: None, }), None, None, )), ..Default::default() }) } fn get_default_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { currency: enums::Currency::USD, email: Some(Email::from_str("abc@gmail.com").unwrap()), ..PaymentAuthorizeType::default().0 }) } #[actix_web::test] async fn should_only_authorize_payment() { let response = Cybersource {} .authorize_payment( get_default_payment_authorize_data(), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized); } #[actix_web::test] async fn should_make_payment() { let response = Cybersource {} .make_payment( get_default_payment_authorize_data(), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Pending); } #[actix_web::test] async fn should_capture_already_authorized_payment() { let connector = Cybersource {}; let response = connector .authorize_and_capture_payment( get_default_payment_authorize_data(), None, get_default_payment_info(), ) .await; assert_eq!(response.unwrap().status, enums::AttemptStatus::Pending); } #[actix_web::test] async fn should_partially_capture_already_authorized_payment() { let connector = Cybersource {}; let response = connector .authorize_and_capture_payment( get_default_payment_authorize_data(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await; assert_eq!(response.unwrap().status, enums::AttemptStatus::Pending); } #[actix_web::test] #[ignore = "Status field is missing in the response, Communication is being done with cybersource team"] async fn should_sync_payment() { let connector = Cybersource {}; let response = connector .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( "6699597903496176903954".to_string(), ), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged); } #[actix_web::test] async fn should_void_already_authorized_payment() { let connector = Cybersource {}; let response = connector .authorize_and_void_payment( get_default_payment_authorize_data(), Some(types::PaymentsCancelData { connector_transaction_id: "".to_string(), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await; assert_eq!(response.unwrap().status, enums::AttemptStatus::Voided); } #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = Cybersource {} .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("13".to_string()), ..utils::CCardType::default().0 }), ..get_default_payment_authorize_data().unwrap() }), get_default_payment_info(), ) .await .unwrap(); let x = response.response.unwrap_err(); assert_eq!( x.message, "Declined - One or more fields in the request contains invalid data", ); assert_eq!( x.reason, Some("paymentInformation.card.expirationMonth : INVALID_DATA".to_string()) ); } #[actix_web::test] async fn should_fail_payment_for_invalid_exp_year() { let response = Cybersource {} .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2022".to_string()), ..utils::CCardType::default().0 }), ..get_default_payment_authorize_data().unwrap() }), get_default_payment_info(), ) .await .unwrap(); let x = response.response.unwrap_err(); assert_eq!(x.message, "Decline - Expired card. You might also receive this if the expiration date you provided does not match the date the issuing bank has on file."); } #[actix_web::test] async fn should_fail_payment_for_invalid_card_cvc() { let response = Cybersource {} .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("9123456789".to_string()), ..utils::CCardType::default().0 }), ..get_default_payment_authorize_data().unwrap() }), get_default_payment_info(), ) .await .unwrap(); let x = response.response.unwrap_err(); assert_eq!( x.message, "Declined - One or more fields in the request contains invalid data", ); assert_eq!( x.reason, Some("paymentInformation.card.securityCode : INVALID_DATA".to_string()) ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_reversed_payment() { let connector = Cybersource {}; // Authorize let authorize_response = connector .make_payment( get_default_payment_authorize_data(), get_default_payment_info(), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Pending); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); // Void let void_response = connector .void_payment("6736046645576085004953".to_string(), None, None) .await .unwrap(); let res = void_response.response.unwrap_err(); assert_eq!( res.message, "Decline - The authorization has already been reversed." ); } #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let connector = Cybersource {}; let response = connector .capture_payment("12345".to_string(), None, get_default_payment_info()) .await .unwrap(); let err = response.response.unwrap_err(); assert_eq!( err.message, "Declined - One or more fields in the request contains invalid data" ); assert_eq!(err.code, "InvalidData".to_string()); } #[actix_web::test] async fn should_refund_succeeded_payment() { let connector = Cybersource {}; let response = connector .make_payment_and_refund( get_default_payment_authorize_data(), None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Pending, ); } #[actix_web::test] #[ignore = "Connector Error, needs to be looked into and fixed"] async fn should_refund_manually_captured_payment() { let connector = Cybersource {}; let response = connector .auth_capture_and_refund( get_default_payment_authorize_data(), None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Pending, ); } #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let connector = Cybersource {}; let refund_response = connector .make_payment_and_refund( get_default_payment_authorize_data(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Pending, ); } #[actix_web::test] #[ignore = "refunds tests are ignored for this connector because it takes one day for a payment to be settled."] async fn should_partially_refund_manually_captured_payment() { let connector = Cybersource {}; let response = connector .auth_capture_and_refund( get_default_payment_authorize_data(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Pending, ); } #[actix_web::test] async fn should_fail_refund_for_invalid_amount() { let connector = Cybersource {}; let response = connector .make_payment_and_refund( get_default_payment_authorize_data(), Some(types::RefundsData { refund_amount: 15000, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Pending, ); } #[actix_web::test] #[ignore = "Status field is missing in the response, Communication is being done with cybersource team"] async fn should_sync_refund() { let connector = Cybersource {}; let response = connector .rsync_retry_till_status_matches( enums::RefundStatus::Success, "6699597076726585603955".to_string(), None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } #[actix_web::test] #[ignore = "refunds tests are ignored for this connector because it takes one day for a payment to be settled."] async fn should_sync_manually_captured_refund() {} #[actix_web::test] #[ignore = "refunds tests are ignored for this connector because it takes one day for a payment to be settled."] async fn should_refund_auto_captured_payment() {} #[actix_web::test] #[ignore = "refunds tests are ignored for this connector because it takes one day for a payment to be settled."] async fn should_refund_succeeded_payment_multiple_times() {} #[actix_web::test] #[ignore = "refunds tests are ignored for this connector because it takes one day for a payment to be settled."] async fn should_fail_for_refund_amount_higher_than_payment_amount() {}
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/paytm.rs
crates/router/tests/connectors/paytm.rs
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct PaytmTest; impl ConnectorActions for PaytmTest {} impl utils::Connector for PaytmTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Paytm; utils::construct_connector_data_old( Box::new(Paytm::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .paytm .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "paytm".to_string() } } static CONNECTOR: PaytmTest = PaytmTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/main.rs
crates/router/tests/connectors/main.rs
#![allow( clippy::expect_used, clippy::panic, clippy::unwrap_in_result, clippy::unwrap_used )] use test_utils::connector_auth; mod aci; mod adyen; mod adyenplatform; mod affirm; mod airwallex; mod amazonpay; mod authorizedotnet; mod bambora; mod bamboraapac; #[cfg(feature = "dummy_connector")] mod bankofamerica; mod barclaycard; #[cfg(feature = "dummy_connector")] mod billwerk; mod bitpay; mod blackhawknetwork; mod bluesnap; mod boku; mod breadpay; mod calida; mod cashtocode; mod celero; mod chargebee; mod checkbook; mod checkout; mod coinbase; mod cryptopay; mod cybersource; mod datatrans; mod deutschebank; mod dlocal; #[cfg(feature = "dummy_connector")] mod dummyconnector; mod dwolla; mod ebanx; mod elavon; mod envoy; mod facilitapay; mod finix; mod fiserv; mod fiservemea; mod fiuu; mod flexiti; mod forte; mod getnet; mod gigadat; mod globalpay; mod globepay; mod gocardless; mod gpayments; mod helcim; mod hipay; mod hyperswitch_vault; mod hyperwallet; mod iatapay; mod inespay; mod itaubank; mod jpmorgan; mod juspaythreedsserver; mod katapult; mod loonio; mod mifinity; mod mollie; mod moneris; mod mpgs; mod multisafepay; mod netcetera; mod nexinets; mod nexixpay; mod nmi; mod nomupay; mod noon; mod nordea; mod novalnet; mod nuvei; #[cfg(feature = "dummy_connector")] mod opayo; mod opennode; mod paybox; #[cfg(feature = "dummy_connector")] mod payeezy; mod payjustnow; mod payjustnowinstore; mod payload; mod payme; mod payone; mod paypal; mod paysafe; mod paystack; mod paytm; mod payu; mod peachpayments; mod phonepe; mod placetopay; mod plaid; mod powertranz; #[cfg(feature = "dummy_connector")] mod prophetpay; mod rapyd; mod razorpay; mod redsys; mod santander; mod shift4; mod sift; mod silverflow; mod square; mod stax; mod stripe; mod stripebilling; mod taxjar; mod tesouro; mod tokenex; mod tokenio; mod trustpay; mod trustpayments; mod tsys; mod unified_authentication_service; mod utils; mod vgs; mod volt; mod wellsfargo; mod worldpayvantiv; mod zift; // mod wellsfargopayout; #[cfg(feature = "payouts")] mod wise; mod worldline; mod worldpay; mod worldpayxml; mod zen; mod zsl;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/rapyd.rs
crates/router/tests/connectors/rapyd.rs
use std::str::FromStr; use futures::future::OptionFuture; use masking::Secret; use router::types::{self, domain, storage::enums}; use serial_test::serial; use crate::{ connector_auth, utils::{self, ConnectorActions, PaymentInfo}, }; struct Rapyd; impl ConnectorActions for Rapyd {} impl utils::Connector for Rapyd { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Rapyd; utils::construct_connector_data_old( Box::new(Rapyd::new()), types::Connector::Rapyd, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .rapyd .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "rapyd".to_string() } } #[actix_web::test] async fn should_only_authorize_payment() { let response = Rapyd {} .authorize_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2024".to_string()), card_cvc: Secret::new("123".to_string()), card_issuer: None, card_network: None, card_type: None, card_issuing_country: None, card_issuing_country_code: None, bank_code: None, nick_name: Some(Secret::new("nick_name".into())), card_holder_name: Some(Secret::new("card holder name".into())), co_badged_card_data: None, }), capture_method: Some(diesel_models::enums::CaptureMethod::Manual), ..utils::PaymentAuthorizeType::default().0 }), Some(PaymentInfo::with_default_billing_name()), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized); } #[actix_web::test] async fn should_authorize_and_capture_payment() { let response = Rapyd {} .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2024".to_string()), card_cvc: Secret::new("123".to_string()), card_issuer: None, card_network: None, card_type: None, card_issuing_country: None, card_issuing_country_code: None, bank_code: None, nick_name: Some(Secret::new("nick_name".into())), card_holder_name: Some(Secret::new("card holder name".into())), co_badged_card_data: None, }), ..utils::PaymentAuthorizeType::default().0 }), Some(PaymentInfo::with_default_billing_name()), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged); } #[actix_web::test] async fn should_capture_already_authorized_payment() { let connector = Rapyd {}; let authorize_response = connector .authorize_payment(None, Some(PaymentInfo::with_default_billing_name())) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response: OptionFuture<_> = txn_id .map(|transaction_id| async move { connector .capture_payment(transaction_id, None, None) .await .unwrap() .status }) .into(); assert_eq!(response.await, Some(enums::AttemptStatus::Charged)); } #[actix_web::test] #[serial] async fn voiding_already_authorized_payment_fails() { let connector = Rapyd {}; let authorize_response = connector .authorize_payment(None, Some(PaymentInfo::with_default_billing_name())) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response: OptionFuture<_> = txn_id .map(|transaction_id| async move { connector .void_payment(transaction_id, None, None) .await .unwrap() .status }) .into(); assert_eq!(response.await, Some(enums::AttemptStatus::Failure)); //rapyd doesn't allow authorize transaction to be voided } #[actix_web::test] async fn should_refund_succeeded_payment() { let connector = Rapyd {}; //make a successful payment let response = connector.make_payment(None, None).await.unwrap(); //try refund for previous payment if let Some(transaction_id) = utils::get_connector_transaction_id(response.response) { let response = connector .refund_payment(transaction_id, None, None) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } } #[actix_web::test] async fn should_fail_payment_for_incorrect_card_number() { let response = Rapyd {} .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("0000000000000000").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); assert!(response.response.is_err(), "The Payment pass"); }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/inespay.rs
crates/router/tests/connectors/inespay.rs
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct InespayTest; impl ConnectorActions for InespayTest {} impl utils::Connector for InespayTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Inespay; utils::construct_connector_data_old( Box::new(Inespay::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .inespay .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "inespay".to_string() } } static CONNECTOR: InespayTest = InespayTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/powertranz.rs
crates/router/tests/connectors/powertranz.rs
use masking::Secret; use router::types::{self, domain, storage::enums}; use crate::{ connector_auth, utils::{self, ConnectorActions}, }; #[derive(Clone, Copy)] struct PowertranzTest; impl ConnectorActions for PowertranzTest {} impl utils::Connector for PowertranzTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Powertranz; utils::construct_connector_data_old( Box::new(Powertranz::new()), types::Connector::Powertranz, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .powertranz .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "powertranz".to_string() } } static CONNECTOR: PowertranzTest = PowertranzTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] #[ignore = "Connector does not support partial capture"] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] #[ignore = "Connector does not support payment sync"] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] #[ignore = "Connector does not support payment sync"] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] #[ignore = "Connector does not support payment sync"] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] #[ignore = "Connector does not support multiple refund"] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] #[ignore = "Connector does not support refund sync"] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Field is invalid: CardCvv".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Field is invalid: CardExpiration".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Failure,); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!(void_response.status, enums::AttemptStatus::VoidFailed); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("Original auth not found") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.response.unwrap_err().message, "Invalid amount"); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/xendit.rs
crates/router/tests/connectors/xendit.rs
use masking::Secret; use router::{ types::{self, api, storage::enums, }}; use crate::utils::{self, ConnectorActions}; use test_utils::connector_auth; #[derive(Clone, Copy)] struct XenditTest; impl ConnectorActions for XenditTest {} impl utils::Connector for XenditTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Xendit; api::ConnectorData { connector: Box::new(Xendit::new()), connector_name: types::Connector::Xendit, get_token: types::api::GetToken::Connector, merchant_connector_id: None, } } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .xendit .expect("Missing connector authentication configuration").into(), ) } fn get_name(&self) -> String { "xendit".to_string() } } static CONNECTOR: XenditTest = XenditTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund(payment_method_details(), None, None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund(payment_method_details(), None, None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: api::PaymentMethodData::Card(api::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: api::PaymentMethodData::Card(api::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/square.rs
crates/router/tests/connectors/square.rs
use std::{str::FromStr, time::Duration}; use masking::Secret; use router::types::{self, storage::enums, PaymentsResponseData}; use test_utils::connector_auth::ConnectorAuthentication; use crate::utils::{self, get_connector_transaction_id, Connector, ConnectorActions}; #[derive(Clone, Copy)] struct SquareTest; impl ConnectorActions for SquareTest {} impl Connector for SquareTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Square; utils::construct_connector_data_old( Box::new(&Square), types::Connector::Square, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( ConnectorAuthentication::new() .square .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "square".to_string() } } static CONNECTOR: SquareTest = SquareTest {}; fn get_default_payment_info(payment_method_token: Option<String>) -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: None, auth_type: None, access_token: None, connector_meta_data: None, connector_customer: None, payment_method_token, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] currency: None, }) } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } fn token_details() -> Option<types::PaymentMethodTokenizationData> { Some(types::PaymentMethodTokenizationData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("04".to_string()), card_exp_year: Secret::new("2027".to_string()), card_cvc: Secret::new("100".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, split_payments: None, mandate_id: None, setup_future_usage: None, customer_acceptance: None, setup_mandate_details: None, payment_method_type: None, router_return_url: None, capture_method: None, }) } async fn create_token() -> Option<String> { let token_response = CONNECTOR .create_connector_pm_token(token_details(), get_default_payment_info(None)) .await .expect("Authorize payment response"); match token_response.response.unwrap() { PaymentsResponseData::TokenizationResponse { token } => Some(token), _ => None, } } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment( payment_method_details(), get_default_payment_info(create_token().await), ) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), None, get_default_payment_info(create_token().await), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] #[ignore = "Connector does not support partial capture"] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(create_token().await), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment( payment_method_details(), get_default_payment_info(create_token().await), ) .await .expect("Authorize payment response"); let txn_id = get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(None), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(create_token().await), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(create_token().await), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(create_token().await), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(create_token().await), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(create_token().await), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(create_token().await), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(None), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), None, get_default_payment_info(create_token().await), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(create_token().await), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { //make a successful payment let response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(create_token().await), ) .await .unwrap(); let refund_data = Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }); //try refund for previous payment let transaction_id = get_connector_transaction_id(response.response).unwrap(); for _x in 0..2 { tokio::time::sleep(Duration::from_secs(CONNECTOR.get_request_interval())).await; // to avoid 404 error let refund_response = CONNECTOR .refund_payment( transaction_id.clone(), refund_data.clone(), get_default_payment_info(None), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), None, get_default_payment_info(create_token().await), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let token_response = CONNECTOR .create_connector_pm_token( Some(types::PaymentMethodTokenizationData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("11".to_string()), card_exp_year: Secret::new("2027".to_string()), card_cvc: Secret::new("".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, split_payments: None, mandate_id: None, setup_future_usage: None, customer_acceptance: None, setup_mandate_details: None, payment_method_type: None, router_return_url: None, capture_method: None, }), get_default_payment_info(None), ) .await .expect("Authorize payment response"); assert_eq!( token_response .response .unwrap_err() .reason .unwrap_or("".to_string()), "Missing required parameter.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let token_response = CONNECTOR .create_connector_pm_token( Some(types::PaymentMethodTokenizationData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("20".to_string()), card_exp_year: Secret::new("2027".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, split_payments: None, mandate_id: None, setup_future_usage: None, customer_acceptance: None, setup_mandate_details: None, payment_method_type: None, router_return_url: None, capture_method: None, }), get_default_payment_info(None), ) .await .expect("Authorize payment response"); assert_eq!( token_response .response .unwrap_err() .reason .unwrap_or("".to_string()), "Invalid card expiration date.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let token_response = CONNECTOR .create_connector_pm_token( Some(types::PaymentMethodTokenizationData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("11".to_string()), card_exp_year: Secret::new("2000".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, split_payments: None, mandate_id: None, setup_future_usage: None, customer_acceptance: None, setup_mandate_details: None, payment_method_type: None, router_return_url: None, capture_method: None, }), get_default_payment_info(None), ) .await .expect("Authorize payment response"); assert_eq!( token_response .response .unwrap_err() .reason .unwrap_or("".to_string()), "Invalid card expiration date.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(create_token().await), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment( txn_id.clone().unwrap(), None, get_default_payment_info(None), ) .await .unwrap(); let connector_transaction_id = txn_id.unwrap(); assert_eq!( void_response.response.unwrap_err().reason.unwrap_or("".to_string()), format!("Payment {connector_transaction_id} is in inflight state COMPLETED, which is invalid for the requested operation") ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment( "123456789".to_string(), None, get_default_payment_info(create_token().await), ) .await .unwrap(); assert_eq!( capture_response .response .unwrap_err() .reason .unwrap_or("".to_string()), String::from("Could not find payment with id: 123456789") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(create_token().await), ) .await .unwrap(); assert_eq!( response .response .unwrap_err() .reason .unwrap_or("".to_string()), "The requested refund amount exceeds the amount available to refund.", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/zsl.rs
crates/router/tests/connectors/zsl.rs
use router::types::{self, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; struct ZslTest; impl ConnectorActions for ZslTest {} impl utils::Connector for ZslTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Zsl; utils::construct_connector_data_old( Box::new(&Zsl), types::Connector::Adyen, // Added as Dummy connector as template code is added for future usage types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .zsl .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "zsl".to_string() } } static CONNECTOR: ZslTest = ZslTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::AuthenticationPending); }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/calida.rs
crates/router/tests/connectors/calida.rs
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct CalidaTest; impl ConnectorActions for CalidaTest {} impl utils::Connector for CalidaTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Calida; utils::construct_connector_data_old( Box::new(Calida::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .calida .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "calida".to_string() } } static CONNECTOR: CalidaTest = CalidaTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/stax.rs
crates/router/tests/connectors/stax.rs
use std::{str::FromStr, time::Duration}; use masking::Secret; use router::types::{self, domain, storage::enums, PaymentsResponseData}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct StaxTest; impl ConnectorActions for StaxTest {} impl utils::Connector for StaxTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Stax; utils::construct_connector_data_old( Box::new(&Stax), types::Connector::Stax, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .stax .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "stax".to_string() } } static CONNECTOR: StaxTest = StaxTest {}; fn get_default_payment_info( connector_customer: Option<String>, payment_method_token: Option<String>, ) -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: None, auth_type: None, access_token: None, connector_meta_data: None, connector_customer, payment_method_token, #[cfg(feature = "payouts")] payout_method_data: None, #[cfg(feature = "payouts")] currency: None, }) } fn customer_details() -> Option<types::ConnectorCustomerData> { Some(types::ConnectorCustomerData { ..utils::CustomerType::default().0 }) } fn token_details() -> Option<types::PaymentMethodTokenizationData> { Some(types::PaymentMethodTokenizationData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("04".to_string()), card_exp_year: Secret::new("2027".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, split_payments: None, mandate_id: None, setup_future_usage: None, customer_acceptance: None, setup_mandate_details: None, payment_method_type: None, router_return_url: None, capture_method: None, }) } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { ..utils::PaymentAuthorizeType::default().0 }) } async fn create_customer_and_get_token() -> Option<String> { let customer_response = CONNECTOR .create_connector_customer(customer_details(), get_default_payment_info(None, None)) .await .expect("Authorize payment response"); let connector_customer_id = match customer_response.response.unwrap() { PaymentsResponseData::ConnectorCustomerResponse(customer_data) => { Some(customer_data.connector_customer_id) } _ => None, }; let token_response = CONNECTOR .create_connector_pm_token( token_details(), get_default_payment_info(connector_customer_id, None), ) .await .expect("Authorize payment response"); match token_response.response.unwrap() { PaymentsResponseData::TokenizationResponse { token } => Some(token), _ => None, } } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment( payment_method_details(), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), None, get_default_payment_info(None, create_customer_and_get_token().await), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment( payment_method_details(), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(None, None), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let capture_response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .expect("Capture payment response"); let refund_txn_id = utils::get_connector_transaction_id(capture_response.response.clone()).unwrap(); let refund_connector_meta = utils::get_connector_metadata(capture_response.response); let response = CONNECTOR .refund_payment( refund_txn_id, Some(types::RefundsData { connector_metadata: refund_connector_meta, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(None, None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let capture_response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .expect("Capture payment response"); let refund_txn_id = utils::get_connector_transaction_id(capture_response.response.clone()).unwrap(); let refund_connector_meta = utils::get_connector_metadata(capture_response.response); let response = CONNECTOR .refund_payment( refund_txn_id, Some(types::RefundsData { refund_amount: 50, connector_metadata: refund_connector_meta, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(None, None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let capture_response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .expect("Capture payment response"); let refund_txn_id = utils::get_connector_transaction_id(capture_response.response.clone()).unwrap(); let refund_connector_meta = utils::get_connector_metadata(capture_response.response); let refund_response = CONNECTOR .refund_payment( refund_txn_id, Some(types::RefundsData { connector_metadata: refund_connector_meta, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(None, None), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None, None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(None, None), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), None, get_default_payment_info(None, create_customer_and_get_token().await), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { let payment_method_token = create_customer_and_get_token().await; let response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(None, payment_method_token.clone()), ) .await .unwrap(); //try refund for previous payment let transaction_id = utils::get_connector_transaction_id(response.response).unwrap(); for _x in 0..2 { tokio::time::sleep(Duration::from_secs(60)).await; // to avoid 404 error let refund_response = CONNECTOR .refund_payment( transaction_id.clone(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(None, payment_method_token.clone()), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), None, get_default_payment_info(None, create_customer_and_get_token().await), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(None, None), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let customer_response = CONNECTOR .create_connector_customer(customer_details(), get_default_payment_info(None, None)) .await .expect("Authorize payment response"); let connector_customer_id = match customer_response.response.unwrap() { PaymentsResponseData::ConnectorCustomerResponse(customer_data) => { Some(customer_data.connector_customer_id) } _ => None, }; let token_response = CONNECTOR .create_connector_pm_token( Some(types::PaymentMethodTokenizationData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("11".to_string()), card_exp_year: Secret::new("2027".to_string()), card_cvc: Secret::new("123456".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, split_payments: None, mandate_id: None, setup_future_usage: None, customer_acceptance: None, setup_mandate_details: None, payment_method_type: None, router_return_url: None, capture_method: None, }), get_default_payment_info(connector_customer_id, None), ) .await .expect("Authorize payment response"); assert_eq!( token_response.response.unwrap_err().reason, Some(r#"{"card_cvv":["The card cvv may not be greater than 99999."]}"#.to_string()), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let customer_response = CONNECTOR .create_connector_customer(customer_details(), get_default_payment_info(None, None)) .await .expect("Authorize payment response"); let connector_customer_id = match customer_response.response.unwrap() { PaymentsResponseData::ConnectorCustomerResponse(customer_data) => { Some(customer_data.connector_customer_id) } _ => None, }; let token_response = CONNECTOR .create_connector_pm_token( Some(types::PaymentMethodTokenizationData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("20".to_string()), card_exp_year: Secret::new("2027".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, split_payments: None, mandate_id: None, setup_future_usage: None, customer_acceptance: None, setup_mandate_details: None, payment_method_type: None, router_return_url: None, capture_method: None, }), get_default_payment_info(connector_customer_id, None), ) .await .expect("Authorize payment response"); assert_eq!( token_response.response.unwrap_err().reason, Some(r#"{"validation":["Tokenization Validation Errors: Month is invalid"]}"#.to_string()), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let customer_response = CONNECTOR .create_connector_customer(customer_details(), get_default_payment_info(None, None)) .await .expect("Authorize payment response"); let connector_customer_id = match customer_response.response.unwrap() { PaymentsResponseData::ConnectorCustomerResponse(customer_data) => { Some(customer_data.connector_customer_id) } _ => None, }; let token_response = CONNECTOR .create_connector_pm_token( Some(types::PaymentMethodTokenizationData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("04".to_string()), card_exp_year: Secret::new("2000".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: None, amount: None, currency: enums::Currency::USD, split_payments: None, mandate_id: None, setup_future_usage: None, customer_acceptance: None, setup_mandate_details: None, payment_method_type: None, router_return_url: None, capture_method: None, }), get_default_payment_info(connector_customer_id, None), ) .await .expect("Authorize payment response"); assert_eq!( token_response.response.unwrap_err().reason, Some(r#"{"validation":["Tokenization Validation Errors: Year is invalid"]}"#.to_string()), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] #[ignore = "Connector Refunds the payment on Void call for Auto Captured Payment"] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment( payment_method_details(), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info(None, None)) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment( "123456789".to_string(), None, get_default_payment_info(None, create_customer_and_get_token().await), ) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().reason, Some(r#"{"id":["The selected id is invalid."]}"#.to_string()), ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(None, create_customer_and_get_token().await), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().reason, Some(r#"{"total":["The total may not be greater than 1."]}"#.to_string()), ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/wise.rs
crates/router/tests/connectors/wise.rs
use hyperswitch_domain_models::address::{Address, AddressDetails}; use masking::Secret; use router::{ types, types::{api, storage::enums, PaymentAddress}, }; use crate::{ connector_auth, utils::{self, ConnectorActions, PaymentInfo}, }; struct WiseTest; impl ConnectorActions for WiseTest {} impl utils::Connector for WiseTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Adyen; utils::construct_connector_data_old( Box::new(Adyen::new()), types::Connector::Adyen, api::GetToken::Connector, None, ) } fn get_payout_data(&self) -> Option<api::ConnectorData> { use router::connector::Wise; Some(utils::construct_connector_data_old( Box::new(Wise::new()), types::Connector::Wise, api::GetToken::Connector, None, )) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .wise .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "wise".to_string() } } impl WiseTest { fn get_payout_info() -> Option<PaymentInfo> { Some(PaymentInfo { currency: Some(enums::Currency::GBP), address: Some(PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { country: Some(api_models::enums::CountryAlpha2::GB), city: Some("London".to_string()), zip: Some(Secret::new("10025".to_string())), line1: Some(Secret::new("50 Branson Ave".to_string())), ..Default::default() }), phone: None, email: None, }), None, None, )), payout_method_data: Some(api::PayoutMethodData::Bank(api::payouts::BankPayout::Bacs( api::BacsBankTransfer { bank_sort_code: "231470".to_string().into(), bank_account_number: "28821822".to_string().into(), bank_name: Some("Deutsche Bank".to_string()), bank_country_code: Some(enums::CountryAlpha2::NL), bank_city: Some("Amsterdam".to_string()), }, ))), ..Default::default() }) } } static CONNECTOR: WiseTest = WiseTest {}; /******************** Payouts test cases ********************/ // Creates a recipient at connector's end #[actix_web::test] async fn should_create_payout_recipient() { let payout_type = enums::PayoutType::Bank; let payment_info = WiseTest::get_payout_info(); let response = CONNECTOR .create_payout_recipient(payout_type, payment_info) .await .expect("Payout recipient creation response"); assert_eq!( response.status.unwrap(), enums::PayoutStatus::RequiresCreation ); } // Create BACS payout #[actix_web::test] async fn should_create_bacs_payout() { let payout_type = enums::PayoutType::Bank; let payout_info = WiseTest::get_payout_info(); // Create recipient let recipient_res = CONNECTOR .create_payout_recipient(payout_type.to_owned(), payout_info.to_owned()) .await .expect("Payout recipient response"); assert_eq!( recipient_res.status.unwrap(), enums::PayoutStatus::RequiresCreation ); // Create payout let create_res: types::PayoutsResponseData = CONNECTOR .create_payout(recipient_res.connector_payout_id, payout_type, payout_info) .await .expect("Payout bank creation response"); assert_eq!( create_res.status.unwrap(), enums::PayoutStatus::RequiresFulfillment ); } // Create and fulfill BACS payout #[actix_web::test] async fn should_create_and_fulfill_bacs_payout() { let payout_type = enums::PayoutType::Bank; let payout_info = WiseTest::get_payout_info(); // Create recipient let recipient_res = CONNECTOR .create_payout_recipient(payout_type.to_owned(), payout_info.to_owned()) .await .expect("Payout recipient response"); assert_eq!( recipient_res.status.unwrap(), enums::PayoutStatus::RequiresCreation ); let response = CONNECTOR .create_and_fulfill_payout(recipient_res.connector_payout_id, payout_type, payout_info) .await .expect("Payout bank creation and fulfill response"); assert_eq!(response.status.unwrap(), enums::PayoutStatus::Success); }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/fiservemea.rs
crates/router/tests/connectors/fiservemea.rs
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct FiservemeaTest; impl ConnectorActions for FiservemeaTest {} impl utils::Connector for FiservemeaTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Fiservemea; utils::construct_connector_data_old( Box::new(Fiservemea::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .fiservemea .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "fiservemea".to_string() } } static CONNECTOR: FiservemeaTest = FiservemeaTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/nuvei.rs
crates/router/tests/connectors/nuvei.rs
use std::str::FromStr; use masking::Secret; use router::types::{self, storage::enums}; use serde_json::json; use crate::{ connector_auth, utils::{self, ConnectorActions}, }; #[derive(Clone, Copy)] struct NuveiTest; impl ConnectorActions for NuveiTest {} impl utils::Connector for NuveiTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Nuvei; utils::construct_connector_data_old( Box::new(Nuvei::new()), types::Connector::Nuvei, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .nuvei .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "nuvei".to_string() } } static CONNECTOR: NuveiTest = NuveiTest {}; fn get_payment_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str("4444 3333 2222 1111").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }) } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(get_payment_data(), None) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(get_payment_data(), None, None) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( get_payment_data(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), None, ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(get_payment_data(), None) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), connector_meta: Some(json!({ "session_token": authorize_response.session_token.unwrap() })), ..Default::default() }), None, ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( get_payment_data(), Some(types::PaymentsCancelData { cancellation_reason: Some("requested_by_customer".to_string()), amount: Some(100), currency: Some(enums::Currency::USD), ..Default::default() }), None, ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund(get_payment_data(), None, None, None) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( get_payment_data(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(get_payment_data(), None) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(get_payment_data(), None) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), connector_meta: Some(json!({ "session_token": authorize_response.session_token.unwrap() })), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(get_payment_data(), None, None) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( get_payment_data(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), None, ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect card number. #[actix_web::test] async fn should_fail_payment_for_incorrect_card_number() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str("1234567891011").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Missing or invalid CardData data. Invalid credit card number.".to_string(), ); } // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "cardData.CVV is invalid".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Invalid expired date".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_succeed_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str("4000027891380961").unwrap(), card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..get_payment_data().unwrap() }), None, ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(get_payment_data(), None) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment( txn_id.unwrap(), Some(types::PaymentsCancelData { cancellation_reason: Some("requested_by_customer".to_string()), amount: Some(100), currency: Some(enums::Currency::USD), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(void_response.status, enums::AttemptStatus::Voided); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, None) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("Invalid relatedTransactionId") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_accept_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( get_payment_data(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/iatapay.rs
crates/router/tests/connectors/iatapay.rs
use hyperswitch_domain_models::address::{Address, AddressDetails, PhoneDetails}; use masking::Secret; use router::types::{self, api, storage::enums, AccessToken}; use crate::{ connector_auth, utils::{ self, get_connector_transaction_id, Connector, ConnectorActions, PaymentAuthorizeType, }, }; #[derive(Clone, Copy)] struct IatapayTest; impl ConnectorActions for IatapayTest {} impl Connector for IatapayTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Iatapay; utils::construct_connector_data_old( Box::new(Iatapay::new()), types::Connector::Iatapay, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .iatapay .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "iatapay".to_string() } } fn get_access_token() -> Option<AccessToken> { let connector = IatapayTest {}; match connector.get_auth_token() { types::ConnectorAuthType::SignatureKey { api_key, key1: _, api_secret: _, } => Some(AccessToken { token: api_key, expires: 60 * 5, }), _ => None, } } static CONNECTOR: IatapayTest = IatapayTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: Some(types::PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("first".to_string())), last_name: Some(Secret::new("last".to_string())), line1: Some(Secret::new("line1".to_string())), line2: Some(Secret::new("line2".to_string())), city: Some("city".to_string()), zip: Some(Secret::new("zip".to_string())), country: Some(api_models::enums::CountryAlpha2::NL), ..Default::default() }), phone: Some(PhoneDetails { number: Some(Secret::new("9123456789".to_string())), country_code: Some("+91".to_string()), }), email: None, }), None, None, )), access_token: get_access_token(), ..Default::default() }) } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { router_return_url: Some("https://hyperswitch.io".to_string()), webhook_url: Some("https://hyperswitch.io".to_string()), currency: enums::Currency::EUR, ..PaymentAuthorizeType::default().0 }) } // Cards Positive Tests // Creates a payment checking if its status is "requires_customer_action" for redirectinal flow #[actix_web::test] async fn should_only_create_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::AuthenticationPending); } //refund on an unsuccessed payments #[actix_web::test] async fn should_fail_for_refund_on_unsuccessed_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let refund_response = CONNECTOR .refund_payment( get_connector_transaction_id(response.response).unwrap(), Some(types::RefundsData { refund_amount: response.request.amount, webhook_url: Some("https://hyperswitch.io".to_string()), ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap_err().code, "BAD_REQUEST".to_string(), ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .refund_payment( "PWGKCZ91M4JJ0".to_string(), Some(types::RefundsData { refund_amount: 150, webhook_url: Some("https://hyperswitch.io".to_string()), ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "The amount to be refunded (100) is greater than the unrefunded amount (10.00): the amount of the payment is 10.00 and the refunded amount is 0.00", ); } #[actix_web::test] async fn should_sync_payment() { let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( "PE9OTYNP639XW".to_string(), ), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } #[actix_web::test] async fn should_sync_refund() { let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, "R5DNXUW4EY6PQ".to_string(), None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/nmi.rs
crates/router/tests/connectors/nmi.rs
use std::{str::FromStr, time::Duration}; use router::types::{self, domain, storage::enums}; use crate::{ connector_auth, utils::{self, ConnectorActions}, }; struct NmiTest; impl ConnectorActions for NmiTest {} impl utils::Connector for NmiTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Nmi; utils::construct_connector_data_old( Box::new(Nmi::new()), types::Connector::Nmi, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .nmi .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "nmi".to_string() } } static CONNECTOR: NmiTest = NmiTest {}; fn get_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), ..utils::CCardType::default().0 }), amount: 2023, ..utils::PaymentAuthorizeType::default().0 }) } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(get_payment_authorize_data(), None) .await .expect("Authorize payment response"); let transaction_id = utils::get_connector_transaction_id(response.response).unwrap(); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, ) .await .unwrap(); // Assert the sync response, it will be authorized in case of manual capture, for automatic it will be Completed Success assert_eq!(sync_response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_payment(get_payment_authorize_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorizing); let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Authorized); let capture_response = CONNECTOR .capture_payment(transaction_id.clone(), None, None) .await .unwrap(); assert_eq!( capture_response.status, enums::AttemptStatus::CaptureInitiated ); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Pending); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_payment(get_payment_authorize_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorizing); let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Authorized); let capture_response = CONNECTOR .capture_payment( transaction_id.clone(), Some(types::PaymentsCaptureData { amount_to_capture: 1000, ..utils::PaymentCaptureType::default().0 }), None, ) .await .unwrap(); assert_eq!( capture_response.status, enums::AttemptStatus::CaptureInitiated ); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Pending); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_payment(get_payment_authorize_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorizing); let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Authorized); let void_response = CONNECTOR .void_payment( transaction_id.clone(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("user_cancel".to_string()), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(void_response.status, enums::AttemptStatus::VoidInitiated); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Voided, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .authorize_payment(get_payment_authorize_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorizing); let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Authorized); let capture_response = CONNECTOR .capture_payment(transaction_id.clone(), None, None) .await .unwrap(); assert_eq!( capture_response.status, enums::AttemptStatus::CaptureInitiated ); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Pending); let refund_response = CONNECTOR .refund_payment(transaction_id.clone(), None, None) .await .unwrap(); assert_eq!(refund_response.status, enums::AttemptStatus::Pending); let sync_response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Pending, refund_response.response.unwrap().connector_refund_id, None, None, ) .await .unwrap(); assert_eq!( sync_response.response.unwrap().refund_status, enums::RefundStatus::Pending ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .authorize_payment(get_payment_authorize_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorizing); let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Authorized); let capture_response = CONNECTOR .capture_payment( transaction_id.clone(), Some(types::PaymentsCaptureData { amount_to_capture: 2023, ..utils::PaymentCaptureType::default().0 }), None, ) .await .unwrap(); assert_eq!( capture_response.status, enums::AttemptStatus::CaptureInitiated ); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Pending); let refund_response = CONNECTOR .refund_payment( transaction_id.clone(), Some(types::RefundsData { refund_amount: 1023, ..utils::PaymentRefundType::default().0 }), None, ) .await .unwrap(); assert_eq!(refund_response.status, enums::AttemptStatus::Pending); let sync_response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Pending, refund_response.response.unwrap().connector_refund_id, None, None, ) .await .unwrap(); assert_eq!( sync_response.response.unwrap().refund_status, enums::RefundStatus::Pending ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let response = CONNECTOR .make_payment(get_payment_authorize_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated); let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Pending); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment(get_payment_authorize_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated); let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Pending); let refund_response = CONNECTOR .refund_payment(transaction_id.clone(), None, None) .await .unwrap(); assert_eq!(refund_response.status, enums::AttemptStatus::Pending); let sync_response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Pending, refund_response.response.unwrap().connector_refund_id, None, None, ) .await .unwrap(); assert_eq!( sync_response.response.unwrap().refund_status, enums::RefundStatus::Pending ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let response = CONNECTOR .make_payment(get_payment_authorize_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated); let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Pending); let refund_response = CONNECTOR .refund_payment( transaction_id.clone(), Some(types::RefundsData { refund_amount: 1000, ..utils::PaymentRefundType::default().0 }), None, ) .await .unwrap(); assert_eq!(refund_response.status, enums::AttemptStatus::Pending); let sync_response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Pending, refund_response.response.unwrap().connector_refund_id, None, None, ) .await .unwrap(); assert_eq!( sync_response.response.unwrap().refund_status, enums::RefundStatus::Pending ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { let response = CONNECTOR .make_payment(get_payment_authorize_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated); let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Pending); //try refund for previous payment let transaction_id = utils::get_connector_transaction_id(response.response).unwrap(); for _x in 0..2 { tokio::time::sleep(Duration::from_secs(5)).await; // to avoid 404 error let refund_response = CONNECTOR .refund_payment( transaction_id.clone(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), None, ) .await .unwrap(); let sync_response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Pending, refund_response.response.unwrap().connector_refund_id, None, None, ) .await .unwrap(); assert_eq!( sync_response.response.unwrap().refund_status, enums::RefundStatus::Pending, ); } } // Creates a payment with incorrect CVC. #[ignore = "Connector returns SUCCESS status in case of invalid CVC"] #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() {} // Creates a payment with incorrect expiry month. #[ignore = "Connector returns SUCCESS status in case of expired month."] #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() {} // Creates a payment with incorrect expiry year. #[ignore = "Connector returns SUCCESS status in case of expired year."] #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() {} // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let response = CONNECTOR .make_payment(get_payment_authorize_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated); let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Pending); let void_response = CONNECTOR .void_payment(transaction_id.clone(), None, None) .await .unwrap(); assert_eq!(void_response.status, enums::AttemptStatus::VoidFailed); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let response = CONNECTOR .authorize_payment(get_payment_authorize_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorizing); let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Manual), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Authorized); let capture_response = CONNECTOR .capture_payment("9123456789".to_string(), None, None) .await .unwrap(); assert_eq!(capture_response.status, enums::AttemptStatus::CaptureFailed); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment(get_payment_authorize_data(), None) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated); let transaction_id = utils::get_connector_transaction_id(response.response.to_owned()).unwrap(); let sync_response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Pending, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( transaction_id.clone(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(sync_response.status, enums::AttemptStatus::Pending); let refund_response = CONNECTOR .refund_payment( transaction_id, Some(types::RefundsData { refund_amount: 3024, ..utils::PaymentRefundType::default().0 }), None, ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Failure ); }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/payme.rs
crates/router/tests/connectors/payme.rs
use std::str::FromStr; use common_utils::{pii::Email, types::MinorUnit}; use diesel_models::types::OrderDetailsWithAmount; use hyperswitch_domain_models::address::{Address, AddressDetails}; use masking::Secret; use router::types::{self, domain, storage::enums, PaymentAddress}; use crate::{ connector_auth, utils::{self, ConnectorActions, PaymentAuthorizeType}, }; #[derive(Clone, Copy)] struct PaymeTest; impl ConnectorActions for PaymeTest {} impl utils::Connector for PaymeTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Payme; utils::construct_connector_data_old( Box::new(Payme::new()), types::Connector::Payme, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .payme .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "payme".to_string() } } static CONNECTOR: PaymeTest = PaymeTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: Some(PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { city: None, country: None, line1: None, line2: None, line3: None, zip: None, state: None, first_name: Some(Secret::new("John".to_string())), last_name: Some(Secret::new("Doe".to_string())), origin_zip: None, }), phone: None, email: None, }), None, None, )), auth_type: None, access_token: None, connector_meta_data: None, connector_customer: None, payment_method_token: None, #[cfg(feature = "payouts")] currency: None, #[cfg(feature = "payouts")] payout_method_data: None, }) } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { order_details: Some(vec![OrderDetailsWithAmount { product_name: "iphone 13".to_string(), quantity: 1, amount: MinorUnit::new(1000), product_img_link: None, requires_shipping: None, product_id: None, category: None, sub_category: None, brand: None, product_type: None, product_tax_code: None, tax_rate: None, total_tax_amount: None, description: None, sku: None, upc: None, commodity_code: None, unit_of_measure: None, total_amount: None, unit_discount_amount: None, }]), router_return_url: Some("https://hyperswitch.io".to_string()), webhook_url: Some("https://hyperswitch.io".to_string()), email: Some(Email::from_str("test@gmail.com").unwrap()), payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_cvc: Secret::new("123".to_string()), card_exp_month: Secret::new("10".to_string()), card_exp_year: Secret::new("2025".to_string()), ..utils::CCardType::default().0 }), amount: 1000, ..PaymentAuthorizeType::default().0 }) } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] #[ignore = "Connector does not support partial capture"] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] #[ignore = "Connector does not supports sync"] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] #[ignore = "Connector does not supports void"] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Void flow not supported by Payme connector".to_string() ); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] #[ignore = "Connector does not supports sync"] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] #[ignore = "Connector does not supports sync"] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 100, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] #[ignore = "Connector does not supports sync"] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund Sync flow not supported by Payme connector", ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { amount: 100, currency: enums::Currency::ILS, payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), order_details: Some(vec![OrderDetailsWithAmount { product_name: "iphone 13".to_string(), quantity: 1, amount: MinorUnit::new(1000), product_img_link: None, requires_shipping: None, product_id: None, category: None, sub_category: None, brand: None, product_type: None, product_tax_code: None, tax_rate: None, total_tax_amount: None, description: None, sku: None, upc: None, commodity_code: None, unit_of_measure: None, total_amount: None, unit_discount_amount: None, }]), router_return_url: Some("https://hyperswitch.io".to_string()), webhook_url: Some("https://hyperswitch.io".to_string()), email: Some(Email::from_str("test@gmail.com").unwrap()), ..PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "internal_server_error".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { amount: 100, currency: enums::Currency::ILS, payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), order_details: Some(vec![OrderDetailsWithAmount { product_name: "iphone 13".to_string(), quantity: 1, amount: MinorUnit::new(1000), product_img_link: None, requires_shipping: None, product_id: None, category: None, sub_category: None, brand: None, product_type: None, product_tax_code: None, tax_rate: None, total_tax_amount: None, description: None, sku: None, upc: None, commodity_code: None, unit_of_measure: None, total_amount: None, unit_discount_amount: None, }]), router_return_url: Some("https://hyperswitch.io".to_string()), webhook_url: Some("https://hyperswitch.io".to_string()), email: Some(Email::from_str("test@gmail.com").unwrap()), ..PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "internal_server_error".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { amount: 100, currency: enums::Currency::ILS, payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2012".to_string()), ..utils::CCardType::default().0 }), order_details: Some(vec![OrderDetailsWithAmount { product_name: "iphone 13".to_string(), quantity: 1, amount: MinorUnit::new(1000), product_img_link: None, requires_shipping: None, product_id: None, category: None, sub_category: None, brand: None, product_type: None, product_tax_code: None, tax_rate: None, total_tax_amount: None, description: None, sku: None, upc: None, commodity_code: None, unit_of_measure: None, total_amount: None, unit_discount_amount: None, }]), router_return_url: Some("https://hyperswitch.io".to_string()), webhook_url: Some("https://hyperswitch.io".to_string()), email: Some(Email::from_str("test@gmail.com").unwrap()), ..PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "internal_server_error".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] #[ignore = "Connector does not supports void"] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "Void flow not supported by Payme connector" ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("internal_server_error") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 1500, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "internal_server_error", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/peachpayments.rs
crates/router/tests/connectors/peachpayments.rs
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct PeachpaymentsTest; impl ConnectorActions for PeachpaymentsTest {} impl utils::Connector for PeachpaymentsTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Peachpayments; utils::construct_connector_data_old( Box::new(Peachpayments::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .peachpayments .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "peachpayments".to_string() } } static CONNECTOR: PeachpaymentsTest = PeachpaymentsTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/breadpay.rs
crates/router/tests/connectors/breadpay.rs
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct BreadpayTest; impl ConnectorActions for BreadpayTest {} impl utils::Connector for BreadpayTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Breadpay; utils::construct_connector_data_old( Box::new(Breadpay::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .breadpay .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "breadpay".to_string() } } static CONNECTOR: BreadpayTest = BreadpayTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/prophetpay.rs
crates/router/tests/connectors/prophetpay.rs
use masking::Secret; use router::types::{self, domain, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct ProphetpayTest; impl ConnectorActions for ProphetpayTest {} impl utils::Connector for ProphetpayTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Prophetpay; utils::construct_connector_data_old( Box::new(&Prophetpay), types::Connector::Prophetpay, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .prophetpay .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "prophetpay".to_string() } } static CONNECTOR: ProphetpayTest = ProphetpayTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/dummyconnector.rs
crates/router/tests/connectors/dummyconnector.rs
use std::str::FromStr; use cards::CardNumber; use masking::Secret; use router::types::{self, domain, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct DummyConnectorTest; impl ConnectorActions for DummyConnectorTest {} impl utils::Connector for DummyConnectorTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::DummyConnector; utils::construct_connector_data_old( Box::new(DummyConnector::<1>::new()), types::Connector::DummyConnector1, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .dummyconnector .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "dummyconnector".to_string() } } static CONNECTOR: DummyConnectorTest = DummyConnectorTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect card number. #[actix_web::test] async fn should_fail_payment_for_incorrect_card_number() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: CardNumber::from_str("1234567891011").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card number is incorrect.".to_string(), ); } // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/getnet.rs
crates/router/tests/connectors/getnet.rs
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct GetnetTest; impl ConnectorActions for GetnetTest {} impl utils::Connector for GetnetTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Getnet; utils::construct_connector_data_old( Box::new(Getnet::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .getnet .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "getnet".to_string() } } static CONNECTOR: GetnetTest = GetnetTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/cashtocode.rs
crates/router/tests/connectors/cashtocode.rs
use common_utils::id_type; use hyperswitch_domain_models::address::{Address, AddressDetails}; use router::types::{self, domain, storage::enums}; use crate::{ connector_auth, utils::{self, ConnectorActions}, }; #[derive(Clone, Copy)] struct CashtocodeTest; impl ConnectorActions for CashtocodeTest {} impl utils::Connector for CashtocodeTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Cashtocode; utils::construct_connector_data_old( Box::new(Cashtocode::new()), types::Connector::Cashtocode, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .cashtocode .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "cashtocode".to_string() } } static CONNECTOR: CashtocodeTest = CashtocodeTest {}; impl CashtocodeTest { fn get_payment_authorize_data( payment_method_type: Option<enums::PaymentMethodType>, payment_method_data: domain::PaymentMethodData, ) -> Option<types::PaymentsAuthorizeData> { let cust_id = id_type::CustomerId::try_from(std::borrow::Cow::from("John Doe")); Some(types::PaymentsAuthorizeData { amount: 1000, currency: enums::Currency::EUR, payment_method_data, confirm: true, setup_future_usage: None, mandate_id: None, off_session: None, setup_mandate_details: None, capture_method: None, browser_info: None, order_details: None, order_category: None, email: None, customer_name: None, payment_experience: None, payment_method_type, session_token: None, enrolled_for_3ds: false, related_transaction_id: None, router_return_url: Some(String::from("https://google.com")), webhook_url: None, complete_authorize_url: None, customer_id: cust_id.ok(), surcharge_details: None, request_incremental_authorization: false, metadata: None, authentication_data: None, customer_acceptance: None, billing_descriptor: None, ..utils::PaymentAuthorizeType::default().0 }) } fn get_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: Some(types::PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { country: Some(api_models::enums::CountryAlpha2::US), ..Default::default() }), phone: None, email: None, }), None, None, )), ..Default::default() }) } } //fetch payurl for payment create #[actix_web::test] async fn should_fetch_pay_url_classic() { let authorize_response = CONNECTOR .make_payment( CashtocodeTest::get_payment_authorize_data( Some(enums::PaymentMethodType::ClassicReward), domain::payments::PaymentMethodData::Reward, ), CashtocodeTest::get_payment_info(), ) .await .unwrap(); assert_eq!( authorize_response.status, enums::AttemptStatus::AuthenticationPending ); } #[actix_web::test] async fn should_fetch_pay_url_evoucher() { let authorize_response = CONNECTOR .make_payment( CashtocodeTest::get_payment_authorize_data( Some(enums::PaymentMethodType::Evoucher), domain::payments::PaymentMethodData::Reward, ), CashtocodeTest::get_payment_info(), ) .await .unwrap(); assert_eq!( authorize_response.status, enums::AttemptStatus::AuthenticationPending ); }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/moneris.rs
crates/router/tests/connectors/moneris.rs
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct MonerisTest; impl ConnectorActions for MonerisTest {} impl utils::Connector for MonerisTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Moneris; utils::construct_connector_data_old( Box::new(Moneris::new()), types::Connector::Moneris, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .moneris .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "moneris".to_string() } } static CONNECTOR: MonerisTest = MonerisTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/tokenio.rs
crates/router/tests/connectors/tokenio.rs
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct TokenioTest; impl ConnectorActions for TokenioTest {} impl utils::Connector for TokenioTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Tokenio; utils::construct_connector_data_old( Box::new(Tokenio::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .tokenio .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "tokenio".to_string() } } static CONNECTOR: TokenioTest = TokenioTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/digitalvirgo.rs
crates/router/tests/connectors/digitalvirgo.rs
use masking::Secret; use router::{ types::{self, api, storage::enums, }}; use crate::utils::{self, ConnectorActions}; use test_utils::connector_auth; #[derive(Clone, Copy)] struct DigitalvirgoTest; impl ConnectorActions for DigitalvirgoTest {} impl utils::Connector for DigitalvirgoTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Digitalvirgo; api::ConnectorData { connector: Box::new(Digitalvirgo::new()), connector_name: types::Connector::Digitalvirgo, get_token: types::api::GetToken::Connector, merchant_connector_id: None, } } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .digitalvirgo .expect("Missing connector authentication configuration").into(), ) } fn get_name(&self) -> String { "digitalvirgo".to_string() } } static CONNECTOR: DigitalvirgoTest = DigitalvirgoTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund(payment_method_details(), None, None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund(payment_method_details(), None, None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: api::PaymentMethodData::Card(api::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: api::PaymentMethodData::Card(api::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/deutschebank.rs
crates/router/tests/connectors/deutschebank.rs
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct DeutschebankTest; impl ConnectorActions for DeutschebankTest {} impl utils::Connector for DeutschebankTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Deutschebank; utils::construct_connector_data_old( Box::new(Deutschebank::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .deutschebank .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "deutschebank".to_string() } } static CONNECTOR: DeutschebankTest = DeutschebankTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/bitpay.rs
crates/router/tests/connectors/bitpay.rs
use hyperswitch_domain_models::address::{Address, AddressDetails, PhoneDetails}; use masking::Secret; use router::types::{self, api, domain, storage::enums, PaymentAddress}; use crate::{ connector_auth, utils::{self, ConnectorActions}, }; #[derive(Clone, Copy)] struct BitpayTest; impl ConnectorActions for BitpayTest {} impl utils::Connector for BitpayTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Bitpay; utils::construct_connector_data_old( Box::new(Bitpay::new()), types::Connector::Bitpay, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .bitpay .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "bitpay".to_string() } } static CONNECTOR: BitpayTest = BitpayTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: Some(PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("first".to_string())), last_name: Some(Secret::new("last".to_string())), line1: Some(Secret::new("line1".to_string())), line2: Some(Secret::new("line2".to_string())), city: Some("city".to_string()), zip: Some(Secret::new("zip".to_string())), country: Some(api_models::enums::CountryAlpha2::IN), ..Default::default() }), phone: Some(PhoneDetails { number: Some(Secret::new("9123456789".to_string())), country_code: Some("+91".to_string()), }), email: None, }), None, None, )), ..Default::default() }) } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { amount: 1, currency: enums::Currency::USD, payment_method_data: domain::PaymentMethodData::Crypto(domain::CryptoData { pay_currency: None, network: None, }), confirm: true, setup_future_usage: None, mandate_id: None, off_session: None, setup_mandate_details: None, // capture_method: Some(capture_method), browser_info: None, order_details: None, order_category: None, email: None, customer_name: None, payment_experience: None, payment_method_type: None, session_token: None, enrolled_for_3ds: false, related_transaction_id: None, router_return_url: Some(String::from("https://google.com/")), webhook_url: Some(String::from("https://google.com/")), complete_authorize_url: None, capture_method: None, customer_id: None, surcharge_details: None, request_incremental_authorization: false, metadata: None, authentication_data: None, customer_acceptance: None, billing_descriptor: None, ..utils::PaymentAuthorizeType::default().0 }) } // Creates a payment using the manual capture flow #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let resp = response.clone().response.ok().unwrap(); assert_eq!(response.status, enums::AttemptStatus::AuthenticationPending); let endpoint = match resp { types::PaymentsResponseData::TransactionResponse { redirection_data, .. } => Some(redirection_data), _ => None, }; assert!(endpoint.is_some()) } // Synchronizes a successful transaction. #[actix_web::test] async fn should_sync_authorized_payment() { let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( "NPf27TDfyU5mhcTCw2oaq4".to_string(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a expired transaction. #[actix_web::test] async fn should_sync_expired_payment() { let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( "bUsFf4RjQEahjbjGcETRS".to_string(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Failure); }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/redsys.rs
crates/router/tests/connectors/redsys.rs
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct RedsysTest; impl ConnectorActions for RedsysTest {} impl utils::Connector for RedsysTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Redsys; utils::construct_connector_data_old( Box::new(Redsys::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .redsys .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "redsys".to_string() } } static CONNECTOR: RedsysTest = RedsysTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/trustpay.rs
crates/router/tests/connectors/trustpay.rs
use std::str::FromStr; use hyperswitch_domain_models::address::{Address, AddressDetails}; use masking::Secret; use router::types::{self, api, domain, storage::enums, BrowserInformation}; use crate::{ connector_auth, utils::{self, ConnectorActions}, }; #[derive(Clone, Copy)] struct TrustpayTest; impl ConnectorActions for TrustpayTest {} impl utils::Connector for TrustpayTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Trustpay; utils::construct_connector_data_old( Box::new(Trustpay::new()), types::Connector::Trustpay, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .trustpay .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "trustpay".to_string() } } fn get_default_browser_info() -> BrowserInformation { BrowserInformation { color_depth: Some(24), java_enabled: Some(false), java_script_enabled: Some(true), language: Some("en-US".to_string()), screen_height: Some(1080), screen_width: Some(1920), time_zone: Some(3600), accept_header: Some("*".to_string()), user_agent: Some("none".to_string()), ip_address: None, os_type: None, os_version: None, device_model: None, accept_language: Some("en".to_string()), referer: None, } } fn get_default_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), card_exp_year: Secret::new("25".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: Some(get_default_browser_info()), router_return_url: Some(String::from("http://localhost:8080")), ..utils::PaymentAuthorizeType::default().0 }) } fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: Some(types::PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("first".to_string())), last_name: Some(Secret::new("last".to_string())), line1: Some(Secret::new("line1".to_string())), line2: Some(Secret::new("line2".to_string())), city: Some("city".to_string()), zip: Some(Secret::new("zip".to_string())), country: Some(api_models::enums::CountryAlpha2::IN), ..Default::default() }), phone: None, email: None, }), None, None, )), ..Default::default() }) } static CONNECTOR: TrustpayTest = TrustpayTest {}; // Cards Positive Tests // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment( get_default_payment_authorize_data(), get_default_payment_info(), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment( get_default_payment_authorize_data(), get_default_payment_info(), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund( get_default_payment_authorize_data(), None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund( get_default_payment_authorize_data(), None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, None, ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect card number. #[actix_web::test] async fn should_fail_payment_for_incorrect_card_number() { let payment_authorize_data = types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("1234567891011").unwrap(), card_exp_year: Secret::new("25".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: Some(get_default_browser_info()), ..utils::PaymentAuthorizeType::default().0 }; let response = CONNECTOR .make_payment(Some(payment_authorize_data), get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Errors { code: 61, description: \"invalid payment data (country or brand)\" }".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let payment_authorize_data = Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), card_exp_year: Secret::new("22".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: Some(get_default_browser_info()), ..utils::PaymentAuthorizeType::default().0 }); let response = CONNECTOR .make_payment(payment_authorize_data, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Errors { code: 15, description: \"the provided expiration year is not valid\" }" .to_string(), ); }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/zen.rs
crates/router/tests/connectors/zen.rs
use std::str::FromStr; use cards::CardNumber; use common_utils::{pii::Email, types::MinorUnit}; use hyperswitch_domain_models::types::OrderDetailsWithAmount; use masking::Secret; use router::types::{self, domain, storage::enums}; use crate::{ connector_auth, utils::{self, ConnectorActions}, }; #[derive(Clone, Copy)] struct ZenTest; impl ConnectorActions for ZenTest {} impl utils::Connector for ZenTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Zen; utils::construct_connector_data_old( Box::new(&Zen), types::Connector::Zen, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .zen .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "zen".to_string() } } static CONNECTOR: ZenTest = ZenTest {}; // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[ignore = "Connector triggers 3DS payment on test card"] #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(None, None) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[ignore = "Connector triggers 3DS payment on test card and capture is not supported"] #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(None, None, None) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[ignore = "Connector triggers 3DS payment on test card and capture is not supported"] #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( None, Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), None, ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[ignore = "Connector triggers 3DS payment on test card"] #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(None, None) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), encoded_data: None, capture_method: None, sync_type: types::SyncRequestType::SinglePaymentSync, connector_meta: None, mandate_id: None, payment_method_type: None, currency: enums::Currency::USD, payment_experience: None, amount: MinorUnit::new(100), integrity_object: None, ..Default::default() }), None, ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[ignore = "Connector triggers 3DS payment on test card and void is not supported"] #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( None, Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), None, ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[ignore = "Connector triggers 3DS payment on test card and capture is not supported"] #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund(None, None, None, None) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[ignore = "Connector triggers 3DS payment on test card and capture is not supported"] #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( None, None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[ignore = "Connector triggers 3DS payment on test card and capture is not supported"] #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund(None, None, None, None) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, None, ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[ignore = "Connector triggers 3DS payment on test card"] #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR.make_payment(None, None).await.unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[ignore = "Connector triggers 3DS payment on test card"] #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR.make_payment(None, None).await.unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), encoded_data: None, capture_method: Some(enums::CaptureMethod::Automatic), sync_type: types::SyncRequestType::SinglePaymentSync, connector_meta: None, mandate_id: None, payment_method_type: None, currency: enums::Currency::USD, payment_experience: None, amount: MinorUnit::new(100), integrity_object: None, ..Default::default() }), None, ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[ignore = "Connector triggers 3DS payment on test card"] #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(None, None, None) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[ignore = "Connector triggers 3DS payment on test card"] #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), None, ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[ignore = "Connector triggers 3DS payment on test card"] #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), None, ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[ignore = "Connector triggers 3DS payment on test card"] #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(None, None, None) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, None, ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect card number. #[actix_web::test] async fn should_fail_payment_for_incorrect_card_number() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: CardNumber::from_str("1234567891011").unwrap(), ..utils::CCardType::default().0 }), order_details: Some(vec![OrderDetailsWithAmount { product_name: "iphone 13".to_string(), quantity: 1, amount: MinorUnit::new(1000), product_img_link: None, requires_shipping: None, product_id: None, category: None, sub_category: None, brand: None, product_type: None, product_tax_code: None, tax_rate: None, total_tax_amount: None, description: None, sku: None, upc: None, commodity_code: None, unit_of_measure: None, total_amount: None, unit_discount_amount: None, }]), email: Some(Email::from_str("test@gmail.com").unwrap()), webhook_url: Some("https://1635-116-74-253-164.ngrok-free.app".to_string()), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); assert_eq!( response .response .unwrap_err() .message .split_once(';') .unwrap() .0, "Request data doesn't pass validation".to_string(), ); } // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), order_details: Some(vec![OrderDetailsWithAmount { product_name: "iphone 13".to_string(), quantity: 1, amount: MinorUnit::new(1000), product_img_link: None, requires_shipping: None, product_id: None, category: None, sub_category: None, brand: None, product_type: None, product_tax_code: None, tax_rate: None, total_tax_amount: None, description: None, sku: None, upc: None, commodity_code: None, unit_of_measure: None, total_amount: None, unit_discount_amount: None, }]), email: Some(Email::from_str("test@gmail.com").unwrap()), webhook_url: Some("https://1635-116-74-253-164.ngrok-free.app".to_string()), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); assert_eq!( response .response .unwrap_err() .message .split_once(';') .unwrap() .0, "Request data doesn't pass validation".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), order_details: Some(vec![OrderDetailsWithAmount { product_name: "iphone 13".to_string(), quantity: 1, amount: MinorUnit::new(1000), product_img_link: None, requires_shipping: None, product_id: None, category: None, sub_category: None, brand: None, product_type: None, product_tax_code: None, tax_rate: None, total_tax_amount: None, description: None, sku: None, upc: None, commodity_code: None, unit_of_measure: None, total_amount: None, unit_discount_amount: None, }]), email: Some(Email::from_str("test@gmail.com").unwrap()), webhook_url: Some("https://1635-116-74-253-164.ngrok-free.app".to_string()), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); assert_eq!( response .response .unwrap_err() .message .split_once(';') .unwrap() .0, "Request data doesn't pass validation".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), order_details: Some(vec![OrderDetailsWithAmount { product_name: "iphone 13".to_string(), quantity: 1, amount: MinorUnit::new(1000), product_img_link: None, requires_shipping: None, product_id: None, category: None, sub_category: None, brand: None, product_type: None, product_tax_code: None, tax_rate: None, total_tax_amount: None, description: None, sku: None, upc: None, commodity_code: None, unit_of_measure: None, total_amount: None, unit_discount_amount: None, }]), email: Some(Email::from_str("test@gmail.com").unwrap()), webhook_url: Some("https://1635-116-74-253-164.ngrok-free.app".to_string()), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); assert_eq!( response .response .unwrap_err() .message .split_once(';') .unwrap() .0, "Request data doesn't pass validation".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[ignore = "Connector triggers 3DS payment on test card and void is not supported"] #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR.make_payment(None, None).await.unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, None) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[ignore = "Connector triggers 3DS payment on test card and capture is not supported"] #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, None) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[ignore = "Connector triggers 3DS payment on test card"] #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( None, Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/chargebee.rs
crates/router/tests/connectors/chargebee.rs
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct ChargebeeTest; impl ConnectorActions for ChargebeeTest {} impl utils::Connector for ChargebeeTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Chargebee; utils::construct_connector_data_old( Box::new(Chargebee::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .chargebee .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "chargebee".to_string() } } static CONNECTOR: ChargebeeTest = ChargebeeTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/finix.rs
crates/router/tests/connectors/finix.rs
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData}; use masking::Secret; use router::types::{self, api, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct FinixTest; impl ConnectorActions for FinixTest {} impl utils::Connector for FinixTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Finix; utils::construct_connector_data_old( Box::new(Finix::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .finix .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "finix".to_string() } } static CONNECTOR: FinixTest = FinixTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: PaymentMethodData::Card(Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/paybox.rs
crates/router/tests/connectors/paybox.rs
use masking::Secret; use router::types::{self, api, domain, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct PayboxTest; impl ConnectorActions for PayboxTest {} impl utils::Connector for PayboxTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Paybox; utils::construct_connector_data_old( Box::new(Paybox::new()), types::Connector::Plaid, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .paybox .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "paybox".to_string() } } static CONNECTOR: PayboxTest = PayboxTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/netcetera.rs
crates/router/tests/connectors/netcetera.rs
use router::types::{self, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct NetceteraTest; impl ConnectorActions for NetceteraTest {} impl utils::Connector for NetceteraTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Netcetera; utils::construct_connector_data_old( Box::new(&Netcetera), types::Connector::Netcetera, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .netcetera .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "netcetera".to_string() } } static CONNECTOR: NetceteraTest = NetceteraTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/worldpay.rs
crates/router/tests/connectors/worldpay.rs
use common_enums::GooglePayCardFundingSource; use futures::future::OptionFuture; use router::types::{self, domain, storage::enums}; use serde_json::json; use serial_test::serial; use wiremock::{ matchers::{body_json, method, path}, Mock, ResponseTemplate, }; use crate::{ connector_auth, utils::{self, ConnectorActions, LocalMock, MockConfig}, }; struct Worldpay; impl LocalMock for Worldpay {} impl ConnectorActions for Worldpay {} impl utils::Connector for Worldpay { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Worldpay; utils::construct_connector_data_old( Box::new(Worldpay::new()), types::Connector::Worldpay, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .worldpay .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "worldpay".to_string() } } #[actix_web::test] #[serial] async fn should_authorize_card_payment() { let conn = Worldpay {}; let _mock = conn.start_server(get_mock_config()).await; let response = conn.authorize_payment(None, None).await.unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized); assert_eq!( utils::get_connector_transaction_id(response.response), Some("123456".to_string()) ); } #[actix_web::test] #[serial] async fn should_authorize_gpay_payment() { let conn = Worldpay {}; let _mock = conn.start_server(get_mock_config()).await; let response = conn .authorize_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Wallet( domain::WalletData::GooglePay(domain::GooglePayWalletData { pm_type: "CARD".to_string(), description: "Visa1234567890".to_string(), info: domain::GooglePayPaymentMethodInfo { card_network: "VISA".to_string(), card_details: "1234".to_string(), assurance_details: None, card_funding_source: Some(GooglePayCardFundingSource::Unknown), }, tokenization_data: common_types::payments::GpayTokenizationData::Encrypted( common_types::payments::GpayEcryptedTokenizationData { token_type: "worldpay".to_string(), token: "someToken".to_string(), }, ), }), ), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized); assert_eq!( utils::get_connector_transaction_id(response.response), Some("123456".to_string()) ); } #[actix_web::test] #[serial] async fn should_authorize_applepay_payment() { let conn = Worldpay {}; let _mock = conn.start_server(get_mock_config()).await; let response = conn .authorize_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Wallet( domain::WalletData::ApplePay(domain::ApplePayWalletData { payment_data: common_types::payments::ApplePayPaymentData::Encrypted( "someData".to_string(), ), transaction_identifier: "someId".to_string(), payment_method: domain::ApplepayPaymentMethod { display_name: "someName".to_string(), network: "visa".to_string(), pm_type: "card".to_string(), }, }), ), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized); assert_eq!( utils::get_connector_transaction_id(response.response), Some("123456".to_string()) ); } #[actix_web::test] #[serial] async fn should_capture_already_authorized_payment() { let connector = Worldpay {}; let _mock = connector.start_server(get_mock_config()).await; let authorize_response = connector.authorize_payment(None, None).await.unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response: OptionFuture<_> = txn_id .map(|transaction_id| async move { connector .capture_payment(transaction_id, None, None) .await .unwrap() .status }) .into(); assert_eq!(response.await, Some(enums::AttemptStatus::Charged)); } #[actix_web::test] #[serial] async fn should_sync_payment() { let connector = Worldpay {}; let _mock = connector.start_server(get_mock_config()).await; let response = connector .sync_payment( Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( "112233".to_string(), ), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } #[actix_web::test] #[serial] async fn should_void_already_authorized_payment() { let connector = Worldpay {}; let _mock = connector.start_server(get_mock_config()).await; let authorize_response = connector.authorize_payment(None, None).await.unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response: OptionFuture<_> = txn_id .map(|transaction_id| async move { connector .void_payment(transaction_id, None, None) .await .unwrap() .status }) .into(); assert_eq!(response.await, Some(enums::AttemptStatus::Voided)); } #[actix_web::test] #[serial] async fn should_fail_capture_for_invalid_payment() { let connector = Worldpay {}; let _mock = connector.start_server(get_mock_config()).await; let authorize_response = connector.authorize_payment(None, None).await.unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Authorized); let response = connector .capture_payment("12345".to_string(), None, None) .await .unwrap(); let err = response.response.unwrap_err(); assert_eq!( err.message, "You must provide valid transaction id to capture payment".to_string() ); assert_eq!(err.code, "invalid-id".to_string()); } #[actix_web::test] #[serial] async fn should_refund_succeeded_payment() { let connector = Worldpay {}; let _mock = connector.start_server(get_mock_config()).await; //make a successful payment let response = connector.make_payment(None, None).await.unwrap(); //try refund for previous payment let transaction_id = utils::get_connector_transaction_id(response.response).unwrap(); let response = connector .refund_payment(transaction_id, None, None) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } #[actix_web::test] #[serial] async fn should_sync_refund() { let connector = Worldpay {}; let _mock = connector.start_server(get_mock_config()).await; let response = connector .sync_refund("654321".to_string(), None, None) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } fn get_mock_config() -> MockConfig { let authorized = json!({ "outcome": "authorized", "_links": { "payments:cancel": { "href": "/payments/authorizations/cancellations/123456" }, "payments:settle": { "href": "/payments/settlements/123456" }, "payments:partialSettle": { "href": "/payments/settlements/partials/123456" }, "payments:events": { "href": "/payments/events/123456" }, "curies": [ { "name": "payments", "href": "/rels/payments/{rel}", "templated": true } ] } }); let settled = json!({ "_links": { "payments:refund": { "href": "/payments/settlements/refunds/full/654321" }, "payments:partialRefund": { "href": "/payments/settlements/refunds/partials/654321" }, "payments:events": { "href": "/payments/events/654321" }, "curies": [ { "name": "payments", "href": "/rels/payments/{rel}", "templated": true } ] } }); let error_resp = json!({ "errorName": "invalid-id", "message": "You must provide valid transaction id to capture payment" }); let partial_refund = json!({ "_links": { "payments:events": { "href": "https://try.access.worldpay.com/payments/events/eyJrIjoiazNhYjYzMiJ9" }, "curies": [{ "name": "payments", "href": "https://try.access.worldpay.com/rels/payments/{rel}", "templated": true }] } }); let partial_refund_req_body = json!({ "value": { "amount": 100, "currency": "USD" }, "reference": "123456" }); let refunded = json!({ "lastEvent": "refunded", "_links": { "payments:cancel": "/payments/authorizations/cancellations/654321", "payments:settle": "/payments/settlements/full/654321", "payments:partialSettle": "/payments/settlements/partials/654321", "curies": [ { "name": "payments", "href": "/rels/payments/{rel}", "templated": true } ] } }); let sync_payment = json!({ "lastEvent": "authorized", "_links": { "payments:events": "/payments/authorizations/events/654321", "payments:settle": "/payments/settlements/full/654321", "payments:partialSettle": "/payments/settlements/partials/654321", "curies": [ { "name": "payments", "href": "/rels/payments/{rel}", "templated": true } ] } }); MockConfig { address: Some("127.0.0.1:9090".to_string()), mocks: vec![ Mock::given(method("POST")) .and(path("/payments/authorizations".to_string())) .respond_with(ResponseTemplate::new(201).set_body_json(authorized)), Mock::given(method("POST")) .and(path("/payments/settlements/123456".to_string())) .respond_with(ResponseTemplate::new(202).set_body_json(settled)), Mock::given(method("GET")) .and(path("/payments/events/112233".to_string())) .respond_with(ResponseTemplate::new(200).set_body_json(sync_payment)), Mock::given(method("POST")) .and(path("/payments/settlements/12345".to_string())) .respond_with(ResponseTemplate::new(400).set_body_json(error_resp)), Mock::given(method("POST")) .and(path( "/payments/settlements/refunds/partials/123456".to_string(), )) .and(body_json(partial_refund_req_body)) .respond_with(ResponseTemplate::new(202).set_body_json(partial_refund)), Mock::given(method("GET")) .and(path("/payments/events/654321".to_string())) .respond_with(ResponseTemplate::new(200).set_body_json(refunded)), ], } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/multisafepay.rs
crates/router/tests/connectors/multisafepay.rs
use hyperswitch_domain_models::address::{Address, AddressDetails}; use masking::Secret; use router::types::{self, domain, storage::enums, PaymentAddress}; use crate::{ connector_auth, utils::{self, ConnectorActions, PaymentInfo}, }; #[derive(Clone, Copy)] struct MultisafepayTest; impl ConnectorActions for MultisafepayTest {} impl utils::Connector for MultisafepayTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Multisafepay; utils::construct_connector_data_old( Box::new(Multisafepay::new()), types::Connector::Multisafepay, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .multisafepay .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "multisafepay".to_string() } } static CONNECTOR: MultisafepayTest = MultisafepayTest {}; fn get_default_payment_info() -> Option<PaymentInfo> { let address = Some(PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("John".to_string())), last_name: Some(Secret::new("Doe".to_string())), line1: Some(Secret::new("Kraanspoor".to_string())), line2: Some(Secret::new("line2".to_string())), line3: Some(Secret::new("line3".to_string())), city: Some("Amsterdam".to_string()), zip: Some(Secret::new("1033SC".to_string())), country: Some(api_models::enums::CountryAlpha2::NL), state: Some(Secret::new("Amsterdam".to_string())), origin_zip: None, }), phone: None, email: None, }), None, None, )); Some(PaymentInfo { address, ..PaymentInfo::default() }) } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[ignore = "Connector supports only 3ds flow"] #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(None, get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[ignore = "Connector supports only 3ds flow"] #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(None, None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[ignore = "Connector supports only 3ds flow"] #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( None, Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[ignore = "Connector supports only 3ds flow"] #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(None, get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!( authorize_response.status, enums::AttemptStatus::AuthenticationPending, ); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), None, ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[ignore = "Connector supports only 3ds flow"] #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( None, Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[ignore = "Connector supports only 3ds flow"] #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund(None, None, None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[ignore = "Connector supports only 3ds flow"] #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( None, None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[ignore = "Connector supports only 3ds flow"] #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund(None, None, None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, None, ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[ignore = "Connector supports only 3ds flow"] #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(None, get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[ignore = "Connector supports only 3ds flow"] #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(None, get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[ignore = "Connector supports only 3ds flow"] #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(None, None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[ignore = "Connector supports only 3ds flow"] #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[ignore = "Connector supports only 3ds flow"] #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[ignore = "Connector supports only 3ds flow"] #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(None, None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, None, ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[ignore = "Connector doesn't fail invalid cvv scenario"] #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("123498765".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert!(response.response.is_err()); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert!(response.response.is_err()); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert!(response.response.is_err()); } // Voids a payment using automatic capture flow (Non 3DS). #[ignore = "Connector supports only 3ds flow"] #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(None, get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment(txn_id.unwrap(), None, None) .await .unwrap(); assert_eq!( void_response.response.unwrap_err().message, "You cannot cancel this PaymentIntent because it has a status of succeeded." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("Something went wrong") ); } // Refunds a payment with refund amount higher than payment amount. #[ignore = "Connector supports only 3ds flow"] #[actix_web::test] async fn should_fail_for_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( None, Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert!(response.response.is_err()); }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/adyenplatform.rs
crates/router/tests/connectors/adyenplatform.rs
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/config_importer/src/cli.rs
crates/config_importer/src/cli.rs
use std::path::PathBuf; /// Utility to import a hyperswitch TOML configuration file, convert it into environment variable /// key-value pairs, and export it in the specified format. #[derive(clap::Parser, Debug)] #[command(arg_required_else_help = true)] pub(crate) struct Args { /// Input TOML configuration file. #[arg(short, long, value_name = "FILE")] pub(crate) input_file: PathBuf, /// The format to convert the environment variables to. #[arg( value_enum, short = 'f', long, value_name = "FORMAT", default_value = "kubernetes-json" )] pub(crate) output_format: OutputFormat, /// Output file. Output will be written to stdout if not specified. #[arg(short, long, value_name = "FILE")] pub(crate) output_file: Option<PathBuf>, /// Prefix to be used for each environment variable in the generated output. #[arg(short, long, default_value = "ROUTER")] pub(crate) prefix: String, } /// The output format to convert environment variables to. #[derive(clap::ValueEnum, Clone, Copy, Debug)] pub(crate) enum OutputFormat { /// Converts each environment variable to an object containing `name` and `value` fields. /// /// ```json /// { /// "name": "ENVIRONMENT", /// "value": "PRODUCTION" /// } /// ``` KubernetesJson, }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/config_importer/src/main.rs
crates/config_importer/src/main.rs
mod cli; use std::io::{BufWriter, Write}; use anyhow::Context; /// The separator used in environment variable names. const ENV_VAR_SEPARATOR: &str = "__"; #[cfg(not(feature = "preserve_order"))] type EnvironmentVariableMap = std::collections::HashMap<String, String>; #[cfg(feature = "preserve_order")] type EnvironmentVariableMap = indexmap::IndexMap<String, String>; fn main() -> anyhow::Result<()> { let args = <cli::Args as clap::Parser>::parse(); // Read input TOML file let toml_contents = std::fs::read_to_string(args.input_file).context("Failed to read input file")?; let table = toml_contents .parse::<toml::Table>() .context("Failed to parse TOML file contents")?; // Parse TOML file contents to a `HashMap` of environment variable name and value pairs let env_vars = table .iter() .flat_map(|(key, value)| process_toml_value(&args.prefix, key, value)) .collect::<EnvironmentVariableMap>(); let writer: BufWriter<Box<dyn Write>> = match args.output_file { // Write to file if output file is specified Some(file) => BufWriter::new(Box::new( std::fs::OpenOptions::new() .create(true) .write(true) .truncate(true) .open(file) .context("Failed to open output file")?, )), // Write to stdout otherwise None => BufWriter::new(Box::new(std::io::stdout().lock())), }; // Write environment variables in specified format match args.output_format { cli::OutputFormat::KubernetesJson => { let k8s_env_vars = env_vars .into_iter() .map(|(name, value)| KubernetesEnvironmentVariable { name, value }) .collect::<Vec<_>>(); serde_json::to_writer_pretty(writer, &k8s_env_vars) .context("Failed to serialize environment variables as JSON")? } } Ok(()) } fn process_toml_value( prefix: impl std::fmt::Display + Clone, key: impl std::fmt::Display + Clone, value: &toml::Value, ) -> Vec<(String, String)> { let key_with_prefix = format!("{prefix}{ENV_VAR_SEPARATOR}{key}").to_ascii_uppercase(); match value { toml::Value::String(s) => vec![(key_with_prefix, s.to_owned())], toml::Value::Integer(i) => vec![(key_with_prefix, i.to_string())], toml::Value::Float(f) => vec![(key_with_prefix, f.to_string())], toml::Value::Boolean(b) => vec![(key_with_prefix, b.to_string())], toml::Value::Datetime(dt) => vec![(key_with_prefix, dt.to_string())], toml::Value::Array(values) => { if values.is_empty() { return vec![(key_with_prefix, String::new())]; } // This logic does not support / account for arrays of tables or arrays of arrays. let (_processed_keys, processed_values) = values .iter() .flat_map(|v| process_toml_value(prefix.clone(), key.clone(), v)) .unzip::<_, _, Vec<String>, Vec<String>>(); vec![(key_with_prefix, processed_values.join(","))] } toml::Value::Table(map) => map .into_iter() .flat_map(|(k, v)| process_toml_value(key_with_prefix.clone(), k, v)) .collect(), } } /// The Kubernetes environment variable structure containing a name and a value. #[derive(Debug, serde::Serialize, serde::Deserialize)] pub(crate) struct KubernetesEnvironmentVariable { name: String, value: String, }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid_wasm/src/lib.rs
crates/euclid_wasm/src/lib.rs
#![allow(non_upper_case_globals)] mod types; mod utils; use std::{ collections::{HashMap, HashSet}, str::FromStr, sync::OnceLock, }; use api_models::{ enums as api_model_enums, routing::ConnectorSelection, surcharge_decision_configs::SurchargeDecisionConfigs, }; use common_types::three_ds_decision_rule_engine::ThreeDSDecisionRule; use connector_configs::{ common_config::{ConnectorApiIntegrationPayload, DashboardRequestPayload}, connector, }; use currency_conversion::{ conversion::convert as convert_currency, types as currency_conversion_types, }; use euclid::{ backend::{inputs, interpreter::InterpreterBackend, EuclidBackend}, dssa::{self, analyzer, graph::CgraphExt, state_machine}, enums::RoutableConnectors, frontend::{ ast, dir::{self, enums as dir_enums, EuclidDirFilter}, }, }; use strum::{EnumMessage, EnumProperty, VariantNames}; use wasm_bindgen::prelude::*; use crate::utils::JsResultExt; type JsResult = Result<JsValue, JsValue>; use api_models::payment_methods::CountryCodeWithName; #[cfg(feature = "payouts")] use common_enums::PayoutStatus; use common_enums::{ CountryAlpha2, DisputeStatus, EventClass, EventType, IntentStatus, MandateStatus, MerchantCategoryCode, MerchantCategoryCodeWithName, RefundStatus, SubscriptionStatus, }; use strum::IntoEnumIterator; struct SeedData { cgraph: hyperswitch_constraint_graph::ConstraintGraph<dir::DirValue>, connectors: Vec<ast::ConnectorChoice>, } static SEED_DATA: OnceLock<SeedData> = OnceLock::new(); static SEED_FOREX: OnceLock<currency_conversion_types::ExchangeRates> = OnceLock::new(); #[wasm_bindgen] extern "C" { #[wasm_bindgen(js_namespace = console, js_name = log)] fn console_log(s: &str); #[wasm_bindgen(js_namespace = console, js_name = error)] fn console_error(s: &str); } /// This function can be used by the frontend to educate wasm about the forex rates data. /// The input argument is a struct fields base_currency and conversion where later is all the conversions associated with the base_currency /// to all different currencies present. #[wasm_bindgen(js_name = setForexData)] pub fn seed_forex(forex: JsValue) -> JsResult { let forex: currency_conversion_types::ExchangeRates = serde_wasm_bindgen::from_value(forex)?; SEED_FOREX .set(forex) .map_err(|_| "Forex has already been seeded".to_string()) .err_to_js()?; Ok(JsValue::NULL) } /// This function can be used to perform currency_conversion on the input amount, from_currency, /// to_currency which are all expected to be one of currencies we already have in our Currency /// enum. #[wasm_bindgen(js_name = convertCurrency)] pub fn convert_forex_value(amount: i64, from_currency: JsValue, to_currency: JsValue) -> JsResult { let forex_data = SEED_FOREX .get() .ok_or("Forex Data not seeded") .err_to_js()?; let from_currency: common_enums::Currency = serde_wasm_bindgen::from_value(from_currency)?; let to_currency: common_enums::Currency = serde_wasm_bindgen::from_value(to_currency)?; let converted_amount = convert_currency(forex_data, from_currency, to_currency, amount) .map_err(|_| "conversion not possible for provided values") .err_to_js()?; Ok(serde_wasm_bindgen::to_value(&converted_amount)?) } /// This function can be used by the frontend to get all the two letter country codes /// along with their country names. #[wasm_bindgen(js_name=getTwoLetterCountryCode)] pub fn get_two_letter_country_code() -> JsResult { let country_code_with_name = CountryAlpha2::iter() .map(|country_code| CountryCodeWithName { code: country_code, name: common_enums::Country::from_alpha2(country_code), }) .collect::<Vec<_>>(); Ok(serde_wasm_bindgen::to_value(&country_code_with_name)?) } /// This function can be used by the frontend to get all the merchant category codes /// along with their names. #[wasm_bindgen(js_name=getMerchantCategoryCodeWithName)] pub fn get_merchant_category_code_with_name() -> JsResult { let merchant_category_codes_with_name = vec![5411, 7011, 763, 8111, 5021, 4816, 5661] .into_iter() .filter_map(|mcc_value| match MerchantCategoryCode::new(mcc_value) { Ok(mcc) => match mcc.get_category_name() { Ok(mcc_name) => Some(MerchantCategoryCodeWithName { code: mcc.clone(), name: mcc_name.to_string(), }), Err(err) => { console_error(&format!( "Failed to get category name for MCC {}: {:?}", mcc_value, err )); None } }, Err(err) => { console_error(&format!( "Failed to create MCC for value {}: {:?}", mcc_value, err )); None } }) .collect::<Vec<_>>(); Ok(serde_wasm_bindgen::to_value( &merchant_category_codes_with_name, )?) } /// This function can be used by the frontend to provide the WASM with information about /// all the merchant's connector accounts. The input argument is a vector of all the merchant's /// connector accounts from the API. #[cfg(feature = "v1")] #[wasm_bindgen(js_name = seedKnowledgeGraph)] pub fn seed_knowledge_graph(mcas: JsValue) -> JsResult { let mcas: Vec<api_models::admin::MerchantConnectorResponse> = serde_wasm_bindgen::from_value(mcas)?; let connectors: Vec<ast::ConnectorChoice> = mcas .iter() .map(|mca| { Ok::<_, strum::ParseError>(ast::ConnectorChoice { connector: RoutableConnectors::from_str(&mca.connector_name)?, }) }) .collect::<Result<_, _>>() .map_err(|_| "invalid connector name received") .err_to_js()?; let pm_filter = kgraph_utils::types::PaymentMethodFilters(HashMap::new()); let config = kgraph_utils::types::CountryCurrencyFilter { connector_configs: HashMap::new(), default_configs: Some(pm_filter), }; let mca_graph = kgraph_utils::mca::make_mca_graph(mcas, &config).err_to_js()?; let analysis_graph = hyperswitch_constraint_graph::ConstraintGraph::combine( &mca_graph, &dssa::truth::ANALYSIS_GRAPH, ) .err_to_js()?; SEED_DATA .set(SeedData { cgraph: analysis_graph, connectors, }) .map_err(|_| "Knowledge Graph has been already seeded".to_string()) .err_to_js()?; Ok(JsValue::NULL) } /// This function allows the frontend to get all the merchant's configured /// connectors that are valid for a rule based on the conditions specified in /// the rule #[wasm_bindgen(js_name = getValidConnectorsForRule)] pub fn get_valid_connectors_for_rule(rule: JsValue) -> JsResult { let seed_data = SEED_DATA.get().ok_or("Data not seeded").err_to_js()?; let rule: ast::Rule<ConnectorSelection> = serde_wasm_bindgen::from_value(rule)?; let dir_rule = ast::lowering::lower_rule(rule).err_to_js()?; let mut valid_connectors: Vec<(ast::ConnectorChoice, dir::DirValue)> = seed_data .connectors .iter() .cloned() .map(|choice| (choice.clone(), dir::DirValue::Connector(Box::new(choice)))) .collect(); let mut invalid_connectors: HashSet<ast::ConnectorChoice> = HashSet::new(); let mut ctx_manager = state_machine::RuleContextManager::new(&dir_rule, &[]); let dummy_meta = HashMap::new(); // For every conjunctive context in the Rule, verify validity of all still-valid connectors // using the knowledge graph while let Some(ctx) = ctx_manager.advance_mut().err_to_js()? { // Standalone conjunctive context analysis to ensure the context itself is valid before // checking it against merchant's connectors seed_data .cgraph .perform_context_analysis( ctx, &mut hyperswitch_constraint_graph::Memoization::new(), None, ) .err_to_js()?; // Update conjunctive context and run analysis on all of merchant's connectors. for (conn, choice) in &valid_connectors { if invalid_connectors.contains(conn) { continue; } let ctx_val = dssa::types::ContextValue::assertion(choice, &dummy_meta); ctx.push(ctx_val); let analysis_result = seed_data.cgraph.perform_context_analysis( ctx, &mut hyperswitch_constraint_graph::Memoization::new(), None, ); if analysis_result.is_err() { invalid_connectors.insert(conn.clone()); } ctx.pop(); } } valid_connectors.retain(|(k, _)| !invalid_connectors.contains(k)); let valid_connectors: Vec<ast::ConnectorChoice> = valid_connectors.into_iter().map(|c| c.0).collect(); Ok(serde_wasm_bindgen::to_value(&valid_connectors)?) } #[wasm_bindgen(js_name = analyzeProgram)] pub fn analyze_program(js_program: JsValue) -> JsResult { let program: ast::Program<ConnectorSelection> = serde_wasm_bindgen::from_value(js_program)?; analyzer::analyze(program, SEED_DATA.get().map(|sd| &sd.cgraph)).err_to_js()?; Ok(JsValue::NULL) } #[wasm_bindgen(js_name = runProgram)] pub fn run_program(program: JsValue, input: JsValue) -> JsResult { let program: ast::Program<ConnectorSelection> = serde_wasm_bindgen::from_value(program)?; let input: inputs::BackendInput = serde_wasm_bindgen::from_value(input)?; let backend = InterpreterBackend::with_program(program).err_to_js()?; let res: euclid::backend::BackendOutput<ConnectorSelection> = backend.execute(input).err_to_js()?; Ok(serde_wasm_bindgen::to_value(&res)?) } #[wasm_bindgen(js_name = getAllConnectors)] pub fn get_all_connectors() -> JsResult { Ok(serde_wasm_bindgen::to_value(RoutableConnectors::VARIANTS)?) } #[wasm_bindgen(js_name = getAllKeys)] pub fn get_all_keys() -> JsResult { let excluded_keys = [ "Connector", // 3DS Decision Rule Keys should not be included in the payument routing keys "issuer_name", "customer_device_platform", "customer_device_type", "customer_device_display_size", "acquirer_country", "acquirer_fraud_rate", ]; let keys: Vec<&'static str> = dir::DirKeyKind::VARIANTS .iter() .copied() .filter(|s| !excluded_keys.contains(s)) .collect(); Ok(serde_wasm_bindgen::to_value(&keys)?) } #[wasm_bindgen(js_name = getKeyType)] pub fn get_key_type(key: &str) -> Result<String, String> { let key = dir::DirKeyKind::from_str(key).map_err(|_| "Invalid key received".to_string())?; let key_str = key.get_type().to_string(); Ok(key_str) } #[wasm_bindgen(js_name = getThreeDsKeys)] pub fn get_three_ds_keys() -> JsResult { let keys = <common_types::payments::ConditionalConfigs as EuclidDirFilter>::ALLOWED; Ok(serde_wasm_bindgen::to_value(keys)?) } #[wasm_bindgen(js_name= getSurchargeKeys)] pub fn get_surcharge_keys() -> JsResult { let keys = <SurchargeDecisionConfigs as EuclidDirFilter>::ALLOWED; Ok(serde_wasm_bindgen::to_value(keys)?) } #[wasm_bindgen(js_name= getThreeDsDecisionRuleKeys)] pub fn get_three_ds_decision_rule_keys() -> JsResult { let keys = <ThreeDSDecisionRule as EuclidDirFilter>::ALLOWED; Ok(serde_wasm_bindgen::to_value(keys)?) } #[wasm_bindgen(js_name=parseToString)] pub fn parser(val: String) -> String { ron_parser::my_parse(val) } #[wasm_bindgen(js_name = getVariantValues)] pub fn get_variant_values(key: &str) -> Result<JsValue, JsValue> { let key = dir::DirKeyKind::from_str(key).map_err(|_| "Invalid key received".to_string())?; let variants: &[&str] = match key { dir::DirKeyKind::PaymentMethod => dir_enums::PaymentMethod::VARIANTS, dir::DirKeyKind::CardType => dir_enums::CardType::VARIANTS, dir::DirKeyKind::CardNetwork => dir_enums::CardNetwork::VARIANTS, dir::DirKeyKind::PayLaterType => dir_enums::PayLaterType::VARIANTS, dir::DirKeyKind::WalletType => dir_enums::WalletType::VARIANTS, dir::DirKeyKind::BankRedirectType => dir_enums::BankRedirectType::VARIANTS, dir::DirKeyKind::CryptoType => dir_enums::CryptoType::VARIANTS, dir::DirKeyKind::RewardType => dir_enums::RewardType::VARIANTS, dir::DirKeyKind::AuthenticationType => dir_enums::AuthenticationType::VARIANTS, dir::DirKeyKind::CaptureMethod => dir_enums::CaptureMethod::VARIANTS, dir::DirKeyKind::PaymentCurrency => dir_enums::PaymentCurrency::VARIANTS, dir::DirKeyKind::BusinessCountry => dir_enums::Country::VARIANTS, dir::DirKeyKind::BillingCountry => dir_enums::Country::VARIANTS, dir::DirKeyKind::BankTransferType => dir_enums::BankTransferType::VARIANTS, dir::DirKeyKind::UpiType => dir_enums::UpiType::VARIANTS, dir::DirKeyKind::SetupFutureUsage => dir_enums::SetupFutureUsage::VARIANTS, dir::DirKeyKind::PaymentType => dir_enums::PaymentType::VARIANTS, dir::DirKeyKind::MandateType => dir_enums::MandateType::VARIANTS, dir::DirKeyKind::MandateAcceptanceType => dir_enums::MandateAcceptanceType::VARIANTS, dir::DirKeyKind::CardRedirectType => dir_enums::CardRedirectType::VARIANTS, dir::DirKeyKind::GiftCardType => dir_enums::GiftCardType::VARIANTS, dir::DirKeyKind::VoucherType => dir_enums::VoucherType::VARIANTS, dir::DirKeyKind::BankDebitType => dir_enums::BankDebitType::VARIANTS, dir::DirKeyKind::RealTimePaymentType => dir_enums::RealTimePaymentType::VARIANTS, dir::DirKeyKind::OpenBankingType => dir_enums::OpenBankingType::VARIANTS, dir::DirKeyKind::MobilePaymentType => dir_enums::MobilePaymentType::VARIANTS, dir::DirKeyKind::IssuerCountry => dir_enums::Country::VARIANTS, dir::DirKeyKind::AcquirerCountry => dir_enums::Country::VARIANTS, dir::DirKeyKind::CustomerDeviceType => dir_enums::CustomerDeviceType::VARIANTS, dir::DirKeyKind::CustomerDevicePlatform => dir_enums::CustomerDevicePlatform::VARIANTS, dir::DirKeyKind::TransactionInitiator => dir_enums::TransactionInitiator::VARIANTS, dir::DirKeyKind::CustomerDeviceDisplaySize => { dir_enums::CustomerDeviceDisplaySize::VARIANTS } dir::DirKeyKind::NetworkTokenType => dir_enums::NetworkTokenType::VARIANTS, dir::DirKeyKind::PaymentAmount | dir::DirKeyKind::Connector | dir::DirKeyKind::CardBin | dir::DirKeyKind::ExtendedCardBin | dir::DirKeyKind::BusinessLabel | dir::DirKeyKind::MetaData | dir::DirKeyKind::IssuerName | dir::DirKeyKind::AcquirerFraudRate => Err("Key does not have variants".to_string())?, }; Ok(serde_wasm_bindgen::to_value(variants)?) } #[wasm_bindgen(js_name = addTwo)] pub fn add_two(n1: i64, n2: i64) -> i64 { n1 + n2 } #[wasm_bindgen(js_name = getDescriptionCategory)] pub fn get_description_category() -> JsResult { let keys = dir::DirKeyKind::VARIANTS .iter() .copied() .filter(|s| s != &"Connector") .collect::<Vec<&'static str>>(); let mut category: HashMap<Option<&str>, Vec<types::Details<'_>>> = HashMap::new(); for key in keys { let dir_key = dir::DirKeyKind::from_str(key).map_err(|_| "Invalid key received".to_string())?; let details = types::Details { description: dir_key.get_detailed_message(), kind: dir_key.clone(), }; category .entry(dir_key.get_str("Category")) .and_modify(|val| val.push(details.clone())) .or_insert(vec![details]); } Ok(serde_wasm_bindgen::to_value(&category)?) } #[wasm_bindgen(js_name = getConnectorConfig)] pub fn get_connector_config(key: &str) -> JsResult { let key = api_model_enums::Connector::from_str(key) .map_err(|_| "Invalid key received".to_string())?; let res = connector::ConnectorConfig::get_connector_config(key)?; Ok(serde_wasm_bindgen::to_value(&res)?) } #[wasm_bindgen(js_name = getBillingConnectorConfig)] pub fn get_billing_connector_config(key: &str) -> JsResult { let key = api_model_enums::BillingConnectors::from_str(key) .map_err(|_| "Invalid key received".to_string())?; let res = connector::ConnectorConfig::get_billing_connector_config(key)?; Ok(serde_wasm_bindgen::to_value(&res)?) } #[cfg(feature = "payouts")] #[wasm_bindgen(js_name = getPayoutConnectorConfig)] pub fn get_payout_connector_config(key: &str) -> JsResult { let key = api_model_enums::PayoutConnectors::from_str(key) .map_err(|_| "Invalid key received".to_string())?; let res = connector::ConnectorConfig::get_payout_connector_config(key)?; Ok(serde_wasm_bindgen::to_value(&res)?) } #[wasm_bindgen(js_name = getAuthenticationConnectorConfig)] pub fn get_authentication_connector_config(key: &str) -> JsResult { let key = api_model_enums::AuthenticationConnectors::from_str(key) .map_err(|_| "Invalid key received".to_string())?; let res = connector::ConnectorConfig::get_authentication_connector_config(key)?; Ok(serde_wasm_bindgen::to_value(&res)?) } #[wasm_bindgen(js_name = getTaxProcessorConfig)] pub fn get_tax_processor_config(key: &str) -> JsResult { let key = api_model_enums::TaxConnectors::from_str(key) .map_err(|_| "Invalid key received".to_string())?; let res = connector::ConnectorConfig::get_tax_processor_config(key)?; Ok(serde_wasm_bindgen::to_value(&res)?) } #[wasm_bindgen(js_name = getPMAuthenticationProcessorConfig)] pub fn get_pm_authentication_processor_config(key: &str) -> JsResult { let key: api_model_enums::PmAuthConnectors = api_model_enums::PmAuthConnectors::from_str(key) .map_err(|_| "Invalid key received".to_string())?; let res = connector::ConnectorConfig::get_pm_authentication_processor_config(key)?; Ok(serde_wasm_bindgen::to_value(&res)?) } #[wasm_bindgen(js_name = getRequestPayload)] pub fn get_request_payload(input: JsValue, response: JsValue) -> JsResult { let input: DashboardRequestPayload = serde_wasm_bindgen::from_value(input)?; let api_response: ConnectorApiIntegrationPayload = serde_wasm_bindgen::from_value(response)?; let result = DashboardRequestPayload::create_connector_request(input, api_response); Ok(serde_wasm_bindgen::to_value(&result)?) } #[wasm_bindgen(js_name = getResponsePayload)] pub fn get_response_payload(input: JsValue) -> JsResult { let input: ConnectorApiIntegrationPayload = serde_wasm_bindgen::from_value(input)?; let result = ConnectorApiIntegrationPayload::get_transformed_response_payload(input); Ok(serde_wasm_bindgen::to_value(&result)?) } #[cfg(feature = "payouts")] #[wasm_bindgen(js_name = getAllPayoutKeys)] pub fn get_all_payout_keys() -> JsResult { let keys: Vec<&'static str> = dir::PayoutDirKeyKind::VARIANTS.to_vec(); Ok(serde_wasm_bindgen::to_value(&keys)?) } #[cfg(feature = "payouts")] #[wasm_bindgen(js_name = getPayoutVariantValues)] pub fn get_payout_variant_values(key: &str) -> Result<JsValue, JsValue> { let key = dir::PayoutDirKeyKind::from_str(key).map_err(|_| "Invalid key received".to_string())?; let variants: &[&str] = match key { dir::PayoutDirKeyKind::BusinessCountry => dir_enums::BusinessCountry::VARIANTS, dir::PayoutDirKeyKind::BillingCountry => dir_enums::BillingCountry::VARIANTS, dir::PayoutDirKeyKind::PayoutCurrency => dir_enums::PaymentCurrency::VARIANTS, dir::PayoutDirKeyKind::PayoutType => dir_enums::PayoutType::VARIANTS, dir::PayoutDirKeyKind::WalletType => dir_enums::PayoutWalletType::VARIANTS, dir::PayoutDirKeyKind::BankTransferType => dir_enums::PayoutBankTransferType::VARIANTS, dir::PayoutDirKeyKind::PayoutAmount | dir::PayoutDirKeyKind::BusinessLabel => { Err("Key does not have variants".to_string())? } }; Ok(serde_wasm_bindgen::to_value(variants)?) } #[cfg(feature = "payouts")] #[wasm_bindgen(js_name = getPayoutDescriptionCategory)] pub fn get_payout_description_category() -> JsResult { let keys = dir::PayoutDirKeyKind::VARIANTS.to_vec(); let mut category: HashMap<Option<&str>, Vec<types::PayoutDetails<'_>>> = HashMap::new(); for key in keys { let dir_key = dir::PayoutDirKeyKind::from_str(key).map_err(|_| "Invalid key received".to_string())?; let details = types::PayoutDetails { description: dir_key.get_detailed_message(), kind: dir_key.clone(), }; category .entry(dir_key.get_str("Category")) .and_modify(|val| val.push(details.clone())) .or_insert(vec![details]); } Ok(serde_wasm_bindgen::to_value(&category)?) } #[wasm_bindgen(js_name = getValidWebhookStatus)] pub fn get_valid_webhook_status(key: &str) -> JsResult { let event_class = EventClass::from_str(key) .map_err(|_| "Invalid webhook event type received".to_string()) .err_to_js()?; match event_class { EventClass::Payments => { let statuses: Vec<IntentStatus> = IntentStatus::iter() .filter(|intent_status| Into::<Option<EventType>>::into(*intent_status).is_some()) .collect(); Ok(serde_wasm_bindgen::to_value(&statuses)?) } EventClass::Refunds => { let statuses: Vec<RefundStatus> = RefundStatus::iter() .filter(|status| Into::<Option<EventType>>::into(*status).is_some()) .collect(); Ok(serde_wasm_bindgen::to_value(&statuses)?) } EventClass::Disputes => { let statuses: Vec<DisputeStatus> = DisputeStatus::iter().collect(); Ok(serde_wasm_bindgen::to_value(&statuses)?) } EventClass::Mandates => { let statuses: Vec<MandateStatus> = MandateStatus::iter() .filter(|status| Into::<Option<EventType>>::into(*status).is_some()) .collect(); Ok(serde_wasm_bindgen::to_value(&statuses)?) } #[cfg(feature = "payouts")] EventClass::Payouts => { let statuses: Vec<PayoutStatus> = PayoutStatus::iter() .filter(|status| Into::<Option<EventType>>::into(*status).is_some()) .collect(); Ok(serde_wasm_bindgen::to_value(&statuses)?) } EventClass::Subscriptions => { let statuses: Vec<SubscriptionStatus> = SubscriptionStatus::iter() .filter(|status| Into::<Option<EventType>>::into(*status).is_some()) .collect(); Ok(serde_wasm_bindgen::to_value(&statuses)?) } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid_wasm/src/types.rs
crates/euclid_wasm/src/types.rs
use euclid::frontend::dir::DirKeyKind; #[cfg(feature = "payouts")] use euclid::frontend::dir::PayoutDirKeyKind; use serde::Serialize; #[derive(Serialize, Clone)] pub struct Details<'a> { pub description: Option<&'a str>, pub kind: DirKeyKind, } #[cfg(feature = "payouts")] #[derive(Serialize, Clone)] pub struct PayoutDetails<'a> { pub description: Option<&'a str>, pub kind: PayoutDirKeyKind, }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/euclid_wasm/src/utils.rs
crates/euclid_wasm/src/utils.rs
use wasm_bindgen::prelude::*; pub trait JsResultExt<T> { fn err_to_js(self) -> Result<T, JsValue>; } impl<T, E> JsResultExt<T> for Result<T, E> where E: serde::Serialize, { fn err_to_js(self) -> Result<T, JsValue> { match self { Ok(t) => Ok(t), Err(e) => Err(serde_wasm_bindgen::to_value(&e)?), } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/errors.rs
crates/analytics/src/errors.rs
use api_models::errors::types::{ApiError, ApiErrorResponse}; use common_utils::errors::{CustomResult, ErrorSwitch}; pub type AnalyticsResult<T> = CustomResult<T, AnalyticsError>; #[derive(Debug, Clone, serde::Serialize, thiserror::Error)] pub enum AnalyticsError { #[allow(dead_code)] #[error("Not implemented: {0}")] NotImplemented(&'static str), #[error("Unknown Analytics Error")] UnknownError, #[error("Access Forbidden Analytics Error")] AccessForbiddenError, #[error("Failed to fetch currency exchange rate")] ForexFetchFailed, } impl ErrorSwitch<ApiErrorResponse> for AnalyticsError { fn switch(&self) -> ApiErrorResponse { match self { Self::NotImplemented(feature) => ApiErrorResponse::NotImplemented(ApiError::new( "IR", 0, format!("{feature} is not implemented."), None, )), Self::UnknownError => ApiErrorResponse::InternalServerError(ApiError::new( "HE", 0, "Something went wrong", None, )), Self::AccessForbiddenError => { ApiErrorResponse::Unauthorized(ApiError::new("IR", 0, "Access Forbidden", None)) } Self::ForexFetchFailed => ApiErrorResponse::InternalServerError(ApiError::new( "HE", 0, "Failed to fetch currency exchange rate", None, )), } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/outgoing_webhook_event.rs
crates/analytics/src/outgoing_webhook_event.rs
mod core; pub mod events; pub trait OutgoingWebhookEventAnalytics: events::OutgoingWebhookLogsFilterAnalytics {} pub use self::core::outgoing_webhook_events_core;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/auth_events.rs
crates/analytics/src/auth_events.rs
pub mod accumulator; mod core; pub mod filters; pub mod metrics; pub mod sankey; pub mod types; pub use accumulator::{AuthEventMetricAccumulator, AuthEventMetricsAccumulator}; pub use self::core::{get_filters, get_metrics, get_sankey};
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/lib.rs
crates/analytics/src/lib.rs
pub mod active_payments; pub mod api_event; pub mod auth_events; mod clickhouse; pub mod connector_events; pub mod core; pub mod disputes; pub mod enums; pub mod errors; pub mod frm; pub mod health_check; pub mod metrics; pub mod opensearch; pub mod outgoing_webhook_event; pub mod payment_intents; pub mod payments; mod query; pub mod refunds; pub mod routing_events; pub mod sdk_events; pub mod search; mod sqlx; mod types; use api_event::metrics::{ApiEventMetric, ApiEventMetricRow}; use common_utils::{errors::CustomResult, types::TenantConfig}; use disputes::metrics::{DisputeMetric, DisputeMetricRow}; use enums::AuthInfo; use hyperswitch_interfaces::secrets_interface::{ secret_handler::SecretsHandler, secret_state::{RawSecret, SecretStateContainer, SecuredSecret}, SecretManagementInterface, SecretsManagementError, }; use refunds::distribution::{RefundDistribution, RefundDistributionRow}; pub use types::AnalyticsDomain; pub mod lambda_utils; pub mod utils; use std::{collections::HashSet, sync::Arc}; use api_models::analytics::{ active_payments::{ActivePaymentsMetrics, ActivePaymentsMetricsBucketIdentifier}, api_event::{ ApiEventDimensions, ApiEventFilters, ApiEventMetrics, ApiEventMetricsBucketIdentifier, }, auth_events::{ AuthEventDimensions, AuthEventFilters, AuthEventMetrics, AuthEventMetricsBucketIdentifier, }, disputes::{DisputeDimensions, DisputeFilters, DisputeMetrics, DisputeMetricsBucketIdentifier}, frm::{FrmDimensions, FrmFilters, FrmMetrics, FrmMetricsBucketIdentifier}, payment_intents::{ PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetrics, PaymentIntentMetricsBucketIdentifier, }, payments::{PaymentDimensions, PaymentFilters, PaymentMetrics, PaymentMetricsBucketIdentifier}, refunds::{RefundDimensions, RefundFilters, RefundMetrics, RefundMetricsBucketIdentifier}, sdk_events::{ SdkEventDimensions, SdkEventFilters, SdkEventMetrics, SdkEventMetricsBucketIdentifier, }, Granularity, PaymentDistributionBody, RefundDistributionBody, TimeRange, }; use clickhouse::ClickhouseClient; pub use clickhouse::ClickhouseConfig; use error_stack::report; use router_env::{ logger, tracing::{self, instrument}, types::FlowMetric, }; use storage_impl::config::Database; use strum::Display; use self::{ active_payments::metrics::{ActivePaymentsMetric, ActivePaymentsMetricRow}, auth_events::metrics::{AuthEventMetric, AuthEventMetricRow}, frm::metrics::{FrmMetric, FrmMetricRow}, payment_intents::metrics::{PaymentIntentMetric, PaymentIntentMetricRow}, payments::{ distribution::{PaymentDistribution, PaymentDistributionRow}, metrics::{PaymentMetric, PaymentMetricRow}, }, refunds::metrics::{RefundMetric, RefundMetricRow}, sdk_events::metrics::{SdkEventMetric, SdkEventMetricRow}, sqlx::SqlxClient, types::MetricsError, }; #[derive(Clone, Debug)] pub enum AnalyticsProvider { Sqlx(SqlxClient), Clickhouse(ClickhouseClient), CombinedCkh(SqlxClient, ClickhouseClient), CombinedSqlx(SqlxClient, ClickhouseClient), } impl Default for AnalyticsProvider { fn default() -> Self { Self::Sqlx(SqlxClient::default()) } } impl std::fmt::Display for AnalyticsProvider { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let analytics_provider = match self { Self::Clickhouse(_) => "Clickhouse", Self::Sqlx(_) => "Sqlx", Self::CombinedCkh(_, _) => "CombinedCkh", Self::CombinedSqlx(_, _) => "CombinedSqlx", }; write!(f, "{analytics_provider}") } } impl AnalyticsProvider { #[instrument(skip_all)] pub async fn get_payment_metrics( &self, metric: &PaymentMetrics, dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, granularity: Option<Granularity>, time_range: &TimeRange, ) -> types::MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { // Metrics to get the fetch time for each payment metric metrics::request::record_operation_time( async { match self { Self::Sqlx(pool) => { metric .load_metrics( dimensions, auth, filters, granularity, time_range, pool, ) .await } Self::Clickhouse(pool) => { metric .load_metrics( dimensions, auth, filters, granularity, time_range, pool, ) .await } Self::CombinedCkh(sqlx_pool, ckh_pool) => { let (ckh_result, sqlx_result) = tokio::join!(metric .load_metrics( dimensions, auth, filters, granularity, time_range, ckh_pool, ), metric .load_metrics( dimensions, auth, filters, granularity, time_range, sqlx_pool, )); match (&sqlx_result, &ckh_result) { (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payments analytics metrics") }, _ => {} }; ckh_result } Self::CombinedSqlx(sqlx_pool, ckh_pool) => { let (ckh_result, sqlx_result) = tokio::join!(metric .load_metrics( dimensions, auth, filters, granularity, time_range, ckh_pool, ), metric .load_metrics( dimensions, auth, filters, granularity, time_range, sqlx_pool, )); match (&sqlx_result, &ckh_result) { (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payments analytics metrics") }, _ => {} }; sqlx_result } } }, &metrics::METRIC_FETCH_TIME, metric, self, ) .await } pub async fn get_payment_distribution( &self, distribution: &PaymentDistributionBody, dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, granularity: Option<Granularity>, time_range: &TimeRange, ) -> types::MetricsResult<Vec<(PaymentMetricsBucketIdentifier, PaymentDistributionRow)>> { // Metrics to get the fetch time for each payment metric metrics::request::record_operation_time( async { match self { Self::Sqlx(pool) => { distribution.distribution_for .load_distribution( distribution, dimensions, auth, filters, granularity, time_range, pool, ) .await } Self::Clickhouse(pool) => { distribution.distribution_for .load_distribution( distribution, dimensions, auth, filters, granularity, time_range, pool, ) .await } Self::CombinedCkh(sqlx_pool, ckh_pool) => { let (ckh_result, sqlx_result) = tokio::join!(distribution.distribution_for .load_distribution( distribution, dimensions, auth, filters, granularity, time_range, ckh_pool, ), distribution.distribution_for .load_distribution( distribution, dimensions, auth, filters, granularity, time_range, sqlx_pool, )); match (&sqlx_result, &ckh_result) { (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payments analytics distribution") }, _ => {} }; ckh_result } Self::CombinedSqlx(sqlx_pool, ckh_pool) => { let (ckh_result, sqlx_result) = tokio::join!(distribution.distribution_for .load_distribution( distribution, dimensions, auth, filters, granularity, time_range, ckh_pool, ), distribution.distribution_for .load_distribution( distribution, dimensions, auth, filters, granularity, time_range, sqlx_pool, )); match (&sqlx_result, &ckh_result) { (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payments analytics distribution") }, _ => {} }; sqlx_result } } }, &metrics::METRIC_FETCH_TIME, &distribution.distribution_for, self, ) .await } pub async fn get_payment_intent_metrics( &self, metric: &PaymentIntentMetrics, dimensions: &[PaymentIntentDimensions], auth: &AuthInfo, filters: &PaymentIntentFilters, granularity: Option<Granularity>, time_range: &TimeRange, ) -> types::MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> { // Metrics to get the fetch time for each payment intent metric metrics::request::record_operation_time( async { match self { Self::Sqlx(pool) => { metric .load_metrics( dimensions, auth, filters, granularity, time_range, pool, ) .await } Self::Clickhouse(pool) => { metric .load_metrics( dimensions, auth, filters, granularity, time_range, pool, ) .await } Self::CombinedCkh(sqlx_pool, ckh_pool) => { let (ckh_result, sqlx_result) = tokio::join!(metric .load_metrics( dimensions, auth, filters, granularity, time_range, ckh_pool, ), metric .load_metrics( dimensions, auth, filters, granularity, time_range, sqlx_pool, )); match (&sqlx_result, &ckh_result) { (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payment intents analytics metrics") }, _ => {} }; ckh_result } Self::CombinedSqlx(sqlx_pool, ckh_pool) => { let (ckh_result, sqlx_result) = tokio::join!(metric .load_metrics( dimensions, auth, filters, granularity, time_range, ckh_pool, ), metric .load_metrics( dimensions, auth, filters, granularity, time_range, sqlx_pool, )); match (&sqlx_result, &ckh_result) { (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payment intents analytics metrics") }, _ => {} }; sqlx_result } } }, &metrics::METRIC_FETCH_TIME, metric, self, ) .await } pub async fn get_refund_metrics( &self, metric: &RefundMetrics, dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, granularity: Option<Granularity>, time_range: &TimeRange, ) -> types::MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> { // Metrics to get the fetch time for each refund metric metrics::request::record_operation_time( async { match self { Self::Sqlx(pool) => { metric .load_metrics( dimensions, auth, filters, granularity, time_range, pool, ) .await } Self::Clickhouse(pool) => { metric .load_metrics( dimensions, auth, filters, granularity, time_range, pool, ) .await } Self::CombinedCkh(sqlx_pool, ckh_pool) => { let (ckh_result, sqlx_result) = tokio::join!( metric.load_metrics( dimensions, auth, filters, granularity, time_range, ckh_pool, ), metric.load_metrics( dimensions, auth, filters, granularity, time_range, sqlx_pool, ) ); match (&sqlx_result, &ckh_result) { (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres refunds analytics metrics") } _ => {} }; ckh_result } Self::CombinedSqlx(sqlx_pool, ckh_pool) => { let (ckh_result, sqlx_result) = tokio::join!( metric.load_metrics( dimensions, auth, filters, granularity, time_range, ckh_pool, ), metric.load_metrics( dimensions, auth, filters, granularity, time_range, sqlx_pool, ) ); match (&sqlx_result, &ckh_result) { (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres refunds analytics metrics") } _ => {} }; sqlx_result } } }, &metrics::METRIC_FETCH_TIME, metric, self, ) .await } pub async fn get_refund_distribution( &self, distribution: &RefundDistributionBody, dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, granularity: &Option<Granularity>, time_range: &TimeRange, ) -> types::MetricsResult<Vec<(RefundMetricsBucketIdentifier, RefundDistributionRow)>> { // Metrics to get the fetch time for each payment metric metrics::request::record_operation_time( async { match self { Self::Sqlx(pool) => { distribution.distribution_for .load_distribution( distribution, dimensions, auth, filters, granularity, time_range, pool, ) .await } Self::Clickhouse(pool) => { distribution.distribution_for .load_distribution( distribution, dimensions, auth, filters, granularity, time_range, pool, ) .await } Self::CombinedCkh(sqlx_pool, ckh_pool) => { let (ckh_result, sqlx_result) = tokio::join!(distribution.distribution_for .load_distribution( distribution, dimensions, auth, filters, granularity, time_range, ckh_pool, ), distribution.distribution_for .load_distribution( distribution, dimensions, auth, filters, granularity, time_range, sqlx_pool, )); match (&sqlx_result, &ckh_result) { (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payments analytics distribution") }, _ => {} }; ckh_result } Self::CombinedSqlx(sqlx_pool, ckh_pool) => { let (ckh_result, sqlx_result) = tokio::join!(distribution.distribution_for .load_distribution( distribution, dimensions, auth, filters, granularity, time_range, ckh_pool, ), distribution.distribution_for .load_distribution( distribution, dimensions, auth, filters, granularity, time_range, sqlx_pool, )); match (&sqlx_result, &ckh_result) { (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payments analytics distribution") }, _ => {} }; sqlx_result } } }, &metrics::METRIC_FETCH_TIME, &distribution.distribution_for, self, ) .await } pub async fn get_frm_metrics( &self, metric: &FrmMetrics, dimensions: &[FrmDimensions], merchant_id: &common_utils::id_type::MerchantId, filters: &FrmFilters, granularity: Option<Granularity>, time_range: &TimeRange, ) -> types::MetricsResult<Vec<(FrmMetricsBucketIdentifier, FrmMetricRow)>> { // Metrics to get the fetch time for each refund metric metrics::request::record_operation_time( async { match self { Self::Sqlx(pool) => { metric .load_metrics( dimensions, merchant_id, filters, granularity, time_range, pool, ) .await } Self::Clickhouse(pool) => { metric .load_metrics( dimensions, merchant_id, filters, granularity, time_range, pool, ) .await } Self::CombinedCkh(sqlx_pool, ckh_pool) => { let (ckh_result, sqlx_result) = tokio::join!( metric.load_metrics( dimensions, merchant_id, filters, granularity, time_range, ckh_pool, ), metric.load_metrics( dimensions, merchant_id, filters, granularity, time_range, sqlx_pool, ) ); match (&sqlx_result, &ckh_result) { (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres frm analytics metrics") } _ => {} }; ckh_result } Self::CombinedSqlx(sqlx_pool, ckh_pool) => { let (ckh_result, sqlx_result) = tokio::join!( metric.load_metrics( dimensions, merchant_id, filters, granularity, time_range, ckh_pool, ), metric.load_metrics( dimensions, merchant_id, filters, granularity, time_range, sqlx_pool, ) ); match (&sqlx_result, &ckh_result) { (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => { logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres frm analytics metrics") } _ => {} }; sqlx_result } } }, &metrics::METRIC_FETCH_TIME, metric, self, ) .await } pub async fn get_dispute_metrics( &self, metric: &DisputeMetrics, dimensions: &[DisputeDimensions], auth: &AuthInfo, filters: &DisputeFilters, granularity: Option<Granularity>, time_range: &TimeRange, ) -> types::MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>> { // Metrics to get the fetch time for each refund metric metrics::request::record_operation_time( async { match self { Self::Sqlx(pool) => { metric .load_metrics( dimensions, auth, filters, granularity, time_range, pool, ) .await } Self::Clickhouse(pool) => { metric
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
true
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/lambda_utils.rs
crates/analytics/src/lambda_utils.rs
use aws_config::{self, meta::region::RegionProviderChain, Region}; use aws_sdk_lambda::{types::InvocationType::Event, Client}; use aws_smithy_types::Blob; use common_utils::errors::CustomResult; use error_stack::{report, ResultExt}; use crate::errors::AnalyticsError; async fn get_aws_client(region: String) -> Client { let region_provider = RegionProviderChain::first_try(Region::new(region)); let sdk_config = aws_config::from_env().region(region_provider).load().await; Client::new(&sdk_config) } pub async fn invoke_lambda( function_name: &str, region: &str, json_bytes: &[u8], ) -> CustomResult<(), AnalyticsError> { get_aws_client(region.to_string()) .await .invoke() .function_name(function_name) .invocation_type(Event) .payload(Blob::new(json_bytes.to_owned())) .send() .await .map_err(|er| { let er_rep = format!("{er:?}"); report!(er).attach_printable(er_rep) }) .change_context(AnalyticsError::UnknownError) .attach_printable("Lambda invocation failed")?; Ok(()) }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/refunds.rs
crates/analytics/src/refunds.rs
pub mod accumulator; mod core; pub mod distribution; pub mod filters; pub mod metrics; pub mod types; pub use accumulator::{RefundMetricAccumulator, RefundMetricsAccumulator}; pub use self::core::{get_filters, get_metrics};
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/routing_events.rs
crates/analytics/src/routing_events.rs
mod core; pub mod events; pub trait RoutingEventAnalytics: events::RoutingEventLogAnalytics {} pub use self::core::routing_events_core;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/sdk_events.rs
crates/analytics/src/sdk_events.rs
pub mod accumulator; mod core; pub mod events; pub mod filters; pub mod metrics; pub mod types; pub use accumulator::{SdkEventMetricAccumulator, SdkEventMetricsAccumulator}; pub use self::core::{get_filters, get_metrics, sdk_events_core};
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/active_payments.rs
crates/analytics/src/active_payments.rs
pub mod accumulator; mod core; pub mod metrics; pub use accumulator::{ActivePaymentsMetricAccumulator, ActivePaymentsMetricsAccumulator}; pub use self::core::get_metrics;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/disputes.rs
crates/analytics/src/disputes.rs
pub mod accumulators; mod core; pub mod filters; pub mod metrics; pub mod types; pub use accumulators::{DisputeMetricAccumulator, DisputeMetricsAccumulator}; pub trait DisputeAnalytics: metrics::DisputeMetricAnalytics {} pub use self::core::{get_filters, get_metrics};
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/connector_events.rs
crates/analytics/src/connector_events.rs
mod core; pub mod events; pub trait ConnectorEventAnalytics: events::ConnectorEventLogAnalytics {} pub use self::core::connector_events_core;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/core.rs
crates/analytics/src/core.rs
use api_models::analytics::GetInfoResponse; use crate::{types::AnalyticsDomain, utils}; pub async fn get_domain_info( domain: AnalyticsDomain, ) -> crate::errors::AnalyticsResult<GetInfoResponse> { let info = match domain { AnalyticsDomain::Payments => GetInfoResponse { metrics: utils::get_payment_metrics_info(), download_dimensions: None, dimensions: utils::get_payment_dimensions(), }, AnalyticsDomain::PaymentIntents => GetInfoResponse { metrics: utils::get_payment_intent_metrics_info(), download_dimensions: None, dimensions: utils::get_payment_intent_dimensions(), }, AnalyticsDomain::Refunds => GetInfoResponse { metrics: utils::get_refund_metrics_info(), download_dimensions: None, dimensions: utils::get_refund_dimensions(), }, AnalyticsDomain::Frm => GetInfoResponse { metrics: utils::get_frm_metrics_info(), download_dimensions: None, dimensions: utils::get_frm_dimensions(), }, AnalyticsDomain::SdkEvents => GetInfoResponse { metrics: utils::get_sdk_event_metrics_info(), download_dimensions: None, dimensions: utils::get_sdk_event_dimensions(), }, AnalyticsDomain::AuthEvents => GetInfoResponse { metrics: utils::get_auth_event_metrics_info(), download_dimensions: None, dimensions: utils::get_auth_event_dimensions(), }, AnalyticsDomain::ApiEvents => GetInfoResponse { metrics: utils::get_api_event_metrics_info(), download_dimensions: None, dimensions: utils::get_api_event_dimensions(), }, AnalyticsDomain::Dispute => GetInfoResponse { metrics: utils::get_dispute_metrics_info(), download_dimensions: None, dimensions: utils::get_dispute_dimensions(), }, AnalyticsDomain::Routing => GetInfoResponse { metrics: utils::get_payment_metrics_info(), download_dimensions: None, dimensions: utils::get_payment_dimensions(), }, }; Ok(info) }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/opensearch.rs
crates/analytics/src/opensearch.rs
use std::collections::HashSet; use api_models::{ analytics::search::SearchIndex, errors::types::{ApiError, ApiErrorResponse}, }; use aws_config::{self, meta::region::RegionProviderChain, Region}; use common_utils::{ errors::{CustomResult, ErrorSwitch}, types::TimeRange, }; use error_stack::ResultExt; use opensearch::{ auth::Credentials, cert::CertificateValidation, cluster::{Cluster, ClusterHealthParts}, http::{ request::JsonBody, response::Response, transport::{SingleNodeConnectionPool, Transport, TransportBuilder}, Url, }, MsearchParts, OpenSearch, SearchParts, }; use serde_json::{json, Map, Value}; use storage_impl::errors::{ApplicationError, StorageError, StorageResult}; use time::PrimitiveDateTime; use super::{health_check::HealthCheck, query::QueryResult, types::QueryExecutionError}; use crate::{enums::AuthInfo, query::QueryBuildingError}; #[derive(Clone, Debug, serde::Deserialize)] #[serde(tag = "auth")] #[serde(rename_all = "lowercase")] pub enum OpenSearchAuth { Basic { username: String, password: String }, Aws { region: String }, } #[derive(Clone, Debug, serde::Deserialize)] pub struct OpenSearchIndexes { pub payment_attempts: String, pub payment_intents: String, pub refunds: String, pub disputes: String, pub payouts: String, pub sessionizer_payment_attempts: String, pub sessionizer_payment_intents: String, pub sessionizer_refunds: String, pub sessionizer_disputes: String, } #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash)] pub struct OpensearchTimeRange { #[serde(with = "common_utils::custom_serde::iso8601")] pub gte: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub lte: Option<PrimitiveDateTime>, } impl From<TimeRange> for OpensearchTimeRange { fn from(time_range: TimeRange) -> Self { Self { gte: time_range.start_time, lte: time_range.end_time, } } } #[derive(Clone, Debug, serde::Deserialize)] pub struct OpenSearchConfig { host: String, auth: OpenSearchAuth, indexes: OpenSearchIndexes, #[serde(default)] enabled: bool, } impl Default for OpenSearchConfig { fn default() -> Self { Self { host: "https://localhost:9200".to_string(), auth: OpenSearchAuth::Basic { username: "admin".to_string(), password: "admin".to_string(), }, indexes: OpenSearchIndexes { payment_attempts: "hyperswitch-payment-attempt-events".to_string(), payment_intents: "hyperswitch-payment-intent-events".to_string(), refunds: "hyperswitch-refund-events".to_string(), disputes: "hyperswitch-dispute-events".to_string(), payouts: "hyperswitch-payout-events".to_string(), sessionizer_payment_attempts: "sessionizer-payment-attempt-events".to_string(), sessionizer_payment_intents: "sessionizer-payment-intent-events".to_string(), sessionizer_refunds: "sessionizer-refund-events".to_string(), sessionizer_disputes: "sessionizer-dispute-events".to_string(), }, enabled: false, } } } #[derive(Debug, thiserror::Error)] pub enum OpenSearchError { #[error("Opensearch is not enabled")] NotEnabled, #[error("Opensearch connection error")] ConnectionError, #[error("Opensearch NON-200 response content: '{0}'")] ResponseNotOK(String), #[error("Opensearch bad request error")] BadRequestError(String), #[error("Opensearch response error")] ResponseError, #[error("Opensearch query building error")] QueryBuildingError, #[error("Opensearch deserialisation error")] DeserialisationError, #[error("Opensearch index access not present error: {0:?}")] IndexAccessNotPermittedError(SearchIndex), #[error("Opensearch unknown error")] UnknownError, #[error("Opensearch access forbidden error")] AccessForbiddenError, } impl ErrorSwitch<OpenSearchError> for QueryBuildingError { fn switch(&self) -> OpenSearchError { OpenSearchError::QueryBuildingError } } impl ErrorSwitch<ApiErrorResponse> for OpenSearchError { fn switch(&self) -> ApiErrorResponse { match self { Self::ConnectionError => ApiErrorResponse::InternalServerError(ApiError::new( "IR", 0, "Connection error", None, )), Self::BadRequestError(response) => { ApiErrorResponse::BadRequest(ApiError::new("IR", 1, response.to_string(), None)) } Self::ResponseNotOK(response) => ApiErrorResponse::InternalServerError(ApiError::new( "IR", 1, format!("Something went wrong {response}"), None, )), Self::ResponseError => ApiErrorResponse::InternalServerError(ApiError::new( "IR", 2, "Something went wrong", None, )), Self::QueryBuildingError => ApiErrorResponse::InternalServerError(ApiError::new( "IR", 3, "Query building error", None, )), Self::DeserialisationError => ApiErrorResponse::InternalServerError(ApiError::new( "IR", 4, "Deserialisation error", None, )), Self::IndexAccessNotPermittedError(index) => { ApiErrorResponse::ForbiddenCommonResource(ApiError::new( "IR", 5, format!("Index access not permitted: {index:?}"), None, )) } Self::UnknownError => { ApiErrorResponse::InternalServerError(ApiError::new("IR", 6, "Unknown error", None)) } Self::AccessForbiddenError => ApiErrorResponse::ForbiddenCommonResource(ApiError::new( "IR", 7, "Access Forbidden error", None, )), Self::NotEnabled => ApiErrorResponse::InternalServerError(ApiError::new( "IR", 8, "Opensearch is not enabled", None, )), } } } #[derive(Clone, Debug)] pub struct OpenSearchClient { pub client: OpenSearch, pub transport: Transport, pub indexes: OpenSearchIndexes, } impl OpenSearchClient { pub async fn create(conf: &OpenSearchConfig) -> CustomResult<Self, OpenSearchError> { let url = Url::parse(&conf.host).map_err(|_| OpenSearchError::ConnectionError)?; let transport = match &conf.auth { OpenSearchAuth::Basic { username, password } => { let credentials = Credentials::Basic(username.clone(), password.clone()); TransportBuilder::new(SingleNodeConnectionPool::new(url)) .cert_validation(CertificateValidation::None) .auth(credentials) .build() .map_err(|_| OpenSearchError::ConnectionError)? } OpenSearchAuth::Aws { region } => { let region_provider = RegionProviderChain::first_try(Region::new(region.clone())); let sdk_config = aws_config::from_env().region(region_provider).load().await; let conn_pool = SingleNodeConnectionPool::new(url); TransportBuilder::new(conn_pool) .auth( sdk_config .clone() .try_into() .map_err(|_| OpenSearchError::ConnectionError)?, ) .service_name("es") .build() .map_err(|_| OpenSearchError::ConnectionError)? } }; Ok(Self { transport: transport.clone(), client: OpenSearch::new(transport), indexes: conf.indexes.clone(), }) } pub fn search_index_to_opensearch_index(&self, index: SearchIndex) -> String { match index { SearchIndex::PaymentAttempts => self.indexes.payment_attempts.clone(), SearchIndex::PaymentIntents => self.indexes.payment_intents.clone(), SearchIndex::Refunds => self.indexes.refunds.clone(), SearchIndex::Disputes => self.indexes.disputes.clone(), SearchIndex::Payouts => self.indexes.payouts.clone(), SearchIndex::SessionizerPaymentAttempts => { self.indexes.sessionizer_payment_attempts.clone() } SearchIndex::SessionizerPaymentIntents => { self.indexes.sessionizer_payment_intents.clone() } SearchIndex::SessionizerRefunds => self.indexes.sessionizer_refunds.clone(), SearchIndex::SessionizerDisputes => self.indexes.sessionizer_disputes.clone(), } } pub async fn execute( &self, query_builder: OpenSearchQueryBuilder, ) -> CustomResult<Response, OpenSearchError> { match query_builder.query_type { OpenSearchQuery::Msearch(ref indexes) => { let payload = query_builder .construct_payload(indexes) .change_context(OpenSearchError::QueryBuildingError)?; let payload_with_indexes = payload.into_iter().zip(indexes).fold( Vec::new(), |mut payload_with_indexes, (index_hit, index)| { payload_with_indexes.push( json!({"index": self.search_index_to_opensearch_index(*index)}).into(), ); payload_with_indexes.push(JsonBody::new(index_hit.clone())); payload_with_indexes }, ); self.client .msearch(MsearchParts::None) .body(payload_with_indexes) .send() .await .change_context(OpenSearchError::ResponseError) } OpenSearchQuery::Search(index) => { let payload = query_builder .clone() .construct_payload(&[index]) .change_context(OpenSearchError::QueryBuildingError)?; let final_payload = payload.first().unwrap_or(&Value::Null); self.client .search(SearchParts::Index(&[ &self.search_index_to_opensearch_index(index) ])) .from(query_builder.offset.unwrap_or(0)) .size(query_builder.count.unwrap_or(10)) .body(final_payload) .send() .await .change_context(OpenSearchError::ResponseError) } } } } #[async_trait::async_trait] impl HealthCheck for OpenSearchClient { async fn deep_health_check(&self) -> CustomResult<(), QueryExecutionError> { let health = Cluster::new(&self.transport) .health(ClusterHealthParts::None) .send() .await .change_context(QueryExecutionError::DatabaseError)? .json::<OpenSearchHealth>() .await .change_context(QueryExecutionError::DatabaseError)?; if health.status != OpenSearchHealthStatus::Red { Ok(()) } else { Err::<(), error_stack::Report<QueryExecutionError>>( QueryExecutionError::DatabaseError.into(), ) .attach_printable_lazy(|| format!("Opensearch cluster health is red: {health:?}")) } } } impl OpenSearchIndexes { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::{ext_traits::ConfigExt, fp_utils::when}; when(self.payment_attempts.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Opensearch Payment Attempts index must not be empty".into(), )) })?; when(self.payment_intents.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Opensearch Payment Intents index must not be empty".into(), )) })?; when(self.refunds.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Opensearch Refunds index must not be empty".into(), )) })?; when(self.disputes.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Opensearch Disputes index must not be empty".into(), )) })?; when(self.payouts.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Opensearch Payouts index must not be empty".into(), )) })?; when( self.sessionizer_payment_attempts.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Opensearch Sessionizer Payment Attempts index must not be empty".into(), )) }, )?; when( self.sessionizer_payment_intents.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Opensearch Sessionizer Payment Intents index must not be empty".into(), )) }, )?; when(self.sessionizer_refunds.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Opensearch Sessionizer Refunds index must not be empty".into(), )) })?; when(self.sessionizer_disputes.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Opensearch Sessionizer Disputes index must not be empty".into(), )) })?; Ok(()) } } impl OpenSearchAuth { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::{ext_traits::ConfigExt, fp_utils::when}; match self { Self::Basic { username, password } => { when(username.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Opensearch Basic auth username must not be empty".into(), )) })?; when(password.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Opensearch Basic auth password must not be empty".into(), )) })?; } Self::Aws { region } => { when(region.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Opensearch Aws auth region must not be empty".into(), )) })?; } }; Ok(()) } } impl OpenSearchConfig { pub async fn get_opensearch_client(&self) -> StorageResult<Option<OpenSearchClient>> { if !self.enabled { return Ok(None); } Ok(Some( OpenSearchClient::create(self) .await .change_context(StorageError::InitializationError)?, )) } pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::{ext_traits::ConfigExt, fp_utils::when}; if !self.enabled { return Ok(()); } when(self.host.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Opensearch host must not be empty".into(), )) })?; self.indexes.validate()?; self.auth.validate()?; Ok(()) } } #[derive(Debug, serde::Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum OpenSearchHealthStatus { Red, Green, Yellow, } #[derive(Debug, serde::Deserialize)] pub struct OpenSearchHealth { pub status: OpenSearchHealthStatus, } #[derive(Debug, Clone)] pub enum OpenSearchQuery { Msearch(Vec<SearchIndex>), Search(SearchIndex), } #[derive(Debug, Clone)] pub struct OpenSearchQueryBuilder { pub query_type: OpenSearchQuery, pub query: String, pub offset: Option<i64>, pub count: Option<i64>, pub filters: Vec<(String, Vec<Value>)>, pub time_range: Option<OpensearchTimeRange>, search_params: Vec<AuthInfo>, case_sensitive_fields: HashSet<&'static str>, } impl OpenSearchQueryBuilder { pub fn new(query_type: OpenSearchQuery, query: String, search_params: Vec<AuthInfo>) -> Self { Self { query_type, query, search_params, offset: Default::default(), count: Default::default(), filters: Default::default(), time_range: Default::default(), case_sensitive_fields: HashSet::from([ "customer_email.keyword", "search_tags.keyword", "card_last_4.keyword", "payment_id.keyword", "amount", "customer_id.keyword", ]), } } pub fn set_offset_n_count(&mut self, offset: i64, count: i64) -> QueryResult<()> { self.offset = Some(offset); self.count = Some(count); Ok(()) } pub fn set_time_range(&mut self, time_range: OpensearchTimeRange) -> QueryResult<()> { self.time_range = Some(time_range); Ok(()) } pub fn add_filter_clause(&mut self, lhs: String, rhs: Vec<Value>) -> QueryResult<()> { self.filters.push((lhs, rhs)); Ok(()) } pub fn get_status_field(&self, index: SearchIndex) -> &str { match index { SearchIndex::Refunds | SearchIndex::SessionizerRefunds => "refund_status.keyword", SearchIndex::Disputes | SearchIndex::SessionizerDisputes => "dispute_status.keyword", _ => "status.keyword", } } pub fn get_amount_field(&self, index: SearchIndex) -> &str { match index { SearchIndex::Refunds | SearchIndex::SessionizerRefunds => "refund_amount", SearchIndex::Disputes | SearchIndex::SessionizerDisputes => "dispute_amount", _ => "amount", } } pub fn build_filter_array( &self, case_sensitive_filters: Vec<&(String, Vec<Value>)>, index: SearchIndex, ) -> Vec<Value> { let mut filter_array = Vec::new(); if !self.query.is_empty() { filter_array.push(json!({ "multi_match": { "type": "phrase", "query": self.query, "lenient": true } })); } let case_sensitive_json_filters = case_sensitive_filters .into_iter() .map(|(k, v)| { let key = if *k == "amount" { self.get_amount_field(index).to_string() } else { k.clone() }; json!({"terms": {key: v}}) }) .collect::<Vec<Value>>(); filter_array.extend(case_sensitive_json_filters); if let Some(ref time_range) = self.time_range { let range = json!(time_range); filter_array.push(json!({ "range": { "@timestamp": range } })); } filter_array } pub fn build_case_insensitive_filters( &self, mut payload: Value, case_insensitive_filters: &[&(String, Vec<Value>)], auth_array: Vec<Value>, index: SearchIndex, ) -> Value { let mut must_array = case_insensitive_filters .iter() .map(|(k, v)| { let key = if *k == "status.keyword" { self.get_status_field(index).to_string() } else { k.clone() }; json!({ "bool": { "must": [ { "bool": { "should": v.iter().map(|value| { json!({ "term": { format!("{}", key): { "value": value, "case_insensitive": true } } }) }).collect::<Vec<Value>>(), "minimum_should_match": 1 } } ] } }) }) .collect::<Vec<Value>>(); must_array.push(json!({ "bool": { "must": [ { "bool": { "should": auth_array, "minimum_should_match": 1 } } ] }})); if let Some(query) = payload.get_mut("query") { if let Some(bool_obj) = query.get_mut("bool") { if let Some(bool_map) = bool_obj.as_object_mut() { bool_map.insert("must".to_string(), Value::Array(must_array)); } } } payload } pub fn build_auth_array(&self) -> Vec<Value> { self.search_params .iter() .map(|user_level| match user_level { AuthInfo::OrgLevel { org_id } => { let must_clauses = vec![json!({ "term": { "organization_id.keyword": { "value": org_id } } })]; json!({ "bool": { "must": must_clauses } }) } AuthInfo::MerchantLevel { org_id, merchant_ids, } => { let must_clauses = vec![ json!({ "term": { "organization_id.keyword": { "value": org_id } } }), json!({ "terms": { "merchant_id.keyword": merchant_ids } }), ]; json!({ "bool": { "must": must_clauses } }) } AuthInfo::ProfileLevel { org_id, merchant_id, profile_ids, } => { let must_clauses = vec![ json!({ "term": { "organization_id.keyword": { "value": org_id } } }), json!({ "term": { "merchant_id.keyword": { "value": merchant_id } } }), json!({ "terms": { "profile_id.keyword": profile_ids } }), ]; json!({ "bool": { "must": must_clauses } }) } }) .collect::<Vec<Value>>() } /// # Panics /// /// This function will panic if: /// /// * The structure of the JSON query is not as expected (e.g., missing keys or incorrect types). /// /// Ensure that the input data and the structure of the query are valid and correctly handled. pub fn construct_payload(&self, indexes: &[SearchIndex]) -> QueryResult<Vec<Value>> { let mut query_obj = Map::new(); let bool_obj = Map::new(); let (case_sensitive_filters, case_insensitive_filters): (Vec<_>, Vec<_>) = self .filters .iter() .partition(|(k, _)| self.case_sensitive_fields.contains(k.as_str())); let should_array = self.build_auth_array(); query_obj.insert("bool".to_string(), Value::Object(bool_obj.clone())); let mut sort_obj = Map::new(); sort_obj.insert( "@timestamp".to_string(), json!({ "order": "desc" }), ); Ok(indexes .iter() .map(|index| { let mut payload = json!({ "query": query_obj.clone(), "sort": [ Value::Object(sort_obj.clone()) ] }); let filter_array = self.build_filter_array(case_sensitive_filters.clone(), *index); if !filter_array.is_empty() { payload .get_mut("query") .and_then(|query| query.get_mut("bool")) .and_then(|bool_obj| bool_obj.as_object_mut()) .map(|bool_map| { bool_map.insert("filter".to_string(), Value::Array(filter_array)); }); } payload = self.build_case_insensitive_filters( payload, &case_insensitive_filters, should_array.clone(), *index, ); payload }) .collect::<Vec<Value>>()) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/search.rs
crates/analytics/src/search.rs
use api_models::analytics::search::{ GetGlobalSearchRequest, GetSearchRequestWithIndex, GetSearchResponse, OpenMsearchOutput, OpensearchOutput, SearchIndex, SearchStatus, }; use common_utils::errors::{CustomResult, ReportSwitchExt}; use error_stack::ResultExt; use router_env::tracing; use serde_json::Value; use crate::{ enums::AuthInfo, opensearch::{OpenSearchClient, OpenSearchError, OpenSearchQuery, OpenSearchQueryBuilder}, }; pub fn convert_to_value<T: Into<Value>>(items: Vec<T>) -> Vec<Value> { items.into_iter().map(|item| item.into()).collect() } pub async fn msearch_results( client: &OpenSearchClient, req: GetGlobalSearchRequest, search_params: Vec<AuthInfo>, indexes: Vec<SearchIndex>, ) -> CustomResult<Vec<GetSearchResponse>, OpenSearchError> { if req.query.trim().is_empty() && req .filters .as_ref() .is_none_or(|filters| filters.is_all_none()) { return Err(OpenSearchError::BadRequestError( "Both query and filters are empty".to_string(), ) .into()); } let mut query_builder = OpenSearchQueryBuilder::new( OpenSearchQuery::Msearch(indexes.clone()), req.query, search_params, ); if let Some(filters) = req.filters { if let Some(currency) = filters.currency { if !currency.is_empty() { query_builder .add_filter_clause("currency.keyword".to_string(), convert_to_value(currency)) .switch()?; } }; if let Some(status) = filters.status { if !status.is_empty() { query_builder .add_filter_clause("status.keyword".to_string(), convert_to_value(status)) .switch()?; } }; if let Some(payment_method) = filters.payment_method { if !payment_method.is_empty() { query_builder .add_filter_clause( "payment_method.keyword".to_string(), convert_to_value(payment_method), ) .switch()?; } }; if let Some(customer_email) = filters.customer_email { if !customer_email.is_empty() { query_builder .add_filter_clause( "customer_email.keyword".to_string(), convert_to_value( customer_email .iter() .filter_map(|email| { // TODO: Add trait based inputs instead of converting this to strings serde_json::to_value(email) .ok() .and_then(|a| a.as_str().map(|a| a.to_string())) }) .collect(), ), ) .switch()?; } }; if let Some(search_tags) = filters.search_tags { if !search_tags.is_empty() { query_builder .add_filter_clause( "feature_metadata.search_tags.keyword".to_string(), convert_to_value( search_tags .iter() .filter_map(|search_tag| { // TODO: Add trait based inputs instead of converting this to strings serde_json::to_value(search_tag) .ok() .and_then(|a| a.as_str().map(|a| a.to_string())) }) .collect(), ), ) .switch()?; } }; if let Some(connector) = filters.connector { if !connector.is_empty() { query_builder .add_filter_clause("connector.keyword".to_string(), convert_to_value(connector)) .switch()?; } }; if let Some(payment_method_type) = filters.payment_method_type { if !payment_method_type.is_empty() { query_builder .add_filter_clause( "payment_method_type.keyword".to_string(), convert_to_value(payment_method_type), ) .switch()?; } }; if let Some(card_network) = filters.card_network { if !card_network.is_empty() { query_builder .add_filter_clause( "card_network.keyword".to_string(), convert_to_value(card_network), ) .switch()?; } }; if let Some(card_last_4) = filters.card_last_4 { if !card_last_4.is_empty() { query_builder .add_filter_clause( "card_last_4.keyword".to_string(), convert_to_value(card_last_4), ) .switch()?; } }; if let Some(payment_id) = filters.payment_id { if !payment_id.is_empty() { query_builder .add_filter_clause( "payment_id.keyword".to_string(), convert_to_value(payment_id), ) .switch()?; } }; if let Some(amount) = filters.amount { if !amount.is_empty() { query_builder .add_filter_clause("amount".to_string(), convert_to_value(amount)) .switch()?; } }; if let Some(customer_id) = filters.customer_id { if !customer_id.is_empty() { query_builder .add_filter_clause( "customer_id.keyword".to_string(), convert_to_value(customer_id), ) .switch()?; } }; }; if let Some(time_range) = req.time_range { query_builder.set_time_range(time_range.into()).switch()?; }; let response_text: OpenMsearchOutput = client .execute(query_builder) .await .change_context(OpenSearchError::ConnectionError)? .text() .await .change_context(OpenSearchError::ResponseError) .and_then(|body: String| { serde_json::from_str::<OpenMsearchOutput>(&body) .change_context(OpenSearchError::DeserialisationError) .attach_printable(body.clone()) })?; let response_body: OpenMsearchOutput = response_text; Ok(response_body .responses .into_iter() .zip(indexes) .map(|(index_hit, index)| match index_hit { OpensearchOutput::Success(success) => GetSearchResponse { count: success.hits.total.value, index, hits: success .hits .hits .into_iter() .map(|hit| hit.source) .collect(), status: SearchStatus::Success, }, OpensearchOutput::Error(error) => { tracing::error!( index = ?index, error_response = ?error, "Search error" ); GetSearchResponse { count: 0, index, hits: Vec::new(), status: SearchStatus::Failure, } } }) .collect()) } pub async fn search_results( client: &OpenSearchClient, req: GetSearchRequestWithIndex, search_params: Vec<AuthInfo>, ) -> CustomResult<GetSearchResponse, OpenSearchError> { let search_req = req.search_req; if search_req.query.trim().is_empty() && search_req .filters .as_ref() .is_none_or(|filters| filters.is_all_none()) { return Err(OpenSearchError::BadRequestError( "Both query and filters are empty".to_string(), ) .into()); } let mut query_builder = OpenSearchQueryBuilder::new( OpenSearchQuery::Search(req.index), search_req.query, search_params, ); if let Some(filters) = search_req.filters { if let Some(currency) = filters.currency { if !currency.is_empty() { query_builder .add_filter_clause("currency.keyword".to_string(), convert_to_value(currency)) .switch()?; } }; if let Some(status) = filters.status { if !status.is_empty() { query_builder .add_filter_clause("status.keyword".to_string(), convert_to_value(status)) .switch()?; } }; if let Some(payment_method) = filters.payment_method { if !payment_method.is_empty() { query_builder .add_filter_clause( "payment_method.keyword".to_string(), convert_to_value(payment_method), ) .switch()?; } }; if let Some(customer_email) = filters.customer_email { if !customer_email.is_empty() { query_builder .add_filter_clause( "customer_email.keyword".to_string(), convert_to_value( customer_email .iter() .filter_map(|email| { // TODO: Add trait based inputs instead of converting this to strings serde_json::to_value(email) .ok() .and_then(|a| a.as_str().map(|a| a.to_string())) }) .collect(), ), ) .switch()?; } }; if let Some(search_tags) = filters.search_tags { if !search_tags.is_empty() { query_builder .add_filter_clause( "feature_metadata.search_tags.keyword".to_string(), convert_to_value( search_tags .iter() .filter_map(|search_tag| { // TODO: Add trait based inputs instead of converting this to strings serde_json::to_value(search_tag) .ok() .and_then(|a| a.as_str().map(|a| a.to_string())) }) .collect(), ), ) .switch()?; } }; if let Some(connector) = filters.connector { if !connector.is_empty() { query_builder .add_filter_clause("connector.keyword".to_string(), convert_to_value(connector)) .switch()?; } }; if let Some(payment_method_type) = filters.payment_method_type { if !payment_method_type.is_empty() { query_builder .add_filter_clause( "payment_method_type.keyword".to_string(), convert_to_value(payment_method_type), ) .switch()?; } }; if let Some(card_network) = filters.card_network { if !card_network.is_empty() { query_builder .add_filter_clause( "card_network.keyword".to_string(), convert_to_value(card_network), ) .switch()?; } }; if let Some(card_last_4) = filters.card_last_4 { if !card_last_4.is_empty() { query_builder .add_filter_clause( "card_last_4.keyword".to_string(), convert_to_value(card_last_4), ) .switch()?; } }; if let Some(payment_id) = filters.payment_id { if !payment_id.is_empty() { query_builder .add_filter_clause( "payment_id.keyword".to_string(), convert_to_value(payment_id), ) .switch()?; } }; if let Some(amount) = filters.amount { if !amount.is_empty() { query_builder .add_filter_clause("amount".to_string(), convert_to_value(amount)) .switch()?; } }; if let Some(customer_id) = filters.customer_id { if !customer_id.is_empty() { query_builder .add_filter_clause( "customer_id.keyword".to_string(), convert_to_value(customer_id), ) .switch()?; } }; }; if let Some(time_range) = search_req.time_range { query_builder.set_time_range(time_range.into()).switch()?; }; query_builder .set_offset_n_count(search_req.offset, search_req.count) .switch()?; let response_text: OpensearchOutput = client .execute(query_builder) .await .change_context(OpenSearchError::ConnectionError)? .text() .await .change_context(OpenSearchError::ResponseError) .and_then(|body: String| { serde_json::from_str::<OpensearchOutput>(&body) .change_context(OpenSearchError::DeserialisationError) .attach_printable(body.clone()) })?; let response_body: OpensearchOutput = response_text; match response_body { OpensearchOutput::Success(success) => Ok(GetSearchResponse { count: success.hits.total.value, index: req.index, hits: success .hits .hits .into_iter() .map(|hit| hit.source) .collect(), status: SearchStatus::Success, }), OpensearchOutput::Error(error) => { tracing::error!( index = ?req.index, error_response = ?error, "Search error" ); Ok(GetSearchResponse { count: 0, index: req.index, hits: Vec::new(), status: SearchStatus::Failure, }) } } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/enums.rs
crates/analytics/src/enums.rs
pub use common_utils::types::authentication::AuthInfo;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/types.rs
crates/analytics/src/types.rs
use std::{fmt::Display, str::FromStr}; use common_utils::{ errors::{CustomResult, ErrorSwitch, ParsingError}, events::{ApiEventMetric, ApiEventsType}, impl_api_event_type, }; use error_stack::{report, Report, ResultExt}; use super::query::QueryBuildingError; use crate::errors::AnalyticsError; #[derive(serde::Deserialize, Debug, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum AnalyticsDomain { Payments, Refunds, Frm, PaymentIntents, AuthEvents, SdkEvents, ApiEvents, Dispute, Routing, } #[derive(Debug, strum::AsRefStr, strum::Display, Clone, Copy)] pub enum AnalyticsCollection { Payment, PaymentSessionized, Refund, RefundSessionized, FraudCheck, SdkEvents, SdkEventsAnalytics, ApiEvents, PaymentIntent, PaymentIntentSessionized, ConnectorEvents, OutgoingWebhookEvent, Authentications, Dispute, DisputeSessionized, ApiEventsAnalytics, ActivePaymentsAnalytics, RoutingEvents, } #[allow(dead_code)] #[derive(Debug)] pub enum TableEngine { CollapsingMergeTree { sign: &'static str }, BasicTree, } #[derive(Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq, Hash)] #[serde(transparent)] pub struct DBEnumWrapper<T: FromStr + Display>(pub T); impl<T: FromStr + Display> AsRef<T> for DBEnumWrapper<T> { fn as_ref(&self) -> &T { &self.0 } } impl<T: FromStr + Display + Default> Default for DBEnumWrapper<T> { fn default() -> Self { Self(T::default()) } } impl<T> FromStr for DBEnumWrapper<T> where T: FromStr + Display, { type Err = Report<ParsingError>; fn from_str(s: &str) -> Result<Self, Self::Err> { T::from_str(s) .map_err(|_er| report!(ParsingError::EnumParseFailure(std::any::type_name::<T>()))) .map(DBEnumWrapper) .attach_printable_lazy(|| format!("raw_value: {s}")) } } #[async_trait::async_trait] pub trait AnalyticsDataSource where Self: Sized + Sync + Send, { type Row; async fn load_results<T>(&self, query: &str) -> CustomResult<Vec<T>, QueryExecutionError> where Self: LoadRow<T>; fn get_table_engine(_table: AnalyticsCollection) -> TableEngine { TableEngine::BasicTree } } pub trait LoadRow<T> where Self: AnalyticsDataSource, T: Sized, { fn load_row(row: Self::Row) -> CustomResult<T, QueryExecutionError>; } #[derive(thiserror::Error, Debug)] pub enum MetricsError { #[error("Error building query")] QueryBuildingError, #[error("Error running Query")] QueryExecutionFailure, #[error("Error processing query results")] PostProcessingFailure, #[allow(dead_code)] #[error("Not Implemented")] NotImplemented, } #[derive(Debug, thiserror::Error)] pub enum QueryExecutionError { #[error("Failed to extract domain rows")] RowExtractionFailure, #[error("Database error")] DatabaseError, } pub type MetricsResult<T> = CustomResult<T, MetricsError>; impl ErrorSwitch<MetricsError> for QueryBuildingError { fn switch(&self) -> MetricsError { MetricsError::QueryBuildingError } } pub type FiltersResult<T> = CustomResult<T, FiltersError>; #[derive(thiserror::Error, Debug)] pub enum FiltersError { #[error("Error building query")] QueryBuildingError, #[error("Error running Query")] QueryExecutionFailure, #[allow(dead_code)] #[error("Not Implemented: {0}")] NotImplemented(&'static str), } impl ErrorSwitch<FiltersError> for QueryBuildingError { fn switch(&self) -> FiltersError { FiltersError::QueryBuildingError } } impl ErrorSwitch<AnalyticsError> for FiltersError { fn switch(&self) -> AnalyticsError { match self { Self::QueryBuildingError | Self::QueryExecutionFailure => AnalyticsError::UnknownError, Self::NotImplemented(a) => AnalyticsError::NotImplemented(a), } } } impl_api_event_type!(Miscellaneous, (AnalyticsDomain));
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/health_check.rs
crates/analytics/src/health_check.rs
use common_utils::errors::CustomResult; use crate::types::QueryExecutionError; #[async_trait::async_trait] pub trait HealthCheck { async fn deep_health_check(&self) -> CustomResult<(), QueryExecutionError>; }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/utils.rs
crates/analytics/src/utils.rs
use api_models::analytics::{ api_event::{ApiEventDimensions, ApiEventMetrics}, auth_events::{AuthEventDimensions, AuthEventMetrics}, disputes::{DisputeDimensions, DisputeMetrics}, frm::{FrmDimensions, FrmMetrics}, payment_intents::{PaymentIntentDimensions, PaymentIntentMetrics}, payments::{PaymentDimensions, PaymentMetrics}, refunds::{RefundDimensions, RefundMetrics}, sdk_events::{SdkEventDimensions, SdkEventMetrics}, NameDescription, }; use strum::IntoEnumIterator; pub fn get_payment_dimensions() -> Vec<NameDescription> { vec![ PaymentDimensions::Connector, PaymentDimensions::PaymentMethod, PaymentDimensions::PaymentMethodType, PaymentDimensions::Currency, PaymentDimensions::AuthType, PaymentDimensions::PaymentStatus, PaymentDimensions::ClientSource, PaymentDimensions::ClientVersion, PaymentDimensions::ProfileId, PaymentDimensions::CardNetwork, PaymentDimensions::MerchantId, PaymentDimensions::RoutingApproach, ] .into_iter() .map(Into::into) .collect() } pub fn get_payment_intent_dimensions() -> Vec<NameDescription> { vec![ PaymentIntentDimensions::PaymentIntentStatus, PaymentIntentDimensions::Currency, PaymentIntentDimensions::ProfileId, PaymentIntentDimensions::Connector, PaymentIntentDimensions::AuthType, PaymentIntentDimensions::PaymentMethod, PaymentIntentDimensions::PaymentMethodType, PaymentIntentDimensions::CardNetwork, PaymentIntentDimensions::MerchantId, ] .into_iter() .map(Into::into) .collect() } pub fn get_auth_event_dimensions() -> Vec<NameDescription> { vec![ AuthEventDimensions::AuthenticationConnector, AuthEventDimensions::MessageVersion, AuthEventDimensions::AcsReferenceNumber, AuthEventDimensions::Platform, AuthEventDimensions::Mcc, AuthEventDimensions::Currency, AuthEventDimensions::MerchantCountry, AuthEventDimensions::BillingCountry, AuthEventDimensions::ShippingCountry, AuthEventDimensions::IssuerCountry, AuthEventDimensions::IssuerId, AuthEventDimensions::EarliestSupportedVersion, AuthEventDimensions::LatestSupportedVersion, AuthEventDimensions::WhitelistDecision, AuthEventDimensions::DeviceManufacturer, AuthEventDimensions::DeviceType, AuthEventDimensions::DeviceBrand, AuthEventDimensions::DeviceOs, AuthEventDimensions::DeviceDisplay, AuthEventDimensions::BrowserName, AuthEventDimensions::BrowserVersion, AuthEventDimensions::SchemeName, AuthEventDimensions::ExemptionRequested, AuthEventDimensions::ExemptionAccepted, ] .into_iter() .map(Into::into) .collect() } pub fn get_refund_dimensions() -> Vec<NameDescription> { RefundDimensions::iter().map(Into::into).collect() } pub fn get_frm_dimensions() -> Vec<NameDescription> { FrmDimensions::iter().map(Into::into).collect() } pub fn get_sdk_event_dimensions() -> Vec<NameDescription> { SdkEventDimensions::iter().map(Into::into).collect() } pub fn get_api_event_dimensions() -> Vec<NameDescription> { ApiEventDimensions::iter().map(Into::into).collect() } pub fn get_payment_metrics_info() -> Vec<NameDescription> { PaymentMetrics::iter().map(Into::into).collect() } pub fn get_payment_intent_metrics_info() -> Vec<NameDescription> { PaymentIntentMetrics::iter().map(Into::into).collect() } pub fn get_refund_metrics_info() -> Vec<NameDescription> { RefundMetrics::iter().map(Into::into).collect() } pub fn get_frm_metrics_info() -> Vec<NameDescription> { FrmMetrics::iter().map(Into::into).collect() } pub fn get_sdk_event_metrics_info() -> Vec<NameDescription> { SdkEventMetrics::iter().map(Into::into).collect() } pub fn get_auth_event_metrics_info() -> Vec<NameDescription> { AuthEventMetrics::iter().map(Into::into).collect() } pub fn get_api_event_metrics_info() -> Vec<NameDescription> { ApiEventMetrics::iter().map(Into::into).collect() } pub fn get_dispute_metrics_info() -> Vec<NameDescription> { DisputeMetrics::iter().map(Into::into).collect() } pub fn get_dispute_dimensions() -> Vec<NameDescription> { DisputeDimensions::iter().map(Into::into).collect() }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/payment_intents.rs
crates/analytics/src/payment_intents.rs
pub mod accumulator; mod core; pub mod filters; pub mod metrics; pub mod sankey; pub mod types; pub use accumulator::{PaymentIntentMetricAccumulator, PaymentIntentMetricsAccumulator}; pub trait PaymentIntentAnalytics: metrics::PaymentIntentMetricAnalytics + filters::PaymentIntentFilterAnalytics { } pub use self::core::{get_filters, get_metrics, get_sankey};
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/clickhouse.rs
crates/analytics/src/clickhouse.rs
use std::sync::Arc; use actix_web::http::StatusCode; use common_utils::errors::ParsingError; use error_stack::{report, Report, ResultExt}; use router_env::logger; use time::PrimitiveDateTime; use super::{ active_payments::metrics::ActivePaymentsMetricRow, auth_events::metrics::AuthEventMetricRow, frm::{filters::FrmFilterRow, metrics::FrmMetricRow}, health_check::HealthCheck, payment_intents::{filters::PaymentIntentFilterRow, metrics::PaymentIntentMetricRow}, payments::{ distribution::PaymentDistributionRow, filters::PaymentFilterRow, metrics::PaymentMetricRow, }, query::{Aggregate, ToSql, Window}, refunds::{ distribution::RefundDistributionRow, filters::RefundFilterRow, metrics::RefundMetricRow, }, sdk_events::{filters::SdkEventFilter, metrics::SdkEventMetricRow}, types::{AnalyticsCollection, AnalyticsDataSource, LoadRow, QueryExecutionError}, }; use crate::{ api_event::{ events::ApiLogsResult, filters::ApiEventFilter, metrics::{latency::LatencyAvg, ApiEventMetricRow}, }, auth_events::filters::AuthEventFilterRow, connector_events::events::ConnectorEventsResult, disputes::{filters::DisputeFilterRow, metrics::DisputeMetricRow}, outgoing_webhook_event::events::OutgoingWebhookLogsResult, routing_events::events::RoutingEventsResult, sdk_events::events::SdkEventsResult, types::TableEngine, }; pub type ClickhouseResult<T> = error_stack::Result<T, ClickhouseError>; #[derive(Clone, Debug)] pub struct ClickhouseClient { pub config: Arc<ClickhouseConfig>, pub database: String, } #[derive(Clone, Debug, serde::Deserialize)] pub struct ClickhouseConfig { username: String, password: Option<String>, host: String, } impl Default for ClickhouseConfig { fn default() -> Self { Self { username: "default".to_string(), password: None, host: "http://localhost:8123".to_string(), } } } impl ClickhouseClient { async fn execute_query(&self, query: &str) -> ClickhouseResult<Vec<serde_json::Value>> { logger::debug!("Executing query: {query}"); let client = reqwest::Client::new(); let params = CkhQuery { date_time_output_format: String::from("iso"), output_format_json_quote_64bit_integers: 0, database: self.database.clone(), }; let response = client .post(&self.config.host) .query(&params) .basic_auth(self.config.username.clone(), self.config.password.clone()) .body(format!("{query}\nFORMAT JSON")) .send() .await .change_context(ClickhouseError::ConnectionError)?; logger::debug!(clickhouse_response=?response, query=?query, "Clickhouse response"); if response.status() != StatusCode::OK { response.text().await.map_or_else( |er| { Err(ClickhouseError::ResponseError) .attach_printable_lazy(|| format!("Error: {er:?}")) }, |t| Err(report!(ClickhouseError::ResponseNotOK(t))), ) } else { Ok(response .json::<CkhOutput<serde_json::Value>>() .await .change_context(ClickhouseError::ResponseError)? .data) } } } #[async_trait::async_trait] impl HealthCheck for ClickhouseClient { async fn deep_health_check( &self, ) -> common_utils::errors::CustomResult<(), QueryExecutionError> { self.execute_query("SELECT 1") .await .map(|_| ()) .change_context(QueryExecutionError::DatabaseError) } } #[async_trait::async_trait] impl AnalyticsDataSource for ClickhouseClient { type Row = serde_json::Value; async fn load_results<T>( &self, query: &str, ) -> common_utils::errors::CustomResult<Vec<T>, QueryExecutionError> where Self: LoadRow<T>, { self.execute_query(query) .await .change_context(QueryExecutionError::DatabaseError)? .into_iter() .map(Self::load_row) .collect::<Result<Vec<_>, _>>() .change_context(QueryExecutionError::RowExtractionFailure) } fn get_table_engine(table: AnalyticsCollection) -> TableEngine { match table { AnalyticsCollection::Payment | AnalyticsCollection::PaymentSessionized | AnalyticsCollection::Refund | AnalyticsCollection::RefundSessionized | AnalyticsCollection::FraudCheck | AnalyticsCollection::PaymentIntent | AnalyticsCollection::PaymentIntentSessionized | AnalyticsCollection::Authentications | AnalyticsCollection::Dispute => { TableEngine::CollapsingMergeTree { sign: "sign_flag" } } AnalyticsCollection::DisputeSessionized => { TableEngine::CollapsingMergeTree { sign: "sign_flag" } } AnalyticsCollection::SdkEvents | AnalyticsCollection::SdkEventsAnalytics | AnalyticsCollection::ApiEvents | AnalyticsCollection::ConnectorEvents | AnalyticsCollection::RoutingEvents | AnalyticsCollection::ApiEventsAnalytics | AnalyticsCollection::OutgoingWebhookEvent | AnalyticsCollection::ActivePaymentsAnalytics => TableEngine::BasicTree, } } } impl<T, E> LoadRow<T> for ClickhouseClient where Self::Row: TryInto<T, Error = Report<E>>, { fn load_row(row: Self::Row) -> common_utils::errors::CustomResult<T, QueryExecutionError> { row.try_into() .map_err(|error| error.change_context(QueryExecutionError::RowExtractionFailure)) } } impl super::payments::filters::PaymentFilterAnalytics for ClickhouseClient {} impl super::payments::metrics::PaymentMetricAnalytics for ClickhouseClient {} impl super::payments::distribution::PaymentDistributionAnalytics for ClickhouseClient {} impl super::payment_intents::filters::PaymentIntentFilterAnalytics for ClickhouseClient {} impl super::payment_intents::metrics::PaymentIntentMetricAnalytics for ClickhouseClient {} impl super::refunds::metrics::RefundMetricAnalytics for ClickhouseClient {} impl super::refunds::filters::RefundFilterAnalytics for ClickhouseClient {} impl super::refunds::distribution::RefundDistributionAnalytics for ClickhouseClient {} impl super::frm::metrics::FrmMetricAnalytics for ClickhouseClient {} impl super::frm::filters::FrmFilterAnalytics for ClickhouseClient {} impl super::sdk_events::filters::SdkEventFilterAnalytics for ClickhouseClient {} impl super::sdk_events::metrics::SdkEventMetricAnalytics for ClickhouseClient {} impl super::sdk_events::events::SdkEventsFilterAnalytics for ClickhouseClient {} impl super::active_payments::metrics::ActivePaymentsMetricAnalytics for ClickhouseClient {} impl super::auth_events::metrics::AuthEventMetricAnalytics for ClickhouseClient {} impl super::auth_events::filters::AuthEventFilterAnalytics for ClickhouseClient {} impl super::api_event::events::ApiLogsFilterAnalytics for ClickhouseClient {} impl super::api_event::filters::ApiEventFilterAnalytics for ClickhouseClient {} impl super::api_event::metrics::ApiEventMetricAnalytics for ClickhouseClient {} impl super::connector_events::events::ConnectorEventLogAnalytics for ClickhouseClient {} impl super::routing_events::events::RoutingEventLogAnalytics for ClickhouseClient {} impl super::outgoing_webhook_event::events::OutgoingWebhookLogsFilterAnalytics for ClickhouseClient { } impl super::disputes::filters::DisputeFilterAnalytics for ClickhouseClient {} impl super::disputes::metrics::DisputeMetricAnalytics for ClickhouseClient {} #[derive(Debug, serde::Serialize)] struct CkhQuery { date_time_output_format: String, output_format_json_quote_64bit_integers: u8, database: String, } #[derive(Debug, serde::Deserialize)] struct CkhOutput<T> { data: Vec<T>, } impl TryInto<ApiLogsResult> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<ApiLogsResult, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse ApiLogsResult in clickhouse results", )) } } impl TryInto<SdkEventsResult> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<SdkEventsResult, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse SdkEventsResult in clickhouse results", )) } } impl TryInto<ConnectorEventsResult> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<ConnectorEventsResult, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse ConnectorEventsResult in clickhouse results", )) } } impl TryInto<RoutingEventsResult> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<RoutingEventsResult, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse RoutingEventsResult in clickhouse results", )) } } impl TryInto<PaymentMetricRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<PaymentMetricRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse PaymentMetricRow in clickhouse results", )) } } impl TryInto<PaymentDistributionRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<PaymentDistributionRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse PaymentDistributionRow in clickhouse results", )) } } impl TryInto<PaymentFilterRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<PaymentFilterRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse FilterRow in clickhouse results", )) } } impl TryInto<PaymentIntentMetricRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<PaymentIntentMetricRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse PaymentIntentMetricRow in clickhouse results", )) } } impl TryInto<PaymentIntentFilterRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<PaymentIntentFilterRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse PaymentIntentFilterRow in clickhouse results", )) } } impl TryInto<RefundMetricRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<RefundMetricRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse RefundMetricRow in clickhouse results", )) } } impl TryInto<RefundFilterRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<RefundFilterRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse RefundFilterRow in clickhouse results", )) } } impl TryInto<RefundDistributionRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<RefundDistributionRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse RefundDistributionRow in clickhouse results", )) } } impl TryInto<FrmMetricRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<FrmMetricRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse FrmMetricRow in clickhouse results", )) } } impl TryInto<FrmFilterRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<FrmFilterRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse FrmFilterRow in clickhouse results", )) } } impl TryInto<DisputeMetricRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<DisputeMetricRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse DisputeMetricRow in clickhouse results", )) } } impl TryInto<DisputeFilterRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<DisputeFilterRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse DisputeFilterRow in clickhouse results", )) } } impl TryInto<ApiEventMetricRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<ApiEventMetricRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse ApiEventMetricRow in clickhouse results", )) } } impl TryInto<LatencyAvg> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<LatencyAvg, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse LatencyAvg in clickhouse results", )) } } impl TryInto<SdkEventMetricRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<SdkEventMetricRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse SdkEventMetricRow in clickhouse results", )) } } impl TryInto<SdkEventFilter> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<SdkEventFilter, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse SdkEventFilter in clickhouse results", )) } } impl TryInto<AuthEventMetricRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<AuthEventMetricRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse AuthEventMetricRow in clickhouse results", )) } } impl TryInto<AuthEventFilterRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<AuthEventFilterRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse AuthEventFilterRow in clickhouse results", )) } } impl TryInto<ApiEventFilter> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<ApiEventFilter, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse ApiEventFilter in clickhouse results", )) } } impl TryInto<OutgoingWebhookLogsResult> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<OutgoingWebhookLogsResult, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse OutgoingWebhookLogsResult in clickhouse results", )) } } impl TryInto<ActivePaymentsMetricRow> for serde_json::Value { type Error = Report<ParsingError>; fn try_into(self) -> Result<ActivePaymentsMetricRow, Self::Error> { serde_json::from_value(self).change_context(ParsingError::StructParseFailure( "Failed to parse ActivePaymentsMetricRow in clickhouse results", )) } } impl ToSql<ClickhouseClient> for PrimitiveDateTime { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(self.assume_utc().unix_timestamp().to_string()) } } impl ToSql<ClickhouseClient> for AnalyticsCollection { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { match self { Self::Payment => Ok("payment_attempts".to_string()), Self::PaymentSessionized => Ok("sessionizer_payment_attempts".to_string()), Self::Refund => Ok("refunds".to_string()), Self::RefundSessionized => Ok("sessionizer_refunds".to_string()), Self::FraudCheck => Ok("fraud_check".to_string()), Self::SdkEvents => Ok("sdk_events_audit".to_string()), Self::SdkEventsAnalytics => Ok("sdk_events".to_string()), Self::ApiEvents => Ok("api_events_audit".to_string()), Self::ApiEventsAnalytics => Ok("api_events".to_string()), Self::PaymentIntent => Ok("payment_intents".to_string()), Self::PaymentIntentSessionized => Ok("sessionizer_payment_intents".to_string()), Self::ConnectorEvents => Ok("connector_events_audit".to_string()), Self::OutgoingWebhookEvent => Ok("outgoing_webhook_events_audit".to_string()), Self::Dispute => Ok("dispute".to_string()), Self::DisputeSessionized => Ok("sessionizer_dispute".to_string()), Self::ActivePaymentsAnalytics => Ok("active_payments".to_string()), Self::Authentications => Ok("authentications".to_string()), Self::RoutingEvents => Ok("routing_events_audit".to_string()), } } } impl<T> ToSql<ClickhouseClient> for Aggregate<T> where T: ToSql<ClickhouseClient>, { fn to_sql(&self, table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(match self { Self::Count { field: _, alias } => { let query = match table_engine { TableEngine::CollapsingMergeTree { sign } => format!("sum({sign})"), TableEngine::BasicTree => "count(*)".to_string(), }; format!( "{query}{}", alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } Self::Sum { field, alias } => { let query = match table_engine { TableEngine::CollapsingMergeTree { sign } => format!( "sum({sign} * {})", field .to_sql(table_engine) .attach_printable("Failed to sum aggregate")? ), TableEngine::BasicTree => format!( "sum({})", field .to_sql(table_engine) .attach_printable("Failed to sum aggregate")? ), }; format!( "{query}{}", alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } Self::Min { field, alias } => { format!( "min({}){}", field .to_sql(table_engine) .attach_printable("Failed to min aggregate")?, alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } Self::Max { field, alias } => { format!( "max({}){}", field .to_sql(table_engine) .attach_printable("Failed to max aggregate")?, alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } Self::Percentile { field, alias, percentile, } => { format!( "quantilesExact(0.{})({})[1]{}", percentile.map_or_else(|| "50".to_owned(), |percentile| percentile.to_string()), field .to_sql(table_engine) .attach_printable("Failed to percentile aggregate")?, alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } Self::DistinctCount { field, alias } => { format!( "count(distinct {}){}", field .to_sql(table_engine) .attach_printable("Failed to percentile aggregate")?, alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } }) } } impl<T> ToSql<ClickhouseClient> for Window<T> where T: ToSql<ClickhouseClient>, { fn to_sql(&self, table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(match self { Self::Sum { field, partition_by, order_by, alias, } => { format!( "sum({}) over ({}{}){}", field .to_sql(table_engine) .attach_printable("Failed to sum window")?, partition_by.as_ref().map_or_else( || "".to_owned(), |partition_by| format!("partition by {}", partition_by.to_owned()) ), order_by.as_ref().map_or_else( || "".to_owned(), |(order_column, order)| format!( " order by {} {}", order_column.to_owned(), order ) ), alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } Self::RowNumber { field: _, partition_by, order_by, alias, } => { format!( "row_number() over ({}{}){}", partition_by.as_ref().map_or_else( || "".to_owned(), |partition_by| format!("partition by {}", partition_by.to_owned()) ), order_by.as_ref().map_or_else( || "".to_owned(), |(order_column, order)| format!( " order by {} {}", order_column.to_owned(), order ) ), alias.map_or_else(|| "".to_owned(), |alias| format!(" as {alias}")) ) } }) } } #[derive(Debug, thiserror::Error)] pub enum ClickhouseError { #[error("Clickhouse connection error")] ConnectionError, #[error("Clickhouse NON-200 response content: '{0}'")] ResponseNotOK(String), #[error("Clickhouse response error")] ResponseError, }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/query.rs
crates/analytics/src/query.rs
use std::{fmt, marker::PhantomData}; use api_models::{ analytics::{ self as analytics_api, api_event::ApiEventDimensions, auth_events::{AuthEventDimensions, AuthEventFlows}, disputes::DisputeDimensions, frm::{FrmDimensions, FrmTransactionType}, payment_intents::PaymentIntentDimensions, payments::{PaymentDimensions, PaymentDistributions}, refunds::{RefundDimensions, RefundDistributions, RefundType}, sdk_events::{SdkEventDimensions, SdkEventNames}, Granularity, }, enums::{ AttemptStatus, AuthenticationType, Connector, Currency, DisputeStage, IntentStatus, PaymentMethod, PaymentMethodType, RoutingApproach, }, refunds::RefundStatus, }; use common_enums::{ AuthenticationConnectors, AuthenticationStatus, DecoupledAuthenticationType, TransactionStatus, }; use common_utils::{ errors::{CustomResult, ParsingError}, id_type::{MerchantId, OrganizationId, ProfileId}, }; use diesel_models::{enums as storage_enums, enums::FraudCheckStatus}; use error_stack::ResultExt; use router_env::{logger, Flow}; use super::types::{AnalyticsCollection, AnalyticsDataSource, LoadRow, TableEngine}; use crate::{enums::AuthInfo, types::QueryExecutionError}; pub type QueryResult<T> = error_stack::Result<T, QueryBuildingError>; pub trait QueryFilter<T> where T: AnalyticsDataSource, AnalyticsCollection: ToSql<T>, { fn set_filter_clause(&self, builder: &mut QueryBuilder<T>) -> QueryResult<()>; } pub trait GroupByClause<T> where T: AnalyticsDataSource, AnalyticsCollection: ToSql<T>, { fn set_group_by_clause(&self, builder: &mut QueryBuilder<T>) -> QueryResult<()>; } pub trait SeriesBucket { type SeriesType; type GranularityLevel; fn get_lowest_common_granularity_level(&self) -> Self::GranularityLevel; fn get_bucket_size(&self) -> u8; fn clip_to_start( &self, value: Self::SeriesType, ) -> error_stack::Result<Self::SeriesType, PostProcessingError>; fn clip_to_end( &self, value: Self::SeriesType, ) -> error_stack::Result<Self::SeriesType, PostProcessingError>; } impl<T> QueryFilter<T> for analytics_api::TimeRange where T: AnalyticsDataSource, time::PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, { fn set_filter_clause(&self, builder: &mut QueryBuilder<T>) -> QueryResult<()> { builder.add_custom_filter_clause("created_at", self.start_time, FilterTypes::Gte)?; if let Some(end) = self.end_time { builder.add_custom_filter_clause("created_at", end, FilterTypes::Lte)?; } Ok(()) } } impl GroupByClause<super::SqlxClient> for Granularity { fn set_group_by_clause( &self, builder: &mut QueryBuilder<super::SqlxClient>, ) -> QueryResult<()> { let trunc_scale = self.get_lowest_common_granularity_level(); let granularity_bucket_scale = match self { Self::OneMin => None, Self::FiveMin | Self::FifteenMin | Self::ThirtyMin => Some("minute"), Self::OneHour | Self::OneDay => None, }; let granularity_divisor = self.get_bucket_size(); builder .add_group_by_clause(format!("DATE_TRUNC('{trunc_scale}', created_at)")) .attach_printable("Error adding time prune group by")?; if let Some(scale) = granularity_bucket_scale { builder .add_group_by_clause(format!( "FLOOR(DATE_PART('{scale}', created_at)/{granularity_divisor})" )) .attach_printable("Error adding time binning group by")?; } Ok(()) } } impl GroupByClause<super::ClickhouseClient> for Granularity { fn set_group_by_clause( &self, builder: &mut QueryBuilder<super::ClickhouseClient>, ) -> QueryResult<()> { let interval = match self { Self::OneMin => "toStartOfMinute(created_at)", Self::FiveMin => "toStartOfFiveMinutes(created_at)", Self::FifteenMin => "toStartOfFifteenMinutes(created_at)", Self::ThirtyMin => "toStartOfInterval(created_at, INTERVAL 30 minute)", Self::OneHour => "toStartOfHour(created_at)", Self::OneDay => "toStartOfDay(created_at)", }; builder .add_group_by_clause(interval) .attach_printable("Error adding interval group by") } } #[derive(strum::Display)] #[strum(serialize_all = "lowercase")] pub enum TimeGranularityLevel { Minute, Hour, Day, } impl SeriesBucket for Granularity { type SeriesType = time::PrimitiveDateTime; type GranularityLevel = TimeGranularityLevel; fn get_lowest_common_granularity_level(&self) -> Self::GranularityLevel { match self { Self::OneMin => TimeGranularityLevel::Minute, Self::FiveMin | Self::FifteenMin | Self::ThirtyMin | Self::OneHour => { TimeGranularityLevel::Hour } Self::OneDay => TimeGranularityLevel::Day, } } fn get_bucket_size(&self) -> u8 { match self { Self::OneMin => 60, Self::FiveMin => 5, Self::FifteenMin => 15, Self::ThirtyMin => 30, Self::OneHour => 60, Self::OneDay => 24, } } fn clip_to_start( &self, value: Self::SeriesType, ) -> error_stack::Result<Self::SeriesType, PostProcessingError> { let clip_start = |value: u8, modulo: u8| -> u8 { value - value % modulo }; let clipped_time = match ( self.get_lowest_common_granularity_level(), self.get_bucket_size(), ) { (TimeGranularityLevel::Minute, i) => time::Time::MIDNIGHT .replace_second(clip_start(value.second(), i)) .and_then(|t| t.replace_minute(value.minute())) .and_then(|t| t.replace_hour(value.hour())), (TimeGranularityLevel::Hour, i) => time::Time::MIDNIGHT .replace_minute(clip_start(value.minute(), i)) .and_then(|t| t.replace_hour(value.hour())), (TimeGranularityLevel::Day, i) => { time::Time::MIDNIGHT.replace_hour(clip_start(value.hour(), i)) } } .change_context(PostProcessingError::BucketClipping)?; Ok(value.replace_time(clipped_time)) } fn clip_to_end( &self, value: Self::SeriesType, ) -> error_stack::Result<Self::SeriesType, PostProcessingError> { let clip_end = |value: u8, modulo: u8| -> u8 { value + modulo - 1 - value % modulo }; let clipped_time = match ( self.get_lowest_common_granularity_level(), self.get_bucket_size(), ) { (TimeGranularityLevel::Minute, i) => time::Time::MIDNIGHT .replace_second(clip_end(value.second(), i)) .and_then(|t| t.replace_minute(value.minute())) .and_then(|t| t.replace_hour(value.hour())), (TimeGranularityLevel::Hour, i) => time::Time::MIDNIGHT .replace_minute(clip_end(value.minute(), i)) .and_then(|t| t.replace_hour(value.hour())), (TimeGranularityLevel::Day, i) => { time::Time::MIDNIGHT.replace_hour(clip_end(value.hour(), i)) } } .change_context(PostProcessingError::BucketClipping) .attach_printable_lazy(|| format!("Bucket Clip Error: {value}"))?; Ok(value.replace_time(clipped_time)) } } #[derive(thiserror::Error, Debug)] pub enum QueryBuildingError { #[allow(dead_code)] #[error("Not Implemented: {0}")] NotImplemented(String), #[error("Failed to Serialize to SQL")] SqlSerializeError, #[error("Failed to build sql query: {0}")] InvalidQuery(&'static str), } #[derive(thiserror::Error, Debug)] pub enum PostProcessingError { #[error("Error Clipping values to bucket sizes")] BucketClipping, } #[derive(Debug)] pub enum Aggregate<R> { Count { field: Option<R>, alias: Option<&'static str>, }, Sum { field: R, alias: Option<&'static str>, }, Min { field: R, alias: Option<&'static str>, }, Max { field: R, alias: Option<&'static str>, }, Percentile { field: R, alias: Option<&'static str>, percentile: Option<&'static u8>, }, DistinctCount { field: R, alias: Option<&'static str>, }, } // Window functions in query // --- // Description - // field: to_sql type value used as expr in aggregation // partition_by: partition by fields in window // order_by: order by fields and order (Ascending / Descending) in window // alias: alias of window expr in query // --- // Usage - // Window::Sum { // field: "count", // partition_by: Some(query_builder.transform_to_sql_values(&dimensions).switch()?), // order_by: Some(("value", Descending)), // alias: Some("total"), // } #[derive(Debug)] pub enum Window<R> { Sum { field: R, partition_by: Option<String>, order_by: Option<(String, Order)>, alias: Option<&'static str>, }, RowNumber { field: R, partition_by: Option<String>, order_by: Option<(String, Order)>, alias: Option<&'static str>, }, } #[derive(Debug, Clone, Copy)] pub enum Order { Ascending, Descending, } impl fmt::Display for Order { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Ascending => write!(f, "asc"), Self::Descending => write!(f, "desc"), } } } // Select TopN values for a group based on a metric // --- // Description - // columns: Columns in group to select TopN values for // count: N in TopN // order_column: metric used to sort and limit TopN // order: sort order of metric (Ascending / Descending) // --- // Usage - // Use via add_top_n_clause fn of query_builder // add_top_n_clause( // &dimensions, // distribution.distribution_cardinality.into(), // "count", // Order::Descending, // ) #[allow(dead_code)] #[derive(Debug)] pub struct TopN { pub columns: String, pub count: u64, pub order_column: String, pub order: Order, } #[derive(Debug, Clone)] pub struct LimitByClause { limit: u64, columns: Vec<String>, } impl fmt::Display for LimitByClause { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "LIMIT {} BY {}", self.limit, self.columns.join(", ")) } } #[derive(Debug, Default, Clone, Copy)] pub enum FilterCombinator { #[default] And, Or, } impl<T: AnalyticsDataSource> ToSql<T> for FilterCombinator { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(match self { Self::And => " AND ", Self::Or => " OR ", } .to_owned()) } } #[derive(Debug, Clone)] pub enum Filter { Plain(String, FilterTypes, String), NestedFilter(FilterCombinator, Vec<Self>), } impl Default for Filter { fn default() -> Self { Self::NestedFilter(FilterCombinator::default(), Vec::new()) } } impl<T: AnalyticsDataSource> ToSql<T> for Filter { fn to_sql(&self, table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(match self { Self::Plain(l, op, r) => filter_type_to_sql(l, *op, r), Self::NestedFilter(operator, filters) => { format!( "( {} )", filters .iter() .map(|f| <Self as ToSql<T>>::to_sql(f, table_engine)) .collect::<Result<Vec<String>, _>>()? .join( <FilterCombinator as ToSql<T>>::to_sql(operator, table_engine)? .as_ref() ) ) } }) } } #[derive(Debug)] pub struct QueryBuilder<T> where T: AnalyticsDataSource, AnalyticsCollection: ToSql<T>, { columns: Vec<String>, filters: Filter, group_by: Vec<String>, order_by: Vec<String>, having: Option<Vec<(String, FilterTypes, String)>>, limit_by: Option<LimitByClause>, outer_select: Vec<String>, top_n: Option<TopN>, table: AnalyticsCollection, distinct: bool, db_type: PhantomData<T>, table_engine: TableEngine, } pub trait ToSql<T: AnalyticsDataSource> { fn to_sql(&self, table_engine: &TableEngine) -> error_stack::Result<String, ParsingError>; } impl<T: AnalyticsDataSource> ToSql<T> for &MerchantId { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(self.get_string_repr().to_owned()) } } impl<T: AnalyticsDataSource> ToSql<T> for MerchantId { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(self.get_string_repr().to_owned()) } } impl<T: AnalyticsDataSource> ToSql<T> for &OrganizationId { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(self.get_string_repr().to_owned()) } } impl<T: AnalyticsDataSource> ToSql<T> for ProfileId { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(self.get_string_repr().to_owned()) } } impl<T: AnalyticsDataSource> ToSql<T> for &common_utils::id_type::PaymentId { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(self.get_string_repr().to_owned()) } } impl<T: AnalyticsDataSource> ToSql<T> for common_utils::id_type::CustomerId { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(self.get_string_repr().to_owned()) } } impl<T: AnalyticsDataSource> ToSql<T> for bool { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { let flag = *self; Ok(i8::from(flag).to_string()) } } /// Implement `ToSql` on arrays of types that impl `ToString`. macro_rules! impl_to_sql_for_to_string { ($($type:ty),+) => { $( impl<T: AnalyticsDataSource> ToSql<T> for $type { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { Ok(self.to_string()) } } )+ }; } impl_to_sql_for_to_string!( String, &str, &PaymentDimensions, &PaymentIntentDimensions, &RefundDimensions, &FrmDimensions, PaymentDimensions, PaymentIntentDimensions, &PaymentDistributions, RefundDimensions, &RefundDistributions, FrmDimensions, PaymentMethod, PaymentMethodType, AuthenticationType, Connector, AttemptStatus, IntentStatus, RefundStatus, FraudCheckStatus, storage_enums::RefundStatus, Currency, RefundType, FrmTransactionType, TransactionStatus, AuthenticationStatus, AuthenticationConnectors, DecoupledAuthenticationType, Flow, &String, &bool, &u64, u64, Order, RoutingApproach ); impl_to_sql_for_to_string!( &SdkEventDimensions, SdkEventDimensions, SdkEventNames, AuthEventFlows, &ApiEventDimensions, ApiEventDimensions, &DisputeDimensions, DisputeDimensions, DisputeStage, AuthEventDimensions, &AuthEventDimensions ); #[derive(Debug, Clone, Copy)] pub enum FilterTypes { Equal, NotEqual, EqualBool, In, Gte, Lte, Gt, Like, NotLike, IsNotNull, } pub fn filter_type_to_sql(l: &str, op: FilterTypes, r: &str) -> String { match op { FilterTypes::EqualBool => format!("{l} = {r}"), FilterTypes::Equal => format!("{l} = '{r}'"), FilterTypes::NotEqual => format!("{l} != '{r}'"), FilterTypes::In => format!("{l} IN ({r})"), FilterTypes::Gte => format!("{l} >= '{r}'"), FilterTypes::Gt => format!("{l} > {r}"), FilterTypes::Lte => format!("{l} <= '{r}'"), FilterTypes::Like => format!("{l} LIKE '%{r}%'"), FilterTypes::NotLike => format!("{l} NOT LIKE '%{r}%'"), FilterTypes::IsNotNull => format!("{l} IS NOT NULL"), } } impl<T> QueryBuilder<T> where T: AnalyticsDataSource, AnalyticsCollection: ToSql<T>, { pub fn new(table: AnalyticsCollection) -> Self { Self { columns: Default::default(), filters: Default::default(), group_by: Default::default(), order_by: Default::default(), having: Default::default(), limit_by: Default::default(), outer_select: Default::default(), top_n: Default::default(), table, distinct: Default::default(), db_type: Default::default(), table_engine: T::get_table_engine(table), } } pub fn add_select_column(&mut self, column: impl ToSql<T>) -> QueryResult<()> { self.columns.push( column .to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing select column")?, ); Ok(()) } pub fn transform_to_sql_values(&mut self, values: &[impl ToSql<T>]) -> QueryResult<String> { let res = values .iter() .map(|i| i.to_sql(&self.table_engine)) .collect::<error_stack::Result<Vec<String>, ParsingError>>() .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing range filter value")? .join(", "); Ok(res) } pub fn add_top_n_clause( &mut self, columns: &[impl ToSql<T>], count: u64, order_column: impl ToSql<T>, order: Order, ) -> QueryResult<()> where Window<&'static str>: ToSql<T>, { let partition_by_columns = self.transform_to_sql_values(columns)?; let order_by_column = order_column .to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing select column")?; self.add_outer_select_column(Window::RowNumber { field: "", partition_by: Some(partition_by_columns.clone()), order_by: Some((order_by_column.clone(), order)), alias: Some("top_n"), })?; self.top_n = Some(TopN { columns: partition_by_columns, count, order_column: order_by_column, order, }); Ok(()) } pub fn set_distinct(&mut self) { self.distinct = true } pub fn add_filter_clause( &mut self, key: impl ToSql<T>, value: impl ToSql<T>, ) -> QueryResult<()> { self.add_custom_filter_clause(key, value, FilterTypes::Equal) } pub fn add_bool_filter_clause( &mut self, key: impl ToSql<T>, value: impl ToSql<T>, ) -> QueryResult<()> { self.add_custom_filter_clause(key, value, FilterTypes::EqualBool) } pub fn add_negative_filter_clause( &mut self, key: impl ToSql<T>, value: impl ToSql<T>, ) -> QueryResult<()> { self.add_custom_filter_clause(key, value, FilterTypes::NotEqual) } pub fn add_custom_filter_clause( &mut self, lhs: impl ToSql<T>, rhs: impl ToSql<T>, comparison: FilterTypes, ) -> QueryResult<()> { let filter = Filter::Plain( lhs.to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing filter key")?, comparison, rhs.to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing filter value")?, ); self.add_nested_filter_clause(filter); Ok(()) } pub fn add_nested_filter_clause(&mut self, filter: Filter) { match &mut self.filters { Filter::NestedFilter(_, ref mut filters) => filters.push(filter), f @ Filter::Plain(_, _, _) => { self.filters = Filter::NestedFilter(FilterCombinator::And, vec![f.clone(), filter]); } } } pub fn add_filter_in_range_clause( &mut self, key: impl ToSql<T>, values: &[impl ToSql<T>], ) -> QueryResult<()> { let list = values .iter() .map(|i| { // trimming whitespaces from the filter values received in request, to prevent a possibility of an SQL injection i.to_sql(&self.table_engine).map(|s| { let trimmed_str = s.replace(' ', ""); format!("'{trimmed_str}'") }) }) .collect::<error_stack::Result<Vec<String>, ParsingError>>() .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing range filter value")? .join(", "); self.add_custom_filter_clause(key, list, FilterTypes::In) } pub fn add_group_by_clause(&mut self, column: impl ToSql<T>) -> QueryResult<()> { self.group_by.push( column .to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing group by field")?, ); Ok(()) } pub fn add_order_by_clause( &mut self, column: impl ToSql<T>, order: impl ToSql<T>, ) -> QueryResult<()> { let column_sql = column .to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing order by column")?; let order_sql = order .to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing order direction")?; self.order_by.push(format!("{column_sql} {order_sql}")); Ok(()) } pub fn set_limit_by(&mut self, limit: u64, columns: &[impl ToSql<T>]) -> QueryResult<()> { let columns = columns .iter() .map(|col| col.to_sql(&self.table_engine)) .collect::<Result<Vec<String>, _>>() .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing LIMIT BY columns")?; self.limit_by = Some(LimitByClause { limit, columns }); Ok(()) } pub fn add_granularity_in_mins(&mut self, granularity: Granularity) -> QueryResult<()> { let interval = match granularity { Granularity::OneMin => "1", Granularity::FiveMin => "5", Granularity::FifteenMin => "15", Granularity::ThirtyMin => "30", Granularity::OneHour => "60", Granularity::OneDay => "1440", }; let _ = self.add_select_column(format!( "toStartOfInterval(created_at, INTERVAL {interval} MINUTE) as time_bucket" )); Ok(()) } fn get_filter_clause(&self) -> QueryResult<String> { <Filter as ToSql<T>>::to_sql(&self.filters, &self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) } fn get_select_clause(&self) -> String { self.columns.join(", ") } fn get_group_by_clause(&self) -> String { self.group_by.join(", ") } fn get_outer_select_clause(&self) -> String { self.outer_select.join(", ") } pub fn add_having_clause<R>( &mut self, aggregate: Aggregate<R>, filter_type: FilterTypes, value: impl ToSql<T>, ) -> QueryResult<()> where Aggregate<R>: ToSql<T>, { let aggregate = aggregate .to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing having aggregate")?; let value = value .to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing having value")?; let entry = (aggregate, filter_type, value); if let Some(having) = &mut self.having { having.push(entry); } else { self.having = Some(vec![entry]); } Ok(()) } pub fn add_outer_select_column(&mut self, column: impl ToSql<T>) -> QueryResult<()> { self.outer_select.push( column .to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing outer select column")?, ); Ok(()) } pub fn get_filter_type_clause(&self) -> Option<String> { self.having.as_ref().map(|vec| { vec.iter() .map(|(l, op, r)| filter_type_to_sql(l, *op, r)) .collect::<Vec<String>>() .join(" AND ") }) } pub fn build_query(&mut self) -> QueryResult<String> where Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { if self.columns.is_empty() { Err(QueryBuildingError::InvalidQuery( "No select fields provided", ))?; } let mut query = String::from("SELECT "); if self.distinct { query.push_str("DISTINCT "); } query.push_str(&self.get_select_clause()); query.push_str(" FROM "); query.push_str( &self .table .to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing table value")?, ); let filter_clause = self.get_filter_clause()?; if !filter_clause.is_empty() { query.push_str(" WHERE "); query.push_str(filter_clause.as_str()); } if !self.group_by.is_empty() { query.push_str(" GROUP BY "); query.push_str(&self.get_group_by_clause()); if let TableEngine::CollapsingMergeTree { sign } = self.table_engine { self.add_having_clause( Aggregate::Count { field: Some(sign), alias: None, }, FilterTypes::Gte, "1", )?; } } if self.having.is_some() { if let Some(condition) = self.get_filter_type_clause() { query.push_str(" HAVING "); query.push_str(condition.as_str()); } } if !self.order_by.is_empty() { query.push_str(" ORDER BY "); query.push_str(&self.order_by.join(", ")); } if let Some(limit_by) = &self.limit_by { query.push_str(&format!(" {limit_by}")); } if !self.outer_select.is_empty() { query.insert_str( 0, format!("SELECT {} FROM (", &self.get_outer_select_clause()).as_str(), ); query.push_str(") _"); } if let Some(top_n) = &self.top_n { query.insert_str(0, "SELECT * FROM ("); query.push_str(format!(") _ WHERE top_n <= {}", top_n.count).as_str()); } logger::debug!(%query); Ok(query) } pub async fn execute_query<R, P>( &mut self, store: &P, ) -> CustomResult<CustomResult<Vec<R>, QueryExecutionError>, QueryBuildingError> where P: LoadRow<R> + AnalyticsDataSource, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { let query = self .build_query() .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Failed to execute query")?; Ok(store.load_results(query.as_str()).await) } } impl<T> QueryFilter<T> for AuthInfo where T: AnalyticsDataSource, AnalyticsCollection: ToSql<T>, { fn set_filter_clause(&self, builder: &mut QueryBuilder<T>) -> QueryResult<()> { match self { Self::OrgLevel { org_id } => { builder .add_filter_clause("organization_id", org_id) .attach_printable("Error adding organization_id filter")?; } Self::MerchantLevel { org_id, merchant_ids, } => { builder .add_filter_clause("organization_id", org_id) .attach_printable("Error adding organization_id filter")?; builder .add_filter_in_range_clause("merchant_id", merchant_ids) .attach_printable("Error adding merchant_id filter")?; } Self::ProfileLevel { org_id, merchant_id, profile_ids, } => { builder .add_filter_clause("organization_id", org_id) .attach_printable("Error adding organization_id filter")?; builder .add_filter_clause("merchant_id", merchant_id) .attach_printable("Error adding merchant_id filter")?; builder .add_filter_in_range_clause("profile_id", profile_ids) .attach_printable("Error adding profile_id filter")?; } } Ok(()) } }
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/metrics.rs
crates/analytics/src/metrics.rs
use router_env::{global_meter, histogram_metric_f64, histogram_metric_u64}; global_meter!(GLOBAL_METER, "ROUTER_API"); histogram_metric_f64!(METRIC_FETCH_TIME, GLOBAL_METER); histogram_metric_u64!(BUCKETS_FETCHED, GLOBAL_METER); pub mod request;
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/frm.rs
crates/analytics/src/frm.rs
pub mod accumulator; mod core; pub mod filters; pub mod metrics; pub mod types; pub use accumulator::{FrmMetricAccumulator, FrmMetricsAccumulator}; pub use self::core::{get_filters, get_metrics};
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/api_event.rs
crates/analytics/src/api_event.rs
mod core; pub mod events; pub mod filters; pub mod metrics; pub mod types; pub trait APIEventAnalytics: events::ApiLogsFilterAnalytics {} pub use self::core::{api_events_core, get_api_event_metrics, get_filters};
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/payments.rs
crates/analytics/src/payments.rs
pub mod accumulator; mod core; pub mod distribution; pub mod filters; pub mod metrics; pub mod types; pub use accumulator::{ PaymentDistributionAccumulator, PaymentMetricAccumulator, PaymentMetricsAccumulator, }; pub trait PaymentAnalytics: metrics::PaymentMetricAnalytics + filters::PaymentFilterAnalytics { } pub use self::core::{get_filters, get_metrics};
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
false
juspay/hyperswitch
https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/sqlx.rs
crates/analytics/src/sqlx.rs
use std::{fmt::Display, str::FromStr}; use api_models::{ analytics::{frm::FrmTransactionType, refunds::RefundType}, enums::{DisputeStage, DisputeStatus}, }; use common_enums::{ AuthenticationConnectors, AuthenticationStatus, DecoupledAuthenticationType, TransactionStatus, }; use common_utils::{ errors::{CustomResult, ParsingError}, DbConnectionParams, }; use diesel_models::enums::{ AttemptStatus, AuthenticationType, Currency, FraudCheckStatus, IntentStatus, PaymentMethod, RefundStatus, RoutingApproach, }; use error_stack::ResultExt; use sqlx::{ postgres::{PgArgumentBuffer, PgPoolOptions, PgRow, PgTypeInfo, PgValueRef}, Decode, Encode, Error::ColumnNotFound, FromRow, Pool, Postgres, Row, }; use storage_impl::config::Database; use time::PrimitiveDateTime; use super::{ health_check::HealthCheck, query::{Aggregate, ToSql, Window}, types::{ AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, QueryExecutionError, TableEngine, }, }; #[derive(Debug, Clone)] pub struct SqlxClient { pool: Pool<Postgres>, } impl Default for SqlxClient { fn default() -> Self { let database_url = format!( "postgres://{}:{}@{}:{}/{}", "db_user", "db_pass", "localhost", 5432, "hyperswitch_db" ); Self { #[allow(clippy::expect_used)] pool: PgPoolOptions::new() .connect_lazy(&database_url) .expect("SQLX Pool Creation failed"), } } } impl SqlxClient { pub async fn from_conf(conf: &Database, schema: &str) -> Self { let database_url = conf.get_database_url(schema); #[allow(clippy::expect_used)] let pool = PgPoolOptions::new() .max_connections(conf.pool_size) .acquire_timeout(std::time::Duration::from_secs(conf.connection_timeout)) .connect_lazy(&database_url) .expect("SQLX Pool Creation failed"); Self { pool } } } pub trait DbType { fn name() -> &'static str; } macro_rules! db_type { ($a: ident, $str: tt) => { impl DbType for $a { fn name() -> &'static str { stringify!($str) } } }; ($a:ident) => { impl DbType for $a { fn name() -> &'static str { stringify!($a) } } }; } db_type!(Currency); db_type!(AuthenticationType); db_type!(AttemptStatus); db_type!(IntentStatus); db_type!(PaymentMethod, TEXT); db_type!(RefundStatus); db_type!(RefundType); db_type!(FraudCheckStatus); db_type!(FrmTransactionType); db_type!(DisputeStage); db_type!(DisputeStatus); db_type!(AuthenticationStatus); db_type!(TransactionStatus); db_type!(AuthenticationConnectors); db_type!(DecoupledAuthenticationType); db_type!(RoutingApproach); impl<'q, Type> Encode<'q, Postgres> for DBEnumWrapper<Type> where Type: DbType + FromStr + Display, { fn encode_by_ref( &self, buf: &mut PgArgumentBuffer, ) -> Result<sqlx::encode::IsNull, Box<dyn std::error::Error + Send + Sync + 'static>> { <String as Encode<'q, Postgres>>::encode(self.0.to_string(), buf) } fn size_hint(&self) -> usize { <String as Encode<'q, Postgres>>::size_hint(&self.0.to_string()) } } impl<'r, Type> Decode<'r, Postgres> for DBEnumWrapper<Type> where Type: DbType + FromStr + Display, { fn decode( value: PgValueRef<'r>, ) -> Result<Self, Box<dyn std::error::Error + 'static + Send + Sync>> { let str_value = <&'r str as Decode<'r, Postgres>>::decode(value)?; Type::from_str(str_value).map(DBEnumWrapper).or(Err(format!( "invalid value {:?} for enum {}", str_value, Type::name() ) .into())) } } impl<Type> sqlx::Type<Postgres> for DBEnumWrapper<Type> where Type: DbType + FromStr + Display, { fn type_info() -> PgTypeInfo { PgTypeInfo::with_name(Type::name()) } } impl<T> LoadRow<T> for SqlxClient where for<'a> T: FromRow<'a, PgRow>, { fn load_row(row: PgRow) -> CustomResult<T, QueryExecutionError> { T::from_row(&row).change_context(QueryExecutionError::RowExtractionFailure) } } impl super::payments::filters::PaymentFilterAnalytics for SqlxClient {} impl super::payments::metrics::PaymentMetricAnalytics for SqlxClient {} impl super::payments::distribution::PaymentDistributionAnalytics for SqlxClient {} impl super::payment_intents::filters::PaymentIntentFilterAnalytics for SqlxClient {} impl super::payment_intents::metrics::PaymentIntentMetricAnalytics for SqlxClient {} impl super::refunds::metrics::RefundMetricAnalytics for SqlxClient {} impl super::refunds::filters::RefundFilterAnalytics for SqlxClient {} impl super::refunds::distribution::RefundDistributionAnalytics for SqlxClient {} impl super::disputes::filters::DisputeFilterAnalytics for SqlxClient {} impl super::disputes::metrics::DisputeMetricAnalytics for SqlxClient {} impl super::frm::metrics::FrmMetricAnalytics for SqlxClient {} impl super::frm::filters::FrmFilterAnalytics for SqlxClient {} impl super::auth_events::metrics::AuthEventMetricAnalytics for SqlxClient {} impl super::auth_events::filters::AuthEventFilterAnalytics for SqlxClient {} #[async_trait::async_trait] impl AnalyticsDataSource for SqlxClient { type Row = PgRow; async fn load_results<T>(&self, query: &str) -> CustomResult<Vec<T>, QueryExecutionError> where Self: LoadRow<T>, { sqlx::query(&format!("{query};")) .fetch_all(&self.pool) .await .change_context(QueryExecutionError::DatabaseError) .attach_printable_lazy(|| format!("Failed to run query {query}"))? .into_iter() .map(Self::load_row) .collect::<Result<Vec<_>, _>>() .change_context(QueryExecutionError::RowExtractionFailure) } } #[async_trait::async_trait] impl HealthCheck for SqlxClient { async fn deep_health_check(&self) -> CustomResult<(), QueryExecutionError> { sqlx::query("SELECT 1") .fetch_all(&self.pool) .await .map(|_| ()) .change_context(QueryExecutionError::DatabaseError) } } impl<'a> FromRow<'a, PgRow> for super::auth_events::metrics::AuthEventMetricRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let authentication_status: Option<DBEnumWrapper<AuthenticationStatus>> = row.try_get("authentication_status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let trans_status: Option<DBEnumWrapper<TransactionStatus>> = row.try_get("trans_status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let authentication_type: Option<DBEnumWrapper<DecoupledAuthenticationType>> = row.try_get("authentication_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let error_message: Option<String> = row.try_get("error_message").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let authentication_connector: Option<DBEnumWrapper<AuthenticationConnectors>> = row .try_get("authentication_connector") .or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let message_version: Option<String> = row.try_get("message_version").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let platform: Option<String> = row.try_get("platform").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let acs_reference_number: Option<String> = row.try_get("acs_reference_number").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let count: Option<i64> = row.try_get("count").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; // Removing millisecond precision to get accurate diffs against clickhouse let start_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("start_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); let end_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("end_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); let mcc: Option<String> = row.try_get("mcc").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let currency: Option<DBEnumWrapper<Currency>> = row.try_get("currency").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let merchant_country: Option<String> = row.try_get("merchant_country").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let billing_country: Option<String> = row.try_get("billing_country").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let shipping_country: Option<String> = row.try_get("shipping_country").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let issuer_country: Option<String> = row.try_get("issuer_country").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let earliest_supported_version: Option<String> = row .try_get("earliest_supported_version") .or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let latest_supported_version: Option<String> = row .try_get("latest_supported_version") .or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let whitelist_decision: Option<bool> = row.try_get("whitelist_decision").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let device_manufacturer: Option<String> = row.try_get("device_manufacturer").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let device_type: Option<String> = row.try_get("device_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let device_brand: Option<String> = row.try_get("device_brand").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let device_os: Option<String> = row.try_get("device_os").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let device_display: Option<String> = row.try_get("device_display").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let browser_name: Option<String> = row.try_get("browser_name").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let browser_version: Option<String> = row.try_get("browser_version").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let issuer_id: Option<String> = row.try_get("issuer_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let scheme_name: Option<String> = row.try_get("scheme_name").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let exemption_requested: Option<bool> = row.try_get("exemption_requested").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let exemption_accepted: Option<bool> = row.try_get("exemption_accepted").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; Ok(Self { authentication_status, trans_status, authentication_type, error_message, authentication_connector, message_version, acs_reference_number, platform, count, start_bucket, end_bucket, mcc, currency, merchant_country, billing_country, shipping_country, issuer_country, earliest_supported_version, latest_supported_version, whitelist_decision, device_manufacturer, device_type, device_brand, device_os, device_display, browser_name, browser_version, issuer_id, scheme_name, exemption_requested, exemption_accepted, }) } } impl<'a> FromRow<'a, PgRow> for super::auth_events::filters::AuthEventFilterRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let authentication_status: Option<DBEnumWrapper<AuthenticationStatus>> = row.try_get("authentication_status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let trans_status: Option<DBEnumWrapper<TransactionStatus>> = row.try_get("trans_status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let authentication_type: Option<DBEnumWrapper<DecoupledAuthenticationType>> = row.try_get("authentication_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let error_message: Option<String> = row.try_get("error_message").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let authentication_connector: Option<DBEnumWrapper<AuthenticationConnectors>> = row .try_get("authentication_connector") .or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let message_version: Option<String> = row.try_get("message_version").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let acs_reference_number: Option<String> = row.try_get("acs_reference_number").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let platform: Option<String> = row.try_get("platform").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let mcc: Option<String> = row.try_get("mcc").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let currency: Option<DBEnumWrapper<Currency>> = row.try_get("currency").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let merchant_country: Option<String> = row.try_get("merchant_country").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let billing_country: Option<String> = row.try_get("billing_country").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let shipping_country: Option<String> = row.try_get("shipping_country").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let issuer_country: Option<String> = row.try_get("issuer_country").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let earliest_supported_version: Option<String> = row .try_get("earliest_supported_version") .or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let latest_supported_version: Option<String> = row .try_get("latest_supported_version") .or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let whitelist_decision: Option<bool> = row.try_get("whitelist_decision").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let device_manufacturer: Option<String> = row.try_get("device_manufacturer").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let device_type: Option<String> = row.try_get("device_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let device_brand: Option<String> = row.try_get("device_brand").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let device_os: Option<String> = row.try_get("device_os").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let device_display: Option<String> = row.try_get("device_display").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let browser_name: Option<String> = row.try_get("browser_name").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let browser_version: Option<String> = row.try_get("browser_version").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let issuer_id: Option<String> = row.try_get("issuer_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let scheme_name: Option<String> = row.try_get("scheme_name").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let exemption_requested: Option<bool> = row.try_get("exemption_requested").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let exemption_accepted: Option<bool> = row.try_get("exemption_accepted").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; Ok(Self { authentication_status, trans_status, authentication_type, error_message, authentication_connector, message_version, platform, acs_reference_number, mcc, currency, merchant_country, billing_country, shipping_country, issuer_country, earliest_supported_version, latest_supported_version, whitelist_decision, device_manufacturer, device_type, device_brand, device_os, device_display, browser_name, browser_version, issuer_id, scheme_name, exemption_requested, exemption_accepted, }) } } impl<'a> FromRow<'a, PgRow> for super::refunds::metrics::RefundMetricRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let currency: Option<DBEnumWrapper<Currency>> = row.try_get("currency").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let refund_status: Option<DBEnumWrapper<RefundStatus>> = row.try_get("refund_status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let connector: Option<String> = row.try_get("connector").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let refund_type: Option<DBEnumWrapper<RefundType>> = row.try_get("refund_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let profile_id: Option<String> = row.try_get("profile_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let refund_reason: Option<String> = row.try_get("refund_reason").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let refund_error_message: Option<String> = row.try_get("refund_error_message").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let count: Option<i64> = row.try_get("count").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; // Removing millisecond precision to get accurate diffs against clickhouse let start_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("start_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); let end_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("end_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); Ok(Self { currency, refund_status, connector, refund_type, profile_id, refund_reason, refund_error_message, total, count, start_bucket, end_bucket, }) } } impl<'a> FromRow<'a, PgRow> for super::frm::metrics::FrmMetricRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let frm_name: Option<String> = row.try_get("frm_name").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let frm_status: Option<DBEnumWrapper<FraudCheckStatus>> = row.try_get("frm_status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let frm_transaction_type: Option<DBEnumWrapper<FrmTransactionType>> = row.try_get("frm_transaction_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let count: Option<i64> = row.try_get("count").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; // Removing millisecond precision to get accurate diffs against clickhouse let start_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("start_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); let end_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("end_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); Ok(Self { frm_name, frm_status, frm_transaction_type, total, count, start_bucket, end_bucket, }) } } impl<'a> FromRow<'a, PgRow> for super::payments::metrics::PaymentMetricRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let currency: Option<DBEnumWrapper<Currency>> = row.try_get("currency").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let status: Option<DBEnumWrapper<AttemptStatus>> = row.try_get("status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let connector: Option<String> = row.try_get("connector").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let authentication_type: Option<DBEnumWrapper<AuthenticationType>> = row.try_get("authentication_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let payment_method: Option<String> = row.try_get("payment_method").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let payment_method_type: Option<String> = row.try_get("payment_method_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let client_source: Option<String> = row.try_get("client_source").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let client_version: Option<String> = row.try_get("client_version").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let profile_id: Option<String> = row.try_get("profile_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let first_attempt: Option<bool> = row.try_get("first_attempt").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let routing_approach: Option<DBEnumWrapper<RoutingApproach>> = row.try_get("routing_approach").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let signature_network: Option<String> = row.try_get("signature_network").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let is_issuer_regulated: Option<bool> = row.try_get("is_issuer_regulated").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let is_debit_routed: Option<bool> = row.try_get("is_debit_routed").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let count: Option<i64> = row.try_get("count").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; // Removing millisecond precision to get accurate diffs against clickhouse let start_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("start_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); let end_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("end_bucket")? .and_then(|dt| dt.replace_millisecond(0).ok()); Ok(Self { currency, status, connector, authentication_type, payment_method, payment_method_type, client_source, client_version, profile_id, card_network, merchant_id, card_last_4, card_issuer, error_reason, first_attempt, routing_approach, signature_network, is_issuer_regulated, is_debit_routed, total, count, start_bucket, end_bucket, }) } } impl<'a> FromRow<'a, PgRow> for super::payments::distribution::PaymentDistributionRow { fn from_row(row: &'a PgRow) -> sqlx::Result<Self> { let currency: Option<DBEnumWrapper<Currency>> = row.try_get("currency").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let status: Option<DBEnumWrapper<AttemptStatus>> = row.try_get("status").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let connector: Option<String> = row.try_get("connector").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let authentication_type: Option<DBEnumWrapper<AuthenticationType>> = row.try_get("authentication_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let payment_method: Option<String> = row.try_get("payment_method").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let payment_method_type: Option<String> = row.try_get("payment_method_type").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; let client_source: Option<String> = row.try_get("client_source").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()),
rust
Apache-2.0
4201e04a8f0f1d46b57f24868f4f943a9be50bda
2026-01-04T15:31:59.475325Z
true