Skip to content

Commit 99b9ce7

Browse files
authored
- Improve logic handling API key switch on exception (#362)
1 parent 76d547c commit 99b9ce7

File tree

2 files changed

+38
-5
lines changed

2 files changed

+38
-5
lines changed

EasyPost.Tests/ServicesTests/PartnerServiceTest.cs

+28
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,34 @@ public async Task TestAddCreditCardToUserStripeBadResponse()
234234
await Assert.ThrowsAsync<ExternalApiError>(async () => await Client.Partner.AddCreditCardToUser(ReferralUserKey, card.Number, card.ExpirationMonth, card.ExpirationYear, card.Cvc, PaymentMethod.Priority.Primary));
235235
}
236236

237+
[Fact]
238+
[Testing.Exception]
239+
public async Task TestAddCreditCardToUserEasyPostApiError()
240+
{
241+
UseMockClient(new List<TestUtils.MockRequest>
242+
{
243+
new(
244+
new TestUtils.MockRequestMatchRules(Method.Get, @"^v2\/partners\/stripe_public_key$"),
245+
new TestUtils.MockRequestResponseInfo(HttpStatusCode.OK, content: "{\"public_key\":\"pk_test_12345\"}")
246+
),
247+
new(
248+
new TestUtils.MockRequestMatchRules(Method.Post, @"^https://api.stripe.com/v1/tokens$"),
249+
new TestUtils.MockRequestResponseInfo(HttpStatusCode.OK, content: "{\"id\":\"tok_12345\"}")
250+
),
251+
new(
252+
new TestUtils.MockRequestMatchRules(Method.Post, @"^v2\/credit_cards$"),
253+
new TestUtils.MockRequestResponseInfo(HttpStatusCode.NotFound, content: "{}")
254+
)
255+
});
256+
257+
CreditCard card = new CreditCard(Fixtures.CreditCardDetails);
258+
259+
await Assert.ThrowsAsync<NotFoundError>(async () => await Client.Partner.AddCreditCardToUser(ReferralUserKey, card.Number, card.ExpirationMonth, card.ExpirationYear, card.Cvc, PaymentMethod.Priority.Primary));
260+
261+
// Assert that the original API key was restored to the client properly even after the failed request
262+
Assert.Equal(TestUtils.GetApiKey(TestUtils.ApiKey.Mock), Client.Configuration.ApiKey);
263+
}
264+
237265
[Fact]
238266
[CrudOperations.Update]
239267
[Testing.Function]

EasyPost/Services/PartnerService.cs

+10-5
Original file line numberDiff line numberDiff line change
@@ -123,11 +123,16 @@ private async Task<PaymentMethod> CreateEasypostCreditCard(string referralApiKey
123123
// Change API key temporarily to referral user's API key.
124124
Client.Configuration.ApiKey = referralApiKey;
125125

126-
// Make request
127-
PaymentMethod paymentMethod = await Client.Request<PaymentMethod>(Method.Post, "credit_cards", ApiVersion.Current, parameters);
128-
129-
// Restore old API key
130-
Client!.Configuration.ApiKey = oldApiKey;
126+
PaymentMethod paymentMethod;
127+
try
128+
{
129+
// Make request
130+
paymentMethod = await Client.Request<PaymentMethod>(Method.Post, "credit_cards", ApiVersion.Current, parameters);
131+
}
132+
finally
133+
{
134+
Client.Configuration.ApiKey = oldApiKey;
135+
}
131136

132137
return paymentMethod;
133138
}

0 commit comments

Comments
 (0)