open-standards/openpay/crates/op-bnpl/tests/affirm_roundtrip.rs
Transaction Science 6575ff1eb7 Ingest batch 3: 9 more crates across openpay / smart-byte / eoc
openpay/ (+3 crates)
  op-bnpl/        Affirm + Klarna + Afterpay/Clearpay rails. Full lifecycle
                  typestate (Initiated→Approved→Captured→Settled→Refunded).
                  Per-provider sandbox+production base URLs, regions (NA/EU/OC
                  for Klarna; US/AuNz/Gb/Ca/Eu for Afterpay). HMAC-SHA256
                  webhook verification with constant-time compare. 61 tests.
  op-batch/       NACHA ACH (94-char records, PPD/CCD/WEB/TEL/CTX, R01-R99
                  return codes, Same-Day ACH cutoffs); SEPA pain.001.001.09
                  (CT) + pain.008.001.08 (DD) with SCT-Inst flagging; Fedwire
                  MT103/MT202/CHIPS + pacs.008.001.12 / pacs.009.001.10 +
                  UETR; Bacs Standard 18. Per-rail cutoff scheduler. Exception
                  taxonomy unified across rails. 51 tests.
  op-screening/   OFAC SDN + EU consolidated + UN consolidated + HMT UK
                  consolidated + Australia DFAT + Canada SEMA + Japan MOF.
                  Levenshtein + Jaro-Winkler + Soundex + Metaphone + token
                  Jaccard scoring. Unicode NFKD normalisation + Cyrillic /
                  Arabic transliteration. Ed25519-signed BLAKE3-chained
                  audit log. BSA helpers: CTR + SAR pattern detection
                  (structuring, round-dollar, rapid-in-out). 43 tests.

smart-byte/smart-byte-rs/ (+3 crates)
  smart-byte-bbs/      BBS+ signatures (IETF draft-irtf-cfrg-bbs-signatures-08).
                       BLS12-381 keys, signatures, disclosure proofs with
                       cryptographic unlinkability. bbs-2023 Data Integrity
                       cryptosuite. AnonCreds-shaped link secrets +
                       predicate proofs. SecretKey zeroize-on-drop. 49 tests.
  smart-byte-didcomm/  DIDComm v2 messaging per DIF spec. Pack-encrypted
                       (ECDH-1PU + ECDH-ES via X25519), pack-signed (JWS),
                       pack-plaintext. Aries protocols: issue-credential v3,
                       present-proof v3, basic-message, trust-ping, discover-
                       features, out-of-band, coordinate-mediation, message-
                       pickup. Mediator role with pluggable storage. 23 tests.
  smart-byte-mdl/      ISO/IEC 18013-5 mobile driver's licence + 18013-7
                       online presentment. mDoc + MSO with salted-hash
                       selective disclosure (per item; SHA-256 digest tree).
                       org.iso.18013.5.1 namespace + AAMVA add-on. ES256
                       device-auth + issuer-auth. QR-code device-engagement
                       scaffolding. 28 tests.

eoc/eoc-rs/ (+3 crates)
  eoc-local/      Local-inference backends behind one NeuralBackend:
                  llama.cpp (GGUF, Q4/Q5/Q6/Q8/F16/F32 quantisation),
                  MLX (Apple Silicon, feature-gated), MLC-LLM (TVM, feature-
                  gated marker), ONNX Runtime. GGUF file-format reader.
                  HuggingFace tokenizers. Greedy / top-k / top-p / temperature /
                  Mirostat samplers. Model registry scanning ~/.eoc/models/.
                  Joule attribution via eoc-meter. 39 tests.
  eoc-rerank/     BM25 sparse + HNSW dense + RRF + min-max hybrid fusion.
                  Cohere v3.5 + Voyage v2 + bge-reranker v2-m3 + ms-marco
                  MiniLM + ColBERT v2 rerankers. Two-stage pipeline:
                  retrieve top-K hybrid → cross-encoder rerank → top-N.
                  KV-stage recovery shim into the cascade. 31 tests.
  eoc-eval/       15 canonical eval harnesses: MMLU, MMLU-Pro, GPQA,
                  HumanEval (pass@1 with python3 sandbox), BBH, IFEval (25
                  verifiable constraints), AlpacaEval, AGIEval, HellaSwag,
                  ARC (Easy + Challenge), TruthfulQA (MC1+MC2), BoolQ,
                  GSM8K, MATH (boxed-answer equivalence), Winogrande. Real
                  questions in BuiltinSamples. EvalRunner emits joules-per-
                  correct alongside accuracy. 49 tests.

Quality:
- cargo check across all three workspaces: clean
- cargo clippy --all-targets -- -D warnings on every new crate: clean
- 374 new tests, all passing
- #![forbid(unsafe_code)] across every new crate
- No unwrap/expect outside #[cfg(test)]

Rust 1.95.0 edition 2024 (inherited via root rust-toolchain.toml).
2026-05-24 01:09:35 -04:00

193 lines
6.7 KiB
Rust

//! Affirm driver round-trip: authorize → capture → refund against a
//! wiremock-stubbed server.
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use op_bnpl::{
AffirmAcquirer, BillingInfo, BnplAcquirer, BnplIntent, ConsumerInfo, IdempotencyKey,
LineItem, RedirectUrls, ShippingInfo,
};
use op_core::{Currency, Money};
use reqwest::Client;
use serde_json::json;
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, Request, ResponseTemplate};
fn sample_intent() -> BnplIntent {
BnplIntent {
amount: Money::from_minor(10_000, Currency::USD),
currency: Currency::USD,
line_items: vec![LineItem {
name: "Thing".into(),
sku: Some("T-1".into()),
quantity: 1,
unit_price: Money::from_minor(10_000, Currency::USD),
total_amount: Money::from_minor(10_000, Currency::USD),
}],
shipping: ShippingInfo {
name: "Alice".into(),
line1: "1 Market".into(),
line2: None,
city: "SF".into(),
region: "CA".into(),
postal_code: "94105".into(),
country: "US".into(),
},
billing: BillingInfo {
name: "Alice".into(),
line1: "1 Market".into(),
line2: None,
city: "SF".into(),
region: "CA".into(),
postal_code: "94105".into(),
country: "US".into(),
},
consumer: ConsumerInfo {
email: "[email protected]".into(),
phone: None,
given_name: None,
family_name: None,
date_of_birth: None,
},
idempotency_key: IdempotencyKey::from("idem-affirm-1"),
redirect_urls: RedirectUrls {
success: "https://m/ok".into(),
cancel: "https://m/cancel".into(),
failure: None,
},
metadata: BTreeMap::new(),
}
}
#[tokio::test]
async fn affirm_full_roundtrip() {
let server = MockServer::start().await;
// POST /api/v2/charges → returns a charge.
Mock::given(method("POST"))
.and(path("/api/v2/charges"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"id": "CHG_TEST_1",
"amount": 10_000,
"status": "authorized"
})))
.expect(1)
.mount(&server)
.await;
// POST /api/v2/charges/{id}/capture → returns event.
Mock::given(method("POST"))
.and(path("/api/v2/charges/CHG_TEST_1/capture"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"id": "EVT_CAP_1",
"amount": 10_000,
"transaction_id": "TXN_BANK_1",
"type": "capture"
})))
.expect(1)
.mount(&server)
.await;
// POST /api/v2/charges/{id}/refund → returns event.
Mock::given(method("POST"))
.and(path("/api/v2/charges/CHG_TEST_1/refund"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"id": "EVT_REF_1",
"amount": 4_000,
"type": "refund"
})))
.expect(1)
.mount(&server)
.await;
let acquirer = AffirmAcquirer::new(Client::new(), "pub", "priv", server.uri());
let intent = sample_intent();
let session = acquirer.initiate(&intent).await.unwrap();
let auth = acquirer.authorize(&session, "checkout_token_abc").await.unwrap();
assert_eq!(auth.provider_ref, "CHG_TEST_1");
assert_eq!(auth.authorized_amount.minor_units, 10_000);
let captured = acquirer.capture(&auth, None).await.unwrap();
assert_eq!(captured.amount.minor_units, 10_000);
assert_eq!(captured.settlement_ref.as_deref(), Some("TXN_BANK_1"));
let refund = acquirer
.refund(&captured, Money::from_minor(4_000, Currency::USD))
.await
.unwrap();
assert_eq!(refund.amount.minor_units, 4_000);
}
#[tokio::test]
async fn affirm_rejected_4xx_maps_to_provider_rejected() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/api/v2/charges"))
.respond_with(ResponseTemplate::new(400).set_body_json(json!({
"code": "invalid-token",
"message": "checkout token expired"
})))
.mount(&server)
.await;
let acquirer = AffirmAcquirer::new(Client::new(), "pub", "priv", server.uri());
let intent = sample_intent();
let session = acquirer.initiate(&intent).await.unwrap();
let err = acquirer.authorize(&session, "stale").await.unwrap_err();
match err {
op_bnpl::Error::ProviderRejected { status, code, .. } => {
assert_eq!(status, 400);
assert_eq!(code, "invalid-token");
}
other => panic!("expected ProviderRejected, got {other:?}"),
}
}
/// Idempotency at the acquirer level: replaying the same intent through
/// `initiate` with the same key must not produce a network call (initiate
/// is local-only for Affirm). And the synthetic provider_ref must match.
#[tokio::test]
async fn affirm_initiate_is_local_and_idempotent_on_key() {
let server = MockServer::start().await;
// No mocks installed — if any HTTP request fires, it 404s and the
// test panics via the assertion below.
let acquirer = AffirmAcquirer::new(Client::new(), "pub", "priv", server.uri());
let intent = sample_intent();
let s1 = acquirer.initiate(&intent).await.unwrap();
let s2 = acquirer.initiate(&intent).await.unwrap();
assert_eq!(s1.provider_ref, s2.provider_ref);
assert_eq!(s1.provider_ref, "idem-affirm-1");
}
/// When the authorize endpoint is hit twice with the same checkout_token,
/// the mock server only fires once for the first request — we verify the
/// acquirer doesn't accidentally re-send.
#[tokio::test]
async fn affirm_authorize_single_call_per_logical_request() {
let server = MockServer::start().await;
let counter: Arc<AtomicUsize> = Arc::new(AtomicUsize::new(0));
let counter_clone = counter.clone();
Mock::given(method("POST"))
.and(path("/api/v2/charges"))
.respond_with(move |_: &Request| {
counter_clone.fetch_add(1, Ordering::SeqCst);
ResponseTemplate::new(200).set_body_json(json!({
"id": "CHG_X",
"amount": 10_000,
"status": "authorized"
}))
})
.mount(&server)
.await;
let acquirer = AffirmAcquirer::new(Client::new(), "pub", "priv", server.uri());
let intent = sample_intent();
let session = acquirer.initiate(&intent).await.unwrap();
let _ = acquirer.authorize(&session, "tok").await.unwrap();
assert_eq!(counter.load(Ordering::SeqCst), 1);
}