forked from linguanostra/GoogleMapsAPI.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClientAPITests.cs
More file actions
439 lines (329 loc) · 12.7 KB
/
Copy pathClientAPITests.cs
File metadata and controls
439 lines (329 loc) · 12.7 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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using FluentAssertions;
using GoogleMapsAPI.NET.API.Client;
using GoogleMapsAPI.NET.API.Common.Components.Locations;
using GoogleMapsAPI.NET.Exceptions;
using GoogleMapsAPI.NET.Requests;
using GoogleMapsAPI.NET.Tests.API.Common;
using GoogleMapsAPI.NET.Tests.API.Extensions;
using GoogleMapsAPI.NET.Tests.API.Utils.MockConfig;
using GoogleMapsAPI.NET.Web.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Rhino.Mocks;
using Rhino.Mocks.Interfaces;
namespace GoogleMapsAPI.NET.Tests.API.Client
{
/// <summary>
/// Client API tests
/// </summary>
[TestClass]
public class ClientAPITests : APITests
{
#region Test methods
/// <summary>
/// Test no API key
/// </summary>
[TestMethod]
[ExpectedException(typeof(APICredentialsNotSpecifiedException))]
public void TestNoAPIKey()
{
// Get API client
using (var client = GetAPIClient(null))
{
// Get directions
client.Directions.GetDirections(
new AddressLocation("Sydney"),
new AddressLocation("Melbourne"));
}
}
/// <summary>
/// Test no enterprise credentials
/// </summary>
[TestMethod]
[ExpectedException(typeof(APICredentialsNotSpecifiedException))]
public void TestNoEnterpriseCredentials()
{
// Get API client
using (var client = GetAPIClient(null))
{
// Get directions
client.Directions.GetDirections(
new AddressLocation("Sydney"),
new AddressLocation("Melbourne"));
}
}
/// <summary>
/// Test invalid API key
/// </summary>
[TestMethod]
[ExpectedException(typeof(APIKeyInvalidException))]
public void TestInvalidAPIKey()
{
// Get API client
using (var client = GetAPIClient("Invalid key"))
{
// Get directions
client.Directions.GetDirections(
new AddressLocation("Sydney"),
new AddressLocation("Melbourne"));
}
}
/// <summary>
/// Test Url encode
/// See: https://github.com/googlemaps/google-maps-services-python/issues/72
/// </summary>
[TestMethod]
public void TestUrlEncode()
{
// Get API client
using (var client = GetAPIClient())
{
// Encode params
var encodedParams = client.UrlEncodeParams(new QueryParams {["address"] = "=Sydney ~" });
// Assertions
encodedParams.Should().Be("address=%3DSydney+~");
}
}
/// <summary>
/// Test queries per second
/// </summary>
[TestMethod]
public void TestQueriesPerSecond()
{
// This test assumes that the time to run a mocked query is
// relatively small, eg a few milliseconds. We define a rate of
// 3 queries per second, and run double that, which should take at
// least 1 second but no more than 2.
// Init
var queriesPerSecond = 3;
var queryRange = queriesPerSecond*2;
// Set API client config
var clientConfig = new MapsAPIClientConfig
{
QueriesPerSecond = queriesPerSecond
};
// Use mocked API client
using (var client = GetMockedAPIClient(clientConfig: clientConfig))
{
// Arrange mocks for empty result
client.ArrangeWebResponseValidResultsMocks();
// Make client calls
var startTime = DateTime.Now;
for (var i = 0; i < queryRange; i++)
{
client.Geocoding.Geocode("Sesame St.");
}
// Get elapsed time
var elapsedTime = DateTime.Now - startTime;
// Assertions
elapsedTime.Seconds.Should().BeInRange(1, 2);
}
}
/// <summary>
/// Test key sent
/// </summary>
[TestMethod]
public void TestKeySent()
{
// Use mocked API client
using (var client = GetMockedAPIClient())
{
// Arrange mocks for empty result
var webMocks = client.ArrangeWebResponseValidResultsMocks();
// Make client call
client.Geocoding.Geocode("Sesame St.");
// Assertions
webMocks.WebRequestUtil.AssertGetWasCalledOnceWithUrl(
"https://maps.googleapis.com/maps/api/geocode/json?" +
"address=Sesame+St.&key=" + client.APIKey, false);
}
}
/// <summary>
/// Test HMAC
/// </summary>
[TestMethod]
public void TestHMAC()
{
/*
From http://en.wikipedia.org/wiki/Hash-based_message_authentication_code
HMAC_SHA1("key", "The quick brown fox jumps over the lazy dog")
= 0xde7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9
*/
// Get API client
using (var client = GetAPIClient())
{
// Config
const string message = "The quick brown fox jumps over the lazy dog";
const string key = "a2V5"; // "key" -> base64
const string signature = "3nybhbi3iqa8ino29wqQcBydtNk=";
// Assertions
client.SignHMAC(key, message).Should().Be(signature);
}
}
/// <summary>
/// Test Url signed
/// </summary>
[TestMethod]
public void TestUrlSigned()
{
// Use mocked API client
using (var client = GetMockedAPIClient("foo", "a2V5"))
{
// Arrange mocks for empty result
var webMocks = client.ArrangeWebResponseValidResultsMocks();
// Make client call
client.Geocoding.Geocode("Sesame St.");
// Assertions
// Check ordering of parameters.
webMocks.WebRequestUtil.AssertWasCalled(utility =>
utility.Get(
Arg<string>.Matches(x => x.Contains("address=Sesame+St.&client=foo&signature")),
Arg<RequestConfig>.Is.Anything),
options => options.Repeat.Once());
// Check url
webMocks.WebRequestUtil.AssertGetWasCalledOnceWithUrl(
"https://maps.googleapis.com/maps/api/geocode/json?" +
"address=Sesame+St.&client=foo&" +
"signature=fxbWUIcNPZSekVOhp2ul9LW5TpY=", false);
}
}
/// <summary>
/// Test user agent sent
/// </summary>
[TestMethod]
public void TestUASent()
{
// Use mocked API client
using (var client = GetMockedAPIClient())
{
// Arrange mocks for empty result
var webMocks = client.ArrangeWebResponseValidResultsMocks();
// Add expectations
webMocks.Request.Expect(
x => x.UserAgent = Arg<string>.Matches(value => value.StartsWith("GoogleGeoApiClientPython")));
// Make client call
client.Geocoding.Geocode("Sesame St.");
// Assertions
webMocks.Request.VerifyAllExpectations();
}
}
/// <summary>
/// Test retry
/// </summary>
[TestMethod]
public void TestRetry()
{
// Use mocked API client
using (var client = GetMockedAPIClient())
{
// Arrange mocks for custom results
var webMocks = client.ArrangeWebResponseResultMocks(
new List<MockResultWebResponseConfig>
{
new MockResultWebResponseConfig("{\"status\":\"OVER_QUERY_LIMIT\"}"),
new MockValidResultsWebResponseConfig()
});
// Make client calls
client.Geocoding.Geocode("Sesame St.");
// Assertions
// Ensure expected requests were made
webMocks.WebRequestUtil.AssertWasCalled(
x => x.Get(Arg<string>.Is.Anything, Arg<RequestConfig>.Is.Anything),
options => options.Repeat.Twice());
// Get requests arguments
var queryUtilsArgs =
webMocks.WebRequestUtil.GetArgumentsForCallsMadeOn(
x => x.Get(Arg<string>.Is.Anything, Arg<RequestConfig>.Is.Anything));
// Ensure they are available
queryUtilsArgs.Should().NotBeNullOrEmpty();
// Ensure all calls with same url
var firstUrl = (string)queryUtilsArgs.First()[0];
queryUtilsArgs.All(x => (string) (x[0]) == firstUrl).Should().BeTrue();
}
}
/// <summary>
/// Test transport error
/// </summary>
[TestMethod]
[ExpectedException(typeof(HttpResponseException))]
public void TestTransportError()
{
// Use mocked API client
using (var client = GetMockedAPIClient())
{
// Arrange mocks for custom result
client.ArrangeWebResponseResultMocks(new MockNotFoundResultWebResponseConfig());
// Make client call
client.Geocoding.Geocode("Foo");
}
}
/// <summary>
/// Test host override
/// </summary>
[TestMethod]
public void TestHostOverride()
{
// Use mocked API client
using (var client = GetMockedAPIClient())
{
// Arrange mocks for custom result
var webMocks = client.ArrangeWebResponseValidResultsMocks();
// Set expectations
webMocks.WebRequestUtil.Expect(
x =>
x.Get(Arg<string>.Matches(value => value.StartsWith("https://foo.com")),
Arg<RequestConfig>.Is.Anything)).CallOriginalMethod(OriginalCallOptions.CreateExpectation);
// Make client call
client.Get("/bar", QueryParams.Empty(), baseUrl: "https://foo.com");
// Assertions
webMocks.WebRequestUtil.VerifyAllExpectations();
}
}
/// <summary>
/// Test custom extraction
/// </summary>
[TestMethod]
public void TestCustomExtract()
{
// Use mocked API client
using (var client = GetMockedAPIClient())
{
// Arrange mocks for custom result
client.ArrangeWebResponseResultMocks(new MockErrorResultWebResponseConfig());
// Extract body handler
var extractBodyFn = new Func<HttpWebResponse, dynamic>(response => response.GetResponseContent());
// Make client call
string result = client.Get("/bar", QueryParams.Empty(), extractBodyFn);
// Assertions
result.Should().Be("{\"error\":\"errormessage\"}");
}
}
/// <summary>
/// Test retry intermittent
/// </summary>
[TestMethod]
public void TestRetryIntermittent()
{
// Use mocked API client
using (var client = GetMockedAPIClient())
{
// Arrange mocks for custom results
var webMocks = client.ArrangeWebResponseResultMocks(
new List<MockResultWebResponseConfig>
{
new MockInternalServerErrorResultWebResponseConfig(),
new MockValidResultsWebResponseConfig()
});
// Make client calls
client.Geocoding.Geocode("Sesame St.");
// Assertions
// Ensure 2 requests were made
webMocks.Request.AssertWasCalled(x => x.GetResponse(), options => options.Repeat.Twice());
}
}
#endregion
}
}