This repository has been archived by the owner on Jan 24, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
BrowserFixture.cs
706 lines (572 loc) · 22.9 KB
/
BrowserFixture.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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
namespace Nancy.Testing.Tests
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using Nancy.Extensions;
using Nancy.Helpers;
using Nancy.Session;
using Nancy.Tests;
using Nancy.Authentication.Forms;
using Nancy.Configuration;
using Nancy.Tests.xUnitExtensions;
using Xunit;
using FakeItEasy;
public class BrowserFixture
{
private readonly Browser browser;
public BrowserFixture()
{
var bootstrapper =
new ConfigurableBootstrapper(config => config.Modules(typeof(EchoModule)));
CookieBasedSessions.Enable(bootstrapper);
this.browser = new Browser(bootstrapper);
}
[Fact]
public async Task Should_be_able_to_send_string_in_body()
{
// Given
const string thisIsMyRequestBody = "This is my request body";
// When
var result = await browser.Post("/", with =>
{
with.HttpRequest();
with.Body(thisIsMyRequestBody);
});
// Then
result.Body.AsString().ShouldEqual(thisIsMyRequestBody);
}
[Fact]
public async Task Should_be_able_to_set_user_host_address()
{
// Given
const string userHostAddress = "127.0.0.1";
// When
var result = await browser.Get("/userHostAddress", with =>
{
with.HttpRequest();
with.UserHostAddress(userHostAddress);
});
// Then
result.Body.AsString().ShouldEqual(userHostAddress);
}
[Fact]
public async Task Should_be_able_check_is_local_ipV4()
{
// Given
const string userHostAddress = "127.0.0.1";
// When
var result = await browser.Get("/isLocal", with =>
{
with.HttpRequest();
with.HostName("localhost");
with.UserHostAddress(userHostAddress);
});
// Then
result.Body.AsString().ShouldEqual("local");
}
[Fact]
public async Task Should_be_able_check_is_local_ipV6()
{
// Given
const string userHostAddress = "::1";
// When
var result = await browser.Get("/isLocal", with =>
{
with.HttpRequest();
with.HostName("localhost");
with.UserHostAddress(userHostAddress);
});
// Then
result.Body.AsString().ShouldEqual("local");
}
[Fact]
public async Task Should_be_able_check_is_not_local()
{
// Given
const string userHostAddress = "84.12.65.72";
// When
var result = await browser.Get("/isLocal", with =>
{
with.HttpRequest();
with.HostName("anotherhost");
with.UserHostAddress(userHostAddress);
});
// Then
result.Body.AsString().ShouldEqual("not-local");
}
[Fact]
public async Task Should_be_able_to_send_stream_in_body()
{
// Given
const string thisIsMyRequestBody = "This is my request body";
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(thisIsMyRequestBody);
writer.Flush();
// When
var result = await browser.Post("/", with =>
{
with.HttpRequest();
with.Body(stream, "text/plain");
});
// Then
result.Body.AsString().ShouldEqual(thisIsMyRequestBody);
}
[Fact]
public async Task Should_be_able_to_send_json_in_body()
{
// Given
var model = new EchoModel { SomeString = "Some String", SomeInt = 29, SomeBoolean = true };
// When
var result = await browser.Post("/", with =>
{
with.JsonBody(model);
});
// Then
var actualModel = result.Body.DeserializeJson<EchoModel>();
actualModel.ShouldNotBeNull();
actualModel.SomeString.ShouldEqual(model.SomeString);
actualModel.SomeInt.ShouldEqual(model.SomeInt);
actualModel.SomeBoolean.ShouldEqual(model.SomeBoolean);
}
[Fact]
public async Task Should_be_able_to_send_xml_in_body()
{
// Given
var model = new EchoModel { SomeString = "Some String", SomeInt = 29, SomeBoolean = true };
// When
var result = await browser.Post("/", with =>
{
with.XMLBody(model);
});
// Then
var actualModel = result.Body.DeserializeXml<EchoModel>();
actualModel.ShouldNotBeNull();
actualModel.SomeString.ShouldEqual(model.SomeString);
actualModel.SomeInt.ShouldEqual(model.SomeInt);
actualModel.SomeBoolean.ShouldEqual(model.SomeBoolean);
}
[Fact]
public async Task Should_add_basic_authentication_credentials_to_the_headers_of_the_request()
{
// Given
var context = new BrowserContext(A.Fake<INancyEnvironment>());
// When
context.BasicAuth("username", "password");
// Then
IBrowserContextValues values = context;
var credentials = string.Format("{0}:{1}", "username", "password");
var encodedCredentials = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials));
values.Headers["Authorization"].ShouldHaveCount(1);
values.Headers["Authorization"].First().ShouldEqual("Basic " + encodedCredentials);
}
[Fact]
public void Should_add_cookies_to_the_request()
{
// Given
var context = new BrowserContext(A.Fake<INancyEnvironment>());
var cookies =
new Dictionary<string, string>
{
{ "CookieName", "CookieValue" },
{ "SomeCookieName", "SomeCookieValue" }
};
// When
context.Cookie(cookies);
// Then
IBrowserContextValues values = context;
var cookieString = cookies.Aggregate(string.Empty, (current, cookie) => current + string.Format("{0}={1};", HttpUtility.UrlEncode(cookie.Key), HttpUtility.UrlEncode(cookie.Value)));
values.Headers["Cookie"].ShouldHaveCount(1);
values.Headers["Cookie"].First().ShouldEqual(cookieString);
}
[Fact]
public void Should_add_cookie_to_the_request()
{
// Given
var context = new BrowserContext(A.Fake<INancyEnvironment>());
var cookies =
new Dictionary<string, string>
{
{ "CookieName", "CookieValue" },
{ "SomeCookieName", "SomeCookieValue" }
};
// When
foreach (var cookie in cookies)
{
context.Cookie(cookie.Key, cookie.Value);
}
// Then
IBrowserContextValues values = context;
var cookieString = cookies.Aggregate(string.Empty, (current, cookie) => current + string.Format("{0}={1};", HttpUtility.UrlEncode(cookie.Key), HttpUtility.UrlEncode(cookie.Value)));
values.Headers["Cookie"].ShouldHaveCount(1);
values.Headers["Cookie"].First().ShouldEqual(cookieString);
}
[Fact]
public async Task Should_add_cookies_to_the_request_and_get_cookies_in_response()
{
// Given
var cookies =
new Dictionary<string, string>
{
{ "CookieName", "CookieValue" },
{ "SomeCookieName", "SomeCookieValue" }
};
// When
var result = await browser.Get("/cookie", with =>
{
with.Cookie(cookies);
});
// Then
result.Cookies.Single(x => x.Name == "CookieName").Value.ShouldEqual("CookieValue");
result.Cookies.Single(x => x.Name == "SomeCookieName").Value.ShouldEqual("SomeCookieValue");
}
[Fact]
public async Task Should_add_a_cookie_to_the_request_and_get_a_cookie_in_response()
{
// Given, When
var result = await browser.Get("/cookie", with => with.Cookie("CookieName", "CookieValue"));
// Then
result.Cookies.Single(x => x.Name == "CookieName").Value.ShouldEqual("CookieValue");
}
[Fact]
public async Task Should_be_able_to_continue_with_another_request()
{
// Given
const string FirstRequestBody = "This is my first request body";
const string SecondRequestBody = "This is my second request body";
var firstRequestStream = new MemoryStream();
var firstRequestWriter = new StreamWriter(firstRequestStream);
firstRequestWriter.Write(FirstRequestBody);
firstRequestWriter.Flush();
var secondRequestStream = new MemoryStream();
var secondRequestWriter = new StreamWriter(secondRequestStream);
secondRequestWriter.Write(SecondRequestBody);
secondRequestWriter.Flush();
// When
await browser.Post("/", with =>
{
with.HttpRequest();
with.Body(firstRequestStream, "text/plain");
});
var result = await browser.Post("/", with =>
{
with.HttpRequest();
with.Body(secondRequestStream, "text/plain");
});
// Then
result.Body.AsString().ShouldEqual(SecondRequestBody);
}
[Fact]
public async Task Should_maintain_cookies_when_chaining_requests()
{
// Given
// When
await browser.Get("/session", with => with.HttpRequest());
var result = await this.browser.Get(
"/session",
with => with.HttpRequest());
//Then
result.Body.AsString().ShouldEqual("Current session value is: I've created a session!");
}
[Fact]
public async Task Should_maintain_cookies_even_if_not_set_on_directly_preceding_request()
{
// Given
// When
await browser.Get("/session", with => with.HttpRequest());
await browser.Get("/nothing", with => with.HttpRequest());
var result = await browser.Get("/session", with => with.HttpRequest());
//Then
result.Body.AsString().ShouldEqual("Current session value is: I've created a session!");
}
[Fact]
public async Task Should_be_able_to_not_specify_delegate_for_basic_http_request()
{
//Given, When
var result = await browser.Get("/type");
//Then
result.Body.AsString().ShouldEqual("http");
}
[Fact]
public async Task Should_add_ajax_header()
{
//Given, When
var result = await browser.Get("/ajax", with => with.AjaxRequest());
//Then
result.Body.AsString().ShouldEqual("ajax");
}
[Fact]
public async Task Should_throw_an_exception_when_the_cert_couldnt_be_found()
{
//Given, When
var exception = await RecordAsync.Exception(() =>
{
return browser.Get("/ajax", with =>
with.Certificate(
StoreLocation.CurrentUser,
StoreName.My,
X509FindType.FindByThumbprint,
"aa aa aa"));
});
//Then
exception.ShouldBeOfType<InvalidOperationException>();
}
[Fact]
public async Task Should_add_certificate()
{
//Given, When
var result = await browser.Get("/cert", with => with.Certificate());
//Then
result.Context.Request.ClientCertificate.ShouldNotBeNull();
}
[Fact]
public async Task Should_change_scheme_to_https_when_HttpsRequest_is_called_on_the_context()
{
//Given, When
var result = await browser.Get("/", with => with.HttpsRequest());
//Then
result.Context.Request.Url.Scheme.ShouldEqual("https");
}
[Fact]
public async Task Should_add_forms_authentication_cookie_to_the_request()
{
//Given
var userId = A.Dummy<Guid>();
var formsAuthConfig = new FormsAuthenticationConfiguration()
{
RedirectUrl = "/login",
UserMapper = A.Fake<IUserMapper>(),
};
var encryptedId = formsAuthConfig.CryptographyConfiguration.EncryptionProvider.Encrypt(userId.ToString());
var hmacBytes = formsAuthConfig.CryptographyConfiguration.HmacProvider.GenerateHmac(encryptedId);
var hmacString = Convert.ToBase64String(hmacBytes);
var cookieContents = String.Format("{1}{0}", encryptedId, hmacString);
//When
var response = await browser.Get("/cookie", (with) =>
{
with.HttpRequest();
with.FormsAuth(userId, formsAuthConfig);
});
var cookie = response.Cookies.Single(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName);
var cookieValue = cookie.Value;
//Then
cookieValue.ShouldEqual(cookieContents);
}
[Fact]
public async Task Should_return_JSON_serialized_form()
{
// Given
var response = await browser.Post("/serializedform", (with) =>
{
with.HttpRequest();
with.Accept("application/json");
with.FormValue("SomeString", "Hi");
with.FormValue("SomeInt", "1");
with.FormValue("SomeBoolean", "true");
});
// When
var actualModel = response.Body.DeserializeJson<EchoModel>();
// Then
Assert.Equal("Hi", actualModel.SomeString);
Assert.Equal(1, actualModel.SomeInt);
Assert.Equal(true, actualModel.SomeBoolean);
}
[Fact]
public async Task Should_return_JSON_serialized_querystring()
{
// Given
var response = await browser.Get("/serializedquerystring", (with) =>
{
with.HttpRequest();
with.Accept("application/json");
with.Query("SomeString", "Hi");
with.Query("SomeInt", "1");
with.Query("SomeBoolean", "true");
});
// When
var actualModel = response.Body.DeserializeJson<EchoModel>();
// Then
Assert.Equal("Hi", actualModel.SomeString);
Assert.Equal(1, actualModel.SomeInt);
Assert.Equal(true, actualModel.SomeBoolean);
}
[Fact]
public async Task Should_encode_form()
{
//Given, When
var result = await browser.Post("/encoded", with =>
{
with.HttpRequest();
with.FormValue("name", "john++");
});
//Then
result.Body.AsString().ShouldEqual("john++");
}
[Fact]
public async Task Should_encode_querystring()
{
//Given, When
var result = await browser.Post("/encodedquerystring", with =>
{
with.HttpRequest();
with.Query("name", "john++");
});
//Then
result.Body.AsString().ShouldEqual("john++");
}
[Fact]
public async Task Should_add_nancy_testing_browser_header_as_default_user_agent()
{
// Given
const string expectedHeaderValue = "Nancy.Testing.Browser";
// When
var result = (await browser.Get("/useragent")).Body.AsString();
// Then
result.ShouldEqual(expectedHeaderValue);
}
[Fact]
public async Task Should_override_default_user_agent_when_explicitly_defined()
{
// Given
const string expectedHeaderValue = "Custom.User.Agent";
// When
var result = await browser.Get("/useragent", with =>
{
with.Header("User-Agent", expectedHeaderValue);
});
var header = result.Body.AsString();
// Then
header.ShouldEqual(expectedHeaderValue);
}
[Theory]
[InlineData("application/xml")]
public async Task Should_return_error_message_on_cyclical_exception(string accept)
{
//Given
var browser = new Browser(with =>
{
with.Modules(typeof(EchoModule));
with.Configure(env =>
{
env.Tracing(
enabled: true,
displayErrorTraces: true);
});
});
// When
var result = await browser.Get("/cyclical", with => with.Accept(accept));
//Then
var resultBody = result.Body.AsString();
resultBody.ShouldNotBeEmpty();
}
[Theory]
[InlineData("application/xml")]
public async Task Should_return_no_error_message_on_cyclical_exception_when_disabled_error_trace(string accept)
{
//Given
var browser = new Browser(with =>
{
with.Modules(typeof(EchoModule));
with.Configure(env =>
{
env.Tracing(
enabled: true,
displayErrorTraces: false);
});
});
// When
var result = await browser.Get("/cyclical", with => with.Accept(accept));
//Then
result.Body.AsString().ShouldBeEmpty();
}
public class EchoModel
{
public string SomeString { get; set; }
public int SomeInt { get; set; }
public bool SomeBoolean { get; set; }
}
public class Category
{
public string Name { get; set; }
public ICollection<Product> Products { get; set; }
}
public class Product
{
public string Name { get; set; }
public Category Category { get; set; }
}
public class EchoModule : NancyModule
{
public EchoModule()
{
Get("/cyclical", args =>
{
var category = new Category();
category.Name = "Electronics";
var product = new Product();
product.Name = "iPad";
product.Category = category;
category.Products = new Collection<Product>(new List<Product>(new[] { product }));
return product;
});
Post("/", args =>
{
var body = new StreamReader(this.Context.Request.Body).ReadToEnd();
return new Response
{
Contents = stream =>
{
var writer = new StreamWriter(stream);
writer.Write(body);
writer.Flush();
}
};
});
Get("/cookie", args =>
{
var response = (Response)"Cookies";
foreach (var cookie in this.Request.Cookies)
{
response.WithCookie(cookie.Key, cookie.Value);
}
return response;
});
Get("/nothing", args => string.Empty);
Get("/userHostAddress", args => this.Request.UserHostAddress);
Get("/isLocal", args => this.Request.IsLocal() ? "local" : "not-local");
Get("/session", args =>
{
var value = Session["moo"] ?? "";
var output = "Current session value is: " + value;
if (string.IsNullOrEmpty(value.ToString()))
{
Session["moo"] = "I've created a session!";
}
var response = (Response)output;
return response;
});
Get("/useragent", args => this.Request.Headers.UserAgent);
Get("/type", args => this.Request.Url.Scheme.ToLower());
Get("/ajax", args => this.Request.IsAjaxRequest() ? "ajax" : "not-ajax");
Post("/encoded", args => (string)this.Request.Form.name);
Post("/encodedquerystring", args => (string)this.Request.Query.name);
Post("/serializedform", args =>
{
var data = Request.Form.ToDictionary();
return data;
});
Get("/serializedquerystring", args =>
{
var data = Request.Query.ToDictionary();
return data;
});
}
}
}
}