/
HttpEndPointTests.cs
422 lines (335 loc) · 11 KB
/
HttpEndPointTests.cs
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
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using NUnit.Framework;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Threading.Tasks;
namespace HttpMock.Integration.Tests
{
[TestFixture]
public class HttpEndPointTests
{
private IHttpServer _stubHttp;
private string _hostUrl;
[SetUp]
public void SetUp()
{
_hostUrl = HostHelper.GenerateAHostUrlForAStubServer();
}
[Test]
public void SUT_should_return_stubbed_response()
{
_stubHttp = HttpMockRepository.At(_hostUrl);
const string expected = "<xml><>response>Hello World</response></xml>";
_stubHttp.Stub(x => x.Get("/endpoint"))
.Return(expected)
.OK();
string result = new WebClient().DownloadString(string.Format("{0}/endpoint", _hostUrl));
Assert.That(result, Is.EqualTo(expected));
}
[Test]
public void SUT_should_return_stubbed_byte_array_response()
{
_stubHttp = HttpMockRepository.At(_hostUrl);
byte[] expected =
Encoding.UTF8.GetBytes(
"<xml><>response>Change to bytes to simulate possible stream response</response></xml>");
_stubHttp.Stub(x => x.Get("/endpoint"))
.Return(expected)
.OK();
byte[] result = new WebClient().DownloadData(string.Format("{0}/endpoint", _hostUrl));
Assert.That(result, Is.EqualTo(expected));
}
[TestCase(1)]
[TestCase(100)]
[TestCase(5000)]
public void SUT_should_get_back_exact_content_in_the_last_request_body(int count)
{
_stubHttp = HttpMockRepository.At(_hostUrl);
string expected = string.Format("<xml><>response>{0}</response></xml>",
string.Join(" ", Enumerable.Range(0, count)));
var requestHandler = _stubHttp.Stub(x => x.Post("/endpoint"));
requestHandler.Return(expected).OK();
using (var wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/xml";
wc.UploadString(string.Format("{0}/endpoint", _hostUrl), expected);
}
var requestBody = ((RequestHandler) requestHandler).LastRequest().Body;
Assert.That(requestBody, Is.EqualTo(expected));
}
[Test]
public void Should_get_the_last_request_that_was_sent()
{
var expected = "expectedbody";
_stubHttp = HttpMockRepository.At(_hostUrl);
var requestHandler =_stubHttp.Stub( x => x.Post("/endpoint"));
requestHandler.Return(expected).OK();
using (var wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/xml";
wc.UploadString(string.Format("{0}/endpoint", _hostUrl), "first");
wc.UploadString(string.Format("{0}/endpoint", _hostUrl), "second");
wc.UploadString(string.Format("{0}/endpoint", _hostUrl), expected);
}
var requestBody = ((RequestHandler) requestHandler).LastRequest().Body;
Assert.That(requestBody, Is.EqualTo(expected));
}
[Test]
public void Should_start_listening_before_stubs_have_been_set()
{
_stubHttp = HttpMockRepository.At(_hostUrl);
_stubHttp.Stub(x => x.Get("/endpoint"))
.Return("listening")
.OK();
using (var tcpClient = new TcpClient())
{
var uri = new Uri(_hostUrl);
tcpClient.Connect(uri.Host, uri.Port);
Assert.That(tcpClient.Connected, Is.True);
tcpClient.Close();
}
string result = new WebClient().DownloadString(string.Format("{0}/endpoint", _hostUrl));
Assert.That(result, Is.EqualTo("listening"));
}
[Test]
public void Should_return_expected_ok_response()
{
_stubHttp = HttpMockRepository.At(_hostUrl);
_stubHttp
.Stub(x => x.Get("/api2/status"))
.Return("Hello")
.OK();
_stubHttp
.Stub(x => x.Get("/api2/echo"))
.Return("Echo")
.NotFound();
_stubHttp
.Stub(x => x.Get("/api2/echo2"))
.Return("Nothing")
.WithStatus(HttpStatusCode.Unauthorized);
var wc = new WebClient();
Assert.That(wc.DownloadString(string.Format("{0}/api2/status", _hostUrl)), Is.EqualTo("Hello"));
try
{
Console.WriteLine(wc.DownloadString(_hostUrl + "/api2/echo"));
}
catch (Exception ex)
{
Assert.That(ex, Is.InstanceOf(typeof(WebException)));
Assert.That(((WebException) ex).Status, Is.EqualTo(WebExceptionStatus.ProtocolError));
}
try
{
wc.DownloadString(_hostUrl + "/api2/echo2");
}
catch (Exception ex)
{
Assert.That(ex, Is.InstanceOf(typeof(WebException)));
Assert.That(((WebException) ex).Status, Is.EqualTo(WebExceptionStatus.ProtocolError));
}
}
[Test]
public void Should_hit_the_same_url_multiple_times()
{
string endpoint = _hostUrl;
_stubHttp = HttpMockRepository.At(endpoint);
_stubHttp
.Stub(x => x.Get("/api2/echo"))
.Return("Echo")
.NotFound();
_stubHttp
.Stub(x => x.Get("/api2/echo2"))
.Return("Nothing")
.WithStatus(HttpStatusCode.Unauthorized);
for (int count = 0; count < 6; count++)
{
RequestEcho(endpoint);
}
}
[Test]
public void Should_support_range_requests()
{
_stubHttp = HttpMockRepository.At(_hostUrl);
string query = "/path/file";
int fileSize = 2048;
string pathToFile = CreateFile(fileSize);
try
{
_stubHttp.Stub(x => x.Get(query))
.ReturnFileRange(pathToFile, 0, 1023)
.WithStatus(HttpStatusCode.PartialContent);
HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(_hostUrl + query);
request.Method = "GET";
request.AddRange(0, 1023);
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
byte[] downloadData = new byte[response.ContentLength];
using (response)
{
response.GetResponseStream().Read(downloadData, 0, downloadData.Length);
}
Assert.That(downloadData.Length, Is.EqualTo(1024));
}
finally
{
try
{
File.Delete(pathToFile);
}
catch
{
}
}
}
[Test]
public void SUT_should_return_stubbed_response_for_custom_verbs()
{
_stubHttp = HttpMockRepository.At(_hostUrl);
const string expected = "<xml><>response>Hello World</response></xml>";
_stubHttp.Stub(x => x.CustomVerb("/endpoint", "PURGE"))
.Return(expected)
.OK();
var request = (HttpWebRequest) WebRequest.Create(string.Format("{0}/endpoint", _hostUrl));
request.Method = "PURGE";
request.Host = "nonstandard.host";
request.Headers.Add("X-Go-Faster", "11");
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
{
var responseBody = new StreamReader(stream).ReadToEnd();
Assert.That(responseBody, Is.EqualTo(expected));
}
}
[TestCase(1)]
[TestCase(10)]
[TestCase(50)]
public void SUT_should_get_back_the_collection_of_requests(int count)
{
_stubHttp = HttpMockRepository.At(_hostUrl);
var requestHandlerStub = _stubHttp.Stub(x => x.Post("/endpoint"));
requestHandlerStub.Return(string.Empty).OK();
var expectedBodyList = new List<string>();
using (var wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/xml";
for (int i = 0; i < count; i++)
{
string expected = string.Format("<xml><>response>{0}</response></xml>",
string.Join(" ", Enumerable.Range(0, i)));
wc.UploadString(string.Format("{0}/endpoint", _hostUrl), expected);
expectedBodyList.Add(expected);
}
}
var requestHandler = (RequestHandler) requestHandlerStub;
var observedRequests = requestHandler.GetObservedRequests();
Assert.AreEqual(expectedBodyList.Count, observedRequests.ToList().Count);
for (int i = 0; i < expectedBodyList.Count; i++)
{
Assert.AreEqual(expectedBodyList.ElementAt(i), observedRequests.ElementAt(i).Body);
}
}
[TestCase(500, 200)]
[TestCase(1234, 250)]
[TestCase(2000, 350)]
public void Should_wait_more_than_the_added_delay(int wait, int added)
{
_stubHttp = HttpMockRepository.At(_hostUrl);
var stub = _stubHttp.Stub(x => x.Get("/endpoint")).Return("Delayed response");
stub.OK();
stub.WithDelay(wait);
string ans;
var sw = new Stopwatch();
using (var wc = new WebClient())
{
sw.Start();
ans = wc.DownloadString($"{_hostUrl}/endpoint");
sw.Stop();
}
Assert.GreaterOrEqual(sw.ElapsedMilliseconds, wait);
Assert.AreEqual("Delayed response", ans);
stub.WithDelay(TimeSpan.FromMilliseconds(added)).Return("Delayed response 2");
sw.Reset();
using (var wc = new WebClient())
{
sw.Start();
ans = wc.DownloadString($"{_hostUrl}/endpoint");
sw.Stop();
}
Assert.GreaterOrEqual(sw.ElapsedMilliseconds, wait + added);
Assert.AreEqual("Delayed response 2", ans);
}
[TestCase(407, 50)]
[TestCase(1015, 50)]
[TestCase(1691, 50)]
public void Delayed_stub_shouldnt_block_undelayed_stub(int wait, int epsilon)
{
_stubHttp = HttpMockRepository.At(_hostUrl);
_stubHttp.Stub(x => x.Get("/firstEndp")).WithDelay(wait).Return("Delayed response (stub 1)").OK();
_stubHttp.Stub(x => x.Get("/secondEndp")).Return("Undelayed response (stub 2)").OK();
Stopwatch swDelayed = new Stopwatch();
Stopwatch swUndelayed = new Stopwatch();
Task<string> taskDelayed = null,
taskUndelayed = null;
using (var wcUndelayed = new WebClient())
using (var wcDelayed = new WebClient())
{
// This triggers the server so that we won't have any initial (unwanted) delays
wcDelayed.DownloadString($"{_hostUrl}/firstEndp");
wcUndelayed.DownloadString($"{_hostUrl}/secondEndp");
taskDelayed = StartDelayedRequest(swDelayed);
taskUndelayed = Task.Run(() =>
{
swUndelayed.Start();
var ans = wcUndelayed.DownloadString($"{_hostUrl}/secondEndp");
swUndelayed.Stop();
return ans;
});
taskDelayed.Wait();
taskUndelayed.Wait();
}
Assert.AreEqual("Delayed response (stub 1)", taskDelayed.Result);
Assert.AreEqual("Undelayed response (stub 2)", taskUndelayed.Result);
Assert.Greater(swDelayed.ElapsedMilliseconds - epsilon, swUndelayed.ElapsedMilliseconds);
}
private string CreateFile(int fileSize)
{
string fileName = Path.GetTempFileName();
using (FileStream fileStream = File.OpenWrite(fileName))
{
for (int count = 0; count < fileSize; count++)
{
fileStream.WriteByte((byte) count);
}
fileStream.Close();
}
return fileName;
}
private static void RequestEcho(string endpoint)
{
var wc = new WebClient();
try
{
wc.DownloadString(endpoint + "/api2/echo");
}
catch (Exception ex)
{
Assert.That(ex, Is.InstanceOf(typeof(WebException)));
Assert.That(((WebException) ex).Status, Is.EqualTo(WebExceptionStatus.ProtocolError));
}
}
public async Task<string> StartDelayedRequest(Stopwatch sw)
{
using (var wc = new WebClient())
{
sw.Restart();
var ans = await wc.DownloadStringTaskAsync($"{_hostUrl}/firstEndp");
sw.Stop();
return ans;
}
}
}
}