-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathClientTest.cs
More file actions
325 lines (272 loc) · 11.9 KB
/
ClientTest.cs
File metadata and controls
325 lines (272 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using EasyPost._base;
using EasyPost.Exceptions.API;
using EasyPost.Tests._Utilities;
using EasyPost.Tests._Utilities.Attributes;
using Newtonsoft.Json.Linq;
using Xunit;
namespace EasyPost.Tests
{
public class ClientTests : UnitTest
{
public ClientTests() : base("client")
{
}
#region Tests
[Fact]
[Testing.Function]
public void TestClient()
{
const string apiBase = "https://www.example.com";
TimeSpan timeout = TimeSpan.FromMilliseconds(5000);
HttpClient httpClient = new();
Client client = new(new ClientConfiguration(FakeApikey)
{
ApiBase = apiBase,
Timeout = timeout,
CustomHttpClient = httpClient,
});
Assert.Equal(FakeApikey, client.ApiKeyInUse);
Assert.Equal(apiBase, client.ApiBaseInUse);
Assert.Equal(timeout, client.Timeout);
Assert.Equal(httpClient, client.CustomHttpClient);
}
[Fact]
[Testing.Logic]
public void TestThreadSafety()
{
const string key1 = "key1";
const string key2 = "key2";
const string key3 = "key3";
Client client1 = new(new ClientConfiguration(key1));
Client client2 = new(new ClientConfiguration(key2));
Client client3 = new(new ClientConfiguration(key3));
Thread thread1 = new(() => Thread(client1, key1));
Thread thread2 = new(() => Thread(client2, key2));
Thread thread3 = new(() => Thread(client3, key3));
// Start all threads, purposely out of order
thread2.Start();
thread3.Start();
thread1.Start();
return;
static void Thread(EasyPostClient client, string keyToMatch) => Assert.Equal(keyToMatch, client.ApiKeyInUse);
}
#endregion
private const string FakeApikey = "fake_api_key";
[Fact]
public void TestBaseUrlOverride()
{
Client normalClient = new(new ClientConfiguration(FakeApikey));
Client overrideClient = new(new ClientConfiguration(FakeApikey)
{
ApiBase = "https://www.example.com",
});
Assert.Equal("https://api.easypost.com", normalClient.ApiBaseInUse);
Assert.Equal("https://www.example.com", overrideClient.ApiBaseInUse);
}
[Fact]
public void TestTimeoutOverride()
{
Client normalClient = new(new ClientConfiguration(FakeApikey));
Client overrideClient = new(new ClientConfiguration(FakeApikey)
{
Timeout = TimeSpan.FromMilliseconds(1),
});
Assert.Equal(TimeSpan.FromSeconds(60), normalClient.Timeout);
Assert.Equal(TimeSpan.FromMilliseconds(1), overrideClient.Timeout);
}
[Fact]
public void TestHttpClientOverride()
{
Client normalClient = new(new ClientConfiguration(FakeApikey));
HttpClient httpClient = new();
Client overrideClient = new(new ClientConfiguration(FakeApikey)
{
CustomHttpClient = httpClient,
});
Assert.NotEqual(httpClient, normalClient.CustomHttpClient);
Assert.Equal(httpClient, overrideClient.CustomHttpClient);
}
[Fact]
public async void TestHttpClientCustomProxy()
{
const string proxyAddress = "localhost:8888";
// Define a custom proxy in a custom HttpClientHandler in a custom HttpClient
HttpClientHandler handler = new()
{
UseProxy = true,
Proxy = new WebProxy($"http://{proxyAddress}"),
};
HttpClient httpClient = new(handler: handler);
Client client = new(new ClientConfiguration(FakeApikey)
{
CustomHttpClient = httpClient,
});
Assert.Equal(httpClient, client.CustomHttpClient);
// Assert that the proxy is set in the HttpClient by attempting to make a request (should fail due to invalid proxy address)
try
{
await client.Address.Create(new Parameters.Address.Create());
Assert.Fail("Expected HttpRequestException");
}
catch (HttpRequestException e)
{
// GitHub runner will reject the connection attempt, this is considered a pass
if (e.Message.Contains("No connection could be made because the target machine actively refused it"))
{
Assert.True(true);
}
else // Evaluate the error message
{
#if NET5_0_OR_GREATER
Assert.Equal($"Connection refused ({proxyAddress})", e.Message);
#else
// Message is inconsistent in .NET Framework, so just assert that the exception was thrown
Assert.True(true);
#endif
}
}
}
[Fact]
public async Task TestRequestHooks()
{
int preRequestCallbackCallCount = 0;
int postRequestCallbackCallCount = 0;
var requestGuid = Guid.Empty;
Hooks hooks = new()
{
OnRequestExecuting = (_, args) =>
{
// Modifying the HttpRequestMessage in this action does not impact the HttpRequestMessage being executed (passed by value, not reference)
preRequestCallbackCallCount++;
Assert.True(args.RequestTimestamp > 0);
requestGuid = args.Id;
},
OnRequestResponseReceived = (_, args) =>
{
postRequestCallbackCallCount++;
Assert.True(args.RequestTimestamp > 0);
Assert.True(args.ResponseTimestamp > 0);
Assert.True(args.ResponseTimestamp >= args.RequestTimestamp);
Assert.Equal(requestGuid, args.Id);
},
};
UseVCRWithCustomClient("request_hooks", (_, httpClient) =>
new Client(new ClientConfiguration(FakeApikey)
{
CustomHttpClient = httpClient,
Hooks = hooks,
})
);
// Make a request, doesn't matter what it is (catch the exception due to invalid API key)
await Assert.ThrowsAsync<UnauthorizedError>(async () => await Client.Address.Create(new Parameters.Address.Create()));
// Assert that the pre-request callback was called
Assert.Equal(1, preRequestCallbackCallCount);
// Assert that the post-request callback was called
Assert.Equal(1, postRequestCallbackCallCount);
}
[Fact]
public async Task TestMultipleRequestHookCallbacks()
{
bool preRequestCallback1Called = false;
bool preRequestCallback2Called = false;
bool postRequestCallback1Called = false;
bool postRequestCallback2Called = false;
Hooks hooks = new();
hooks.OnRequestExecuting += (_, _) => preRequestCallback1Called = true;
hooks.OnRequestExecuting += (_, _) => preRequestCallback2Called = true;
hooks.OnRequestResponseReceived += (_, _) => postRequestCallback1Called = true;
hooks.OnRequestResponseReceived += (_, _) => postRequestCallback2Called = true;
UseVCRWithCustomClient("multiple_request_hooks", (_, httpClient) =>
new Client(new ClientConfiguration(FakeApikey)
{
CustomHttpClient = httpClient,
Hooks = hooks,
})
);
// Make a request, doesn't matter what it is (catch the exception due to invalid API key)
await Assert.ThrowsAsync<UnauthorizedError>(async () => await Client.Address.Create(new Parameters.Address.Create()));
// Assert that the pre-request callbacks were called
Assert.True(preRequestCallback1Called);
Assert.True(preRequestCallback2Called);
// Assert that the post-request callbacks were called
Assert.True(postRequestCallback1Called);
Assert.True(postRequestCallback2Called);
}
[Fact]
public async Task TestRequestHooksUnsubscribing()
{
int preRequestCallbackCallCount = 0;
void PreRequestCallback(object? sender, OnRequestExecutingEventArgs args)
{
preRequestCallbackCallCount++;
}
Hooks hooks = new();
UseVCRWithCustomClient("request_hooks_unsubscribing", (apiKey, httpClient) =>
new Client(new ClientConfiguration(FakeApikey)
{
CustomHttpClient = httpClient,
Hooks = hooks,
})
);
// Subscribe to the pre-request callback
Client.Hooks.OnRequestExecuting += PreRequestCallback;
// Make a request, doesn't matter what it is (catch the exception due to invalid API key)
await Assert.ThrowsAsync<UnauthorizedError>(async () => await Client.Address.Create(new Parameters.Address.Create()));
// Assert that the pre-request callback was called
Assert.Equal(1, preRequestCallbackCallCount);
// Unsubscribe from the pre-request callback
Client.Hooks.OnRequestExecuting -= PreRequestCallback;
// Make a request, doesn't matter what it is (catch the exception due to invalid API key)
await Assert.ThrowsAsync<UnauthorizedError>(async () => await Client.Address.Create(new Parameters.Address.Create()));
// Assert that the pre-request callback was not called again
Assert.Equal(1, preRequestCallbackCallCount);
}
[Fact]
public async Task TestCancellationToken()
{
CancellationTokenSource cancelTokenSource = new();
CancellationToken token = cancelTokenSource.Token;
Hooks hooks = new()
{
OnRequestExecuting = (_, _) =>
{
// Use the cancellation token to cancel the request
cancelTokenSource.Cancel();
},
};
UseVCRWithCustomClient("cancellation_token", (_, httpClient) =>
new Client(new ClientConfiguration(FakeApikey)
{
CustomHttpClient = httpClient,
Hooks = hooks,
})
);
// Make a request, doesn't matter what it is
// Should throw a TimeoutError because the request was cancelled
// If it throws a UnauthorizedError, then the cancellation token was not used (request went through and failed due to invalid API key)
// this will not record a cassette because the request should be cancelled before it is sent
await Assert.ThrowsAsync<TimeoutError>(async () => await Client.Address.Create(new Parameters.Address.Create(), token));
}
[Fact]
[Testing.Function]
public async Task TestClientMakeApiCall()
{
UseVCR("make_api_call");
Dictionary<string, object> parameters = new()
{
{ "page_size", 1 },
};
Dictionary<string, object> response = await Client.MakeApiCallAsync(Http.Method.Get, "/addresses", parameters);
JArray addresses = response["addresses"] as JArray;
Assert.Single(addresses);
JObject firstAddress = addresses[0] as JObject;
Assert.Equal("Address", firstAddress["object"].ToString());
}
}
}