Skip to content

Commit

Permalink
Update tests
Browse files Browse the repository at this point in the history
  • Loading branch information
mzeitlin11 committed Apr 7, 2024
1 parent 1dbf29f commit 7f9d426
Show file tree
Hide file tree
Showing 10 changed files with 45 additions and 39 deletions.
10 changes: 6 additions & 4 deletions async-stripe/src/client/base/async_std.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::pin::Pin;

use async_std::task::sleep;
use http_types::{Request, StatusCode};
use stripe_types::StripeDeserialize;
use miniserde::json::from_str;

use crate::client::request_strategy::{Outcome, RequestStrategy};
use crate::error::StripeError;
Expand All @@ -26,7 +26,7 @@ impl AsyncStdClient {
Self { client: surf::Client::new() }
}

pub fn execute<T: StripeDeserialize + Send + 'static>(
pub fn execute<T: miniserde::Deserialize + Send + 'static>(
&self,
request: Request,
strategy: &RequestStrategy,
Expand All @@ -40,7 +40,9 @@ impl AsyncStdClient {
let bytes = send_inner(&client, request, &strategy).await?;
let str = std::str::from_utf8(bytes.as_ref())
.map_err(|_| StripeError::JSONDeserialize("Response was not valid UTF-8".into()))?;
T::deserialize(str).map_err(StripeError::JSONDeserialize)
from_str(str).map_err(|_| {
StripeError::JSONDeserialize("error deserializing request data".into())

Check warning on line 44 in async-stripe/src/client/base/async_std.rs

View check run for this annotation

Codecov / codecov/patch

async-stripe/src/client/base/async_std.rs#L44

Added line #L44 was not covered by tests
})
})
}
}
Expand Down Expand Up @@ -104,7 +106,7 @@ async fn send_inner(
let str = std::str::from_utf8(bytes.as_ref()).map_err(|_| {
StripeError::JSONDeserialize("Response was not valid UTF-8".into())

Check warning on line 107 in async-stripe/src/client/base/async_std.rs

View check run for this annotation

Codecov / codecov/patch

async-stripe/src/client/base/async_std.rs#L107

Added line #L107 was not covered by tests
})?;
last_error = stripe_shared::Error::deserialize(str)
last_error = from_str(str)
.map(|e: stripe_shared::Error| StripeError::Stripe(*e.error, status.into()))
.unwrap_or_else(|_| {
StripeError::JSONDeserialize(
Expand Down
1 change: 0 additions & 1 deletion async-stripe/src/client/base/tokio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,6 @@ mod tests {
mock.assert_hits_async(1).await;

match res {
Err(StripeError::JSONSerialize(_)) => {}
Err(StripeError::JSONDeserialize(_)) => {}
_ => panic!("Expected stripe error {:?}", res),
}
Expand Down
3 changes: 1 addition & 2 deletions async-stripe/src/client/base/tokio_blocking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
use std::{sync::Arc, time::Duration};

use http_types::Request;
use stripe_types::StripeDeserialize;

use crate::client::base::tokio::TokioClient;
use crate::client::request_strategy::RequestStrategy;
Expand Down Expand Up @@ -39,7 +38,7 @@ impl TokioBlockingClient {
TokioBlockingClient { inner, runtime: Arc::new(runtime) }
}

pub fn execute<T: StripeDeserialize + Send + 'static>(
pub fn execute<T: miniserde::Deserialize + Send + 'static>(
&self,
request: Request,
strategy: &RequestStrategy,
Expand Down
6 changes: 3 additions & 3 deletions stripe_types/src/currency.rs
Original file line number Diff line number Diff line change
Expand Up @@ -489,8 +489,8 @@ mod tests {

#[test]
fn deserialize_currency() {
assert_eq!(serde_json::from_str::<Currency>("\"aed\"").unwrap(), Currency::AED);
assert_eq!(serde_json::from_str::<Currency>("\"usd\"").unwrap(), Currency::USD);
assert_eq!(serde_json::from_str::<Currency>("\"zmw\"").unwrap(), Currency::ZMW);
assert_eq!(miniserde::json::from_str::<Currency>("\"aed\"").unwrap(), Currency::AED);
assert_eq!(miniserde::json::from_str::<Currency>("\"usd\"").unwrap(), Currency::USD);
assert_eq!(miniserde::json::from_str::<Currency>("\"zmw\"").unwrap(), Currency::ZMW);
}
}
11 changes: 5 additions & 6 deletions stripe_types/src/ids.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,6 @@ impl std::error::Error for ParseIdError {
mod tests {
use std::str::FromStr;

use serde::de::DeserializeOwned;
use serde::Serialize;

def_id!(ChargeId, "ch_" | "py_");
Expand All @@ -281,18 +280,18 @@ mod tests {

fn assert_ser_de_roundtrip<T>(id: &str)
where
T: DeserializeOwned + Serialize + FromStr + std::fmt::Display + std::fmt::Debug,
T: miniserde::Deserialize + Serialize + FromStr + std::fmt::Display + std::fmt::Debug,
<T as FromStr>::Err: std::fmt::Debug,
{
let parsed_id = T::from_str(id).expect("Could not parse id");
let ser = serde_json::to_string(&parsed_id).expect("Could not serialize id");
let deser: T = serde_json::from_str(&ser).expect("Could not deserialize id");
let ser = serde_json::to_string(&parsed_id).expect("Could not serialize");
let deser: T = miniserde::json::from_str(&ser).expect("Could not deserialize id");
assert_eq!(deser.to_string(), id.to_string());
}

fn assert_deser_err<T: DeserializeOwned + std::fmt::Debug>(id: &str) {
fn assert_deser_err<T: miniserde::Deserialize + std::fmt::Debug>(id: &str) {
let json_str = format!(r#""{}""#, id);
let deser: Result<T, _> = serde_json::from_str(&json_str);
let deser: Result<T, _> = miniserde::json::from_str(&json_str);
assert!(deser.is_err(), "Expected error, got {:?}", deser);
}

Expand Down
3 changes: 3 additions & 0 deletions stripe_webhook/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,8 @@ stripe_core = { path = "../generated/stripe_core", optional = true }
stripe_checkout = { path = "../generated/stripe_checkout", optional = true }
stripe_billing = { path = "../generated/stripe_billing", optional = true }

[dev-dependencies]
serde_json.workspace = true

[package.metadata.docs.rs]
features = ["stripe_core", "stripe_checkout", "stripe_billing"]
2 changes: 1 addition & 1 deletion stripe_webhook/src/webhook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ mod tests {
"data": {
"object": data,
},
"type": Value::String(event_type.to_string())
"type": event_type.to_string()
})
}

Expand Down
1 change: 1 addition & 0 deletions tests/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ publish = false
serde.workspace = true
miniserde.workspace = true
serde_qs = "0.12.0"
serde_json.workspace = true
chrono = "0.4.26"
httpmock = "0.6.7"
wiremock = "0.5.22"
Expand Down
42 changes: 22 additions & 20 deletions tests/tests/it/deser.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
use miniserde::json::from_str;
use serde_json::{json, Value};
use stripe_connect::Account;
use stripe_core::customer::RetrieveCustomerReturned;
use stripe_core::{
Charge, ChargeStatus, Customer, CustomerTaxExempt, File, FileLink, FilePurpose, PaymentSource,
};
use stripe_types::{Currency, StripeDeserialize, Timestamp};
use stripe_types::{Currency, Timestamp};

fn mock_customer_with_card() -> Value {
json!({
"id": "cus_1234",
"object": "customer",
"account_balance": 0,
"balance": 0,
"created": 1542631579,
"currency": null,
"default_source": "card_ABCD",
Expand Down Expand Up @@ -70,8 +71,9 @@ fn mock_customer_with_card() -> Value {
#[test]
fn deserialize_customer_with_card() {
let example = mock_customer_with_card().to_string();
let result = Customer::deserialize(&example);
assert!(result.is_ok(), "expected ok; was {:?}", result);
let result: Customer = from_str(&example).expect("deserialization failed");
assert_eq!(result.balance, Some(0));
assert!(!result.livemode);
}

#[test]
Expand Down Expand Up @@ -153,8 +155,8 @@ fn deserialize_customer_with_source() {
})
.to_string();

let result = Customer::deserialize(&example);
assert!(result.is_ok(), "expected ok; was {:?}", result);
let result: Customer = from_str(&example).unwrap();
assert_eq!(result.description, None);
}

#[test]
Expand Down Expand Up @@ -207,8 +209,8 @@ fn deserialize_checkout_event() {
}
})
.to_string();
let result = Event::deserialize(&example);
assert!(result.is_ok(), "expected ok; was {:?}", result);
let result: Event = from_str(&example).unwrap();
assert_eq!(result.pending_webhooks, 1);
}

#[test]
Expand All @@ -232,7 +234,7 @@ fn deserialize_charge_with_no_refunds() {
"refunded": false,
})
.to_string();
let charge = Charge::deserialize(&example).unwrap();
let charge: Charge = from_str(&example).unwrap();
assert_eq!(charge.id.as_str(), "ch_123");
assert_eq!(charge.currency, Currency::CAD);
assert_eq!(charge.status, ChargeStatus::Pending);
Expand All @@ -252,7 +254,7 @@ fn mock_file() -> Value {
#[test]
fn deserialize_file() {
let file = mock_file();
let file = File::deserialize(&file.to_string()).unwrap();
let file: File = from_str(&file.to_string()).unwrap();
assert_eq!(file.purpose, FilePurpose::AccountRequirement);
assert_eq!(file.created, FILE_CREATED);
}
Expand All @@ -268,12 +270,12 @@ fn deserialize_id() {
id: FileId,
}
let data = json!({"id": "file_123"});
let id: Id = miniserde::json::from_str(&data.to_string()).unwrap();
let id: Id = from_str(&data.to_string()).unwrap();
assert_eq!(id.id, FileId::from_str("file_123").unwrap());
}

#[test]
fn deserialize_account() {
fn deserialize_account_with_external_accounts() {
let acct_url = "/v1/accounts/acct_123/external_accounts";
let account = json!({
"id": "acct_123",
Expand All @@ -284,7 +286,7 @@ fn deserialize_account() {
"url": acct_url
},
});
let result = Account::deserialize(&account.to_string()).unwrap();
let result: Account = from_str(&account.to_string()).unwrap();
assert_eq!(result.id.as_str(), "acct_123");

let external_accts = result.external_accounts.as_ref().unwrap();
Expand Down Expand Up @@ -315,7 +317,7 @@ fn assert_payment_source_matches(result: &PaymentSource) {
#[test]
fn deserialize_polymorphic() {
let payment_source = mock_payment_source();
let result = PaymentSource::deserialize(&payment_source.to_string()).unwrap();
let result = from_str(&payment_source.to_string()).unwrap();
assert_payment_source_matches(&result);
}

Expand All @@ -333,7 +335,7 @@ fn deserialize_expandable() {
let mut file_link = file_link_base.clone();
file_link.as_object_mut().unwrap().insert("file".into(), Value::String("file_123".into()));

let result = FileLink::deserialize(&file_link.to_string()).unwrap();
let result: FileLink = from_str(&file_link.to_string()).unwrap();
assert!(result.metadata.is_empty());
assert!(!result.livemode);
assert!(!result.expired);
Expand All @@ -345,7 +347,7 @@ fn deserialize_expandable() {
let mut file_link = file_link_base.clone();
file_link.as_object_mut().unwrap().insert("file".into(), mock_file());

let result = FileLink::deserialize(&file_link.to_string()).unwrap();
let result: FileLink = from_str(&file_link.to_string()).unwrap();
let file = result.file.as_object().unwrap();

assert_eq!(file.created, FILE_CREATED);
Expand All @@ -366,7 +368,7 @@ fn deserialize_expandable_polymorphic() {
let mut cust = base_cust.clone();
cust.as_object_mut().unwrap().insert("default_source".into(), Value::String("ba_123".into()));

let result = Customer::deserialize(&cust.to_string()).unwrap();
let result: Customer = from_str(&cust.to_string()).unwrap();
assert_eq!(result.created, 1704511150);
assert_eq!(result.currency, Some(Currency::USD));
assert_eq!(result.tax_exempt, Some(CustomerTaxExempt::Exempt));
Expand All @@ -376,7 +378,7 @@ fn deserialize_expandable_polymorphic() {
let mut cust = base_cust.clone();
cust.as_object_mut().unwrap().insert("default_source".into(), mock_payment_source());

let result = Customer::deserialize(&cust.to_string()).unwrap();
let result: Customer = from_str(&cust.to_string()).unwrap();
let payment_source = result.default_source.as_ref().unwrap().as_object().unwrap();
assert_payment_source_matches(&payment_source);
}
Expand All @@ -387,14 +389,14 @@ fn deserialize_customer_deleted_or_not() {
"deleted": true,
"id": "cus_123"
});
let result = RetrieveCustomerReturned::deserialize(&deleted_cust.to_string()).unwrap();
let result: RetrieveCustomerReturned = from_str(&deleted_cust.to_string()).unwrap();
let RetrieveCustomerReturned::DeletedCustomer(deleted) = result else {
panic!("expected deleted variant");
};
assert_eq!(deleted.id.as_str(), "cus_123");

let cust = mock_customer_with_card().to_string();
let result = RetrieveCustomerReturned::deserialize(&cust).unwrap();
let result: RetrieveCustomerReturned = from_str(&cust).unwrap();
let RetrieveCustomerReturned::Customer(cust) = result else {
panic!("did not expected deleted variant")
};
Expand Down
5 changes: 3 additions & 2 deletions tests/tests/it/price.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use miniserde::json::from_str;
use stripe_product::{CurrencyOptionTaxBehavior, Price};
use stripe_types::{Currency, StripeDeserialize};
use stripe_types::Currency;

// Using fixture for this test because the stripe-mock server does not (currently [2023-05-25]) support the `currency_options` field.
// See: https://github.com/stripe/stripe-mock/issues/420
Expand Down Expand Up @@ -49,7 +50,7 @@ fn deserialize_currency_options() {
}
"#;

let price = Price::deserialize(fixture).unwrap();
let price: Price = from_str(fixture).unwrap();
assert!(&price.currency_options.is_some());

let currency_options = price.currency_options.unwrap();
Expand Down

0 comments on commit 7f9d426

Please sign in to comment.