This repository has been archived by the owner on Nov 25, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 104
/
ApiControllerTest.cs
794 lines (682 loc) · 36.3 KB
/
ApiControllerTest.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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.Controllers;
using System.Web.Http.Dispatcher;
using System.Web.Http.Filters;
using System.Web.Http.ModelBinding;
using System.Web.Http.Routing;
using System.Web.Http.Services;
using Microsoft.TestCommon;
using Moq;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Http
{
public class ApiControllerTest
{
private readonly HttpActionContext _actionContextInstance = ContextUtil.CreateActionContext();
private readonly HttpConfiguration _configurationInstance = new HttpConfiguration();
private readonly HttpActionDescriptor _actionDescriptorInstance = new Mock<HttpActionDescriptor>() { CallBase = true }.Object;
[Fact]
public void Setting_CustomActionInvoker()
{
// Arrange
ApiController api = new UsersController();
string responseText = "Hello World";
HttpControllerContext controllerContext = ContextUtil.CreateControllerContext();
HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, "test", typeof(UsersController));
controllerContext.ControllerDescriptor = controllerDescriptor;
Mock<IHttpActionInvoker> mockInvoker = new Mock<IHttpActionInvoker>();
mockInvoker
.Setup(invoker => invoker.InvokeActionAsync(It.IsAny<HttpActionContext>(), It.IsAny<CancellationToken>()))
.Returns(() =>
{
TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
tcs.TrySetResult(new HttpResponseMessage() { Content = new StringContent(responseText) });
return tcs.Task;
});
controllerDescriptor.Configuration.Services.Replace(typeof(IHttpActionInvoker), mockInvoker.Object);
// Act
HttpResponseMessage message = api.ExecuteAsync(
controllerContext,
CancellationToken.None).Result;
// Assert
Assert.Equal(responseText, message.Content.ReadAsStringAsync().Result);
}
[Fact]
public void Setting_CustomActionSelector()
{
// Arrange
ApiController api = new UsersController();
HttpControllerContext controllerContext = ContextUtil.CreateControllerContext();
HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, "test", typeof(UsersController));
controllerContext.ControllerDescriptor = controllerDescriptor;
Mock<IHttpActionSelector> mockSelector = new Mock<IHttpActionSelector>();
mockSelector
.Setup(invoker => invoker.SelectAction(It.IsAny<HttpControllerContext>()))
.Returns(() =>
{
Func<HttpResponseMessage> testDelegate =
() => new HttpResponseMessage { Content = new StringContent("This is a test") };
return new ReflectedHttpActionDescriptor
{
Configuration = controllerContext.Configuration,
ControllerDescriptor = controllerDescriptor,
MethodInfo = testDelegate.Method
};
});
controllerDescriptor.Configuration.Services.Replace(typeof(IHttpActionSelector), mockSelector.Object);
// Act
HttpResponseMessage message = api.ExecuteAsync(
controllerContext,
CancellationToken.None).Result;
// Assert
Assert.Equal("This is a test", message.Content.ReadAsStringAsync().Result);
}
[Fact]
public void Default_Get()
{
// Arrange
ApiController api = new UsersController();
HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(instance: api, request: new HttpRequestMessage() { Method = HttpMethod.Get });
controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, "test", typeof(UsersController));
// Act
HttpResponseMessage message = api.ExecuteAsync(
controllerContext,
CancellationToken.None).Result;
// Assert
Assert.Equal("Default User", message.Content.ReadAsStringAsync().Result);
}
[Fact]
public void Default_Post()
{
// Arrange
ApiController api = new UsersController();
HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(instance: api, request: new HttpRequestMessage() { Method = HttpMethod.Post });
controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, "test", typeof(UsersController));
// Act
HttpResponseMessage message = api.ExecuteAsync(
controllerContext,
CancellationToken.None).Result;
// Assert
Assert.Equal("User Posted", message.Content.ReadAsStringAsync().Result);
}
[Fact]
public void Default_Put()
{
// Arrange
ApiController api = new UsersController();
HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(instance: api, request: new HttpRequestMessage() { Method = HttpMethod.Put });
controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, "test", typeof(UsersController));
// Act
HttpResponseMessage message = api.ExecuteAsync(
controllerContext,
CancellationToken.None).Result;
// Assert
Assert.Equal("User Updated", message.Content.ReadAsStringAsync().Result);
}
[Fact]
public void Default_Delete()
{
// Arrange
ApiController api = new UsersController();
HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(instance: api, request: new HttpRequestMessage() { Method = HttpMethod.Delete });
controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, "test", typeof(UsersController));
// Act
HttpResponseMessage message = api.ExecuteAsync(
controllerContext,
CancellationToken.None).Result;
// Assert
Assert.Equal("User Deleted", message.Content.ReadAsStringAsync().Result);
}
[Fact]
public void Route_ActionName()
{
// Arrange
ApiController api = new UsersRpcController();
HttpRouteData route = new HttpRouteData(new HttpRoute());
route.Values.Add("action", "Admin");
HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(instance: api, routeData: route, request: new HttpRequestMessage() { Method = HttpMethod.Post });
controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, "test", typeof(UsersRpcController));
// Act
HttpResponseMessage message = api.ExecuteAsync(controllerContext, CancellationToken.None).Result;
User user = message.Content.ReadAsAsync<User>().Result;
// Assert
Assert.Equal("Yao", user.FirstName);
Assert.Equal("Huang", user.LastName);
}
[Fact]
public void Route_Get_Action_With_Route_Parameters()
{
// Arrange
ApiController api = new UsersRpcController();
HttpRouteData route = new HttpRouteData(new HttpRoute());
route.Values.Add("action", "EchoUser");
route.Values.Add("firstName", "RouteFirstName");
route.Values.Add("lastName", "RouteLastName");
HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(instance: api, routeData: route, request: new HttpRequestMessage() { Method = HttpMethod.Post });
controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, "test", typeof(UsersRpcController));
// Act
HttpResponseMessage message = api.ExecuteAsync(controllerContext, CancellationToken.None).Result;
User user = message.Content.ReadAsAsync<User>().Result;
// Assert
Assert.Equal("RouteFirstName", user.FirstName);
Assert.Equal("RouteLastName", user.LastName);
}
[Fact]
public void Route_Get_Action_With_Query_Parameters()
{
// Arrange
ApiController api = new UsersRpcController();
HttpRouteData route = new HttpRouteData(new HttpRoute());
route.Values.Add("action", "EchoUser");
Uri requestUri = new Uri("http://localhost/?firstName=QueryFirstName&lastName=QueryLastName");
HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(instance: api, routeData: route, request: new HttpRequestMessage()
{
Method = HttpMethod.Post,
RequestUri = requestUri
});
controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, "test", typeof(UsersRpcController));
// Act
HttpResponseMessage message = api.ExecuteAsync(controllerContext, CancellationToken.None).Result;
User user = message.Content.ReadAsAsync<User>().Result;
// Assert
Assert.Equal("QueryFirstName", user.FirstName);
Assert.Equal("QueryLastName", user.LastName);
}
[Fact]
public void Route_Post_Action_With_Content_Parameter()
{
// Arrange
ApiController api = new UsersRpcController();
HttpRouteData route = new HttpRouteData(new HttpRoute());
route.Values.Add("action", "EchoUserObject");
User postedUser = new User()
{
FirstName = "SampleFirstName",
LastName = "SampleLastName"
};
HttpRequestMessage request = new HttpRequestMessage() { Method = HttpMethod.Post };
// Create a serialized request because this test directly calls the controller
// which would have normally been working with a serialized request content.
string serializedUserAsString = null;
using (HttpRequestMessage tempRequest = new HttpRequestMessage() { Content = new ObjectContent<User>(postedUser, new XmlMediaTypeFormatter()) })
{
serializedUserAsString = tempRequest.Content.ReadAsStringAsync().Result;
}
StringContent stringContent = new StringContent(serializedUserAsString);
stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/xml");
request.Content = stringContent;
HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(instance: api, routeData: route, request: request);
controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, "test", typeof(UsersRpcController));
// Act
HttpResponseMessage message = api.ExecuteAsync(
controllerContext,
CancellationToken.None).Result;
User user = message.Content.ReadAsAsync<User>().Result;
// Assert
Assert.Equal(postedUser.FirstName, user.FirstName);
Assert.Equal(postedUser.LastName, user.LastName);
}
[Fact]
public void Invalid_Action_In_Route()
{
// Arrange
ApiController api = new UsersController();
HttpRouteData route = new HttpRouteData(new HttpRoute());
string actionName = "invalidOp";
route.Values.Add("action", actionName);
HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(instance: api, routeData: route, request: new HttpRequestMessage() { Method = HttpMethod.Get });
Type controllerType = typeof(UsersController);
controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, controllerType.Name, controllerType);
controllerContext.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
// Act & Assert
var exception = Assert.Throws<HttpResponseException>(() =>
{
HttpResponseMessage message = api.ExecuteAsync(controllerContext, CancellationToken.None).Result;
});
Assert.Equal(HttpStatusCode.NotFound, exception.Response.StatusCode);
var content = Assert.IsType<ObjectContent<HttpError>>(exception.Response.Content);
Assert.Equal("No action was found on the controller 'UsersController' that matches the name 'invalidOp'.",
((HttpError)content.Value)["MessageDetail"]);
}
[Fact]
public void ExecuteAsync_InvokesAuthorizationFilters_ThenInvokesModelBinding_ThenInvokesActionFilters_ThenInvokesAction()
{
List<string> log = new List<string>();
Mock<ApiController> controllerMock = new Mock<ApiController>() { CallBase = true };
var controllerContextMock = new Mock<HttpControllerContext>();
Mock<IActionValueBinder> binderMock = new Mock<IActionValueBinder>();
Mock<HttpActionBinding> actionBindingMock = new Mock<HttpActionBinding>();
actionBindingMock.Setup(b => b.ExecuteBindingAsync(It.IsAny<HttpActionContext>(), It.IsAny<CancellationToken>())).Returns(() => Task.Factory.StartNew(() => { log.Add("model binding"); }));
binderMock.Setup(b => b.GetBinding(It.IsAny<HttpActionDescriptor>())).Returns(actionBindingMock.Object);
HttpConfiguration configuration = new HttpConfiguration();
HttpControllerContext controllerContext = controllerContextMock.Object;
controllerContext.Configuration = configuration;
controllerContext.ControllerDescriptor = new HttpControllerDescriptor(configuration, "test", typeof(object));
var actionFilterMock = CreateActionFilterMock((ac, ct, cont) =>
{
log.Add("action filters");
return cont();
});
var authFilterMock = CreateAuthorizationFilterMock((ac, ct, cont) =>
{
log.Add("auth filters");
return cont();
});
var selectorMock = new Mock<IHttpActionSelector>();
Mock<HttpActionDescriptor> actionDescriptorMock = new Mock<HttpActionDescriptor>();
actionDescriptorMock.Setup(ad => ad.ActionBinding).Returns(actionBindingMock.Object);
actionDescriptorMock.Setup(ad => ad.GetFilterPipeline())
.Returns(new Collection<FilterInfo>(new List<FilterInfo>() { new FilterInfo(actionFilterMock.Object, FilterScope.Action), new FilterInfo(authFilterMock.Object, FilterScope.Action) }));
selectorMock.Setup(s => s.SelectAction(controllerContext)).Returns(actionDescriptorMock.Object);
ApiController controller = controllerMock.Object;
var invokerMock = new Mock<IHttpActionInvoker>();
invokerMock.Setup(i => i.InvokeActionAsync(It.IsAny<HttpActionContext>(), It.IsAny<CancellationToken>()))
.Returns(() => Task.Factory.StartNew(() =>
{
log.Add("action");
return new HttpResponseMessage();
}));
controllerContext.Configuration.Services.Replace(typeof(IHttpActionInvoker), invokerMock.Object);
controllerContext.Configuration.Services.Replace(typeof(IHttpActionSelector), selectorMock.Object);
controllerContext.Configuration.Services.Replace(typeof(IActionValueBinder), binderMock.Object);
var task = controller.ExecuteAsync(controllerContext, CancellationToken.None);
Assert.NotNull(task);
task.WaitUntilCompleted();
Assert.Equal(new string[] { "auth filters", "model binding", "action filters", "action" }, log.ToArray());
}
[Fact]
public void GetFilters_QueriesFilterProvidersFromServices()
{
// Arrange
Mock<DefaultServices> servicesMock = new Mock<DefaultServices> { CallBase = true };
Mock<IFilterProvider> filterProviderMock = new Mock<IFilterProvider>();
servicesMock.Setup(r => r.GetServices(typeof(IFilterProvider))).Returns(new object[] { filterProviderMock.Object }).Verifiable();
_configurationInstance.Services = servicesMock.Object;
HttpActionDescriptor actionDescriptorMock = new Mock<HttpActionDescriptor>() { CallBase = true }.Object;
actionDescriptorMock.Configuration = _configurationInstance;
// Act
actionDescriptorMock.GetFilterPipeline();
// Assert
servicesMock.Verify();
}
[Fact]
public void GetFilters_UsesFilterProvidersToGetFilters()
{
// Arrange
Mock<DefaultServices> servicesMock = new Mock<DefaultServices> { CallBase = true };
Mock<IFilterProvider> filterProviderMock = new Mock<IFilterProvider>();
servicesMock.Setup(r => r.GetServices(typeof(IFilterProvider))).Returns(new[] { filterProviderMock.Object });
_configurationInstance.Services = servicesMock.Object;
HttpActionDescriptor actionDescriptorMock = new Mock<HttpActionDescriptor>() { CallBase = true }.Object;
actionDescriptorMock.Configuration = _configurationInstance;
// Act
actionDescriptorMock.GetFilterPipeline().ToList();
// Assert
filterProviderMock.Verify(fp => fp.GetFilters(_configurationInstance, actionDescriptorMock));
}
[Fact]
public void RequestPropertyGetterSetterWorks()
{
Assert.Reflection.Property(new Mock<ApiController>().Object,
c => c.Request, expectedDefaultValue: null, allowNull: false,
roundTripTestValue: new HttpRequestMessage());
}
[Fact]
public void ConfigurationPropertyGetterSetterWorks()
{
Assert.Reflection.Property(new Mock<ApiController>().Object,
c => c.Configuration, expectedDefaultValue: null, allowNull: false,
roundTripTestValue: new HttpConfiguration());
}
[Fact]
public void ModelStatePropertyGetterWorks()
{
// Arrange
ApiController controller = new Mock<ApiController>().Object;
// Act
ModelStateDictionary expected = new ModelStateDictionary();
expected.Add("a", new ModelState() { Value = new ValueProviders.ValueProviderResult("result", "attempted", CultureInfo.InvariantCulture) });
controller.ModelState.Add("a", new ModelState() { Value = new ValueProviders.ValueProviderResult("result", "attempted", CultureInfo.InvariantCulture) });
// Assert
Assert.Equal(expected.Count, controller.ModelState.Count);
}
// TODO: Move these tests to ActionDescriptorTest
[Fact]
public void GetFilters_OrdersFilters()
{
// Arrange
HttpActionDescriptor actionDescriptorMock = new Mock<HttpActionDescriptor>() { CallBase = true }.Object;
actionDescriptorMock.Configuration = _configurationInstance;
var globalFilter = new FilterInfo(new TestMultiFilter(), FilterScope.Global);
var actionFilter = new FilterInfo(new TestMultiFilter(), FilterScope.Action);
var controllerFilter = new FilterInfo(new TestMultiFilter(), FilterScope.Controller);
Mock<DefaultServices> servicesMock = BuildFilterProvidingServicesMock(_configurationInstance, actionDescriptorMock, globalFilter, actionFilter, controllerFilter);
_configurationInstance.Services = servicesMock.Object;
// Act
var result = actionDescriptorMock.GetFilterPipeline().ToArray();
// Assert
Assert.Equal(new[] { globalFilter, controllerFilter, actionFilter }, result);
}
[Fact]
public void GetFilters_RemovesDuplicateUniqueFiltersKeepingMostSpecificScope()
{
// Arrange
HttpActionDescriptor actionDescriptorMock = new Mock<HttpActionDescriptor>() { CallBase = true }.Object;
actionDescriptorMock.Configuration = _configurationInstance;
var multiActionFilter = new FilterInfo(new TestMultiFilter(), FilterScope.Action);
var multiGlobalFilter = new FilterInfo(new TestMultiFilter(), FilterScope.Global);
var uniqueControllerFilter = new FilterInfo(new TestUniqueFilter(), FilterScope.Controller);
var uniqueActionFilter = new FilterInfo(new TestUniqueFilter(), FilterScope.Action);
Mock<DefaultServices> servicesMock = BuildFilterProvidingServicesMock(
_configurationInstance, actionDescriptorMock,
multiActionFilter, multiGlobalFilter, uniqueControllerFilter, uniqueActionFilter);
_configurationInstance.Services = servicesMock.Object;
// Act
var result = actionDescriptorMock.GetFilterPipeline().ToArray();
// Assert
Assert.Equal(new[] { multiGlobalFilter, multiActionFilter, uniqueActionFilter }, result);
}
[Fact]
public void InvokeActionWithActionFilters_ChainsFiltersInOrderFollowedByInnerActionContinuation()
{
// Arrange
List<string> log = new List<string>();
Mock<IActionFilter> globalFilterMock = CreateActionFilterMock((ctx, ct, continuation) =>
{
log.Add("globalFilter");
return continuation();
});
Mock<IActionFilter> actionFilterMock = CreateActionFilterMock((ctx, ct, continuation) =>
{
log.Add("actionFilter");
return continuation();
});
Func<Task<HttpResponseMessage>> innerAction = () => Task<HttpResponseMessage>.Factory.StartNew(() =>
{
log.Add("innerAction");
return null;
});
List<IActionFilter> filters = new List<IActionFilter>() {
globalFilterMock.Object,
actionFilterMock.Object,
};
// Act
var result = ApiController.InvokeActionWithActionFilters(_actionContextInstance, CancellationToken.None, filters, innerAction);
// Assert
Assert.NotNull(result);
var resultTask = result();
Assert.NotNull(resultTask);
resultTask.WaitUntilCompleted();
Assert.Equal(new[] { "globalFilter", "actionFilter", "innerAction" }, log.ToArray());
globalFilterMock.Verify();
actionFilterMock.Verify();
}
[Fact]
public void InvokeActionWithAuthorizationFilters_ChainsFiltersInOrderFollowedByInnerActionContinuation()
{
// Arrange
List<string> log = new List<string>();
Mock<IAuthorizationFilter> globalFilterMock = CreateAuthorizationFilterMock((ctx, ct, continuation) =>
{
log.Add("globalFilter");
return continuation();
});
Mock<IAuthorizationFilter> actionFilterMock = CreateAuthorizationFilterMock((ctx, ct, continuation) =>
{
log.Add("actionFilter");
return continuation();
});
Func<Task<HttpResponseMessage>> innerAction = () => Task<HttpResponseMessage>.Factory.StartNew(() =>
{
log.Add("innerAction");
return null;
});
List<IAuthorizationFilter> filters = new List<IAuthorizationFilter>() {
globalFilterMock.Object,
actionFilterMock.Object,
};
// Act
var result = ApiController.InvokeActionWithAuthorizationFilters(_actionContextInstance, CancellationToken.None, filters, innerAction);
// Assert
Assert.NotNull(result);
var resultTask = result();
Assert.NotNull(resultTask);
resultTask.WaitUntilCompleted();
Assert.Equal(new[] { "globalFilter", "actionFilter", "innerAction" }, log.ToArray());
globalFilterMock.Verify();
actionFilterMock.Verify();
}
[Fact]
public void InvokeActionWithExceptionFilters_IfActionTaskIsSuccessful_ReturnsSuccessTask()
{
// Arrange
List<string> log = new List<string>();
var response = new HttpResponseMessage();
var actionTask = TaskHelpers.FromResult(response);
var exceptionFilterMock = CreateExceptionFilterMock((ec, ct) =>
{
log.Add("exceptionFilter");
return Task.Factory.StartNew(() => { });
});
var filters = new[] { exceptionFilterMock.Object };
// Act
var result = ApiController.InvokeActionWithExceptionFilters(actionTask, _actionContextInstance, CancellationToken.None, filters);
// Assert
Assert.NotNull(result);
result.WaitUntilCompleted();
Assert.Equal(TaskStatus.RanToCompletion, result.Status);
Assert.Same(response, result.Result);
Assert.Equal(new string[] { }, log.ToArray());
}
[Fact]
public void InvokeActionWithExceptionFilters_IfActionTaskIsCanceled_ReturnsCanceledTask()
{
// Arrange
List<string> log = new List<string>();
var actionTask = TaskHelpers.Canceled<HttpResponseMessage>();
var exceptionFilterMock = CreateExceptionFilterMock((ec, ct) =>
{
log.Add("exceptionFilter");
return Task.Factory.StartNew(() => { });
});
var filters = new[] { exceptionFilterMock.Object };
// Act
var result = ApiController.InvokeActionWithExceptionFilters(actionTask, _actionContextInstance, CancellationToken.None, filters);
// Assert
Assert.NotNull(result);
result.WaitUntilCompleted();
Assert.Equal(TaskStatus.Canceled, result.Status);
Assert.Equal(new string[] { }, log.ToArray());
}
[Fact]
public void InvokeActionWithExceptionFilters_IfActionTaskIsFaulted_ExecutesFiltersAndReturnsFaultedTaskIfNotHandled()
{
// Arrange
List<string> log = new List<string>();
var exception = new Exception();
var actionTask = TaskHelpers.FromError<HttpResponseMessage>(exception);
Exception exceptionSeenByFilter = null;
var exceptionFilterMock = CreateExceptionFilterMock((ec, ct) =>
{
exceptionSeenByFilter = ec.Exception;
log.Add("exceptionFilter");
return Task.Factory.StartNew(() => { });
});
var filters = new[] { exceptionFilterMock.Object };
// Act
var result = ApiController.InvokeActionWithExceptionFilters(actionTask, _actionContextInstance, CancellationToken.None, filters);
// Assert
Assert.NotNull(result);
result.WaitUntilCompleted();
Assert.Equal(TaskStatus.Faulted, result.Status);
Assert.Same(exception, result.Exception.InnerException);
Assert.Same(exception, exceptionSeenByFilter);
Assert.Equal(new string[] { "exceptionFilter" }, log.ToArray());
}
[Fact]
public void InvokeActionWithExceptionFilters_IfActionTaskIsFaulted_ExecutesFiltersAndReturnsResultIfHandled()
{
// Arrange
List<string> log = new List<string>();
var exception = new Exception();
var actionTask = TaskHelpers.FromError<HttpResponseMessage>(exception);
HttpResponseMessage globalFilterResponse = new HttpResponseMessage();
HttpResponseMessage actionFilterResponse = new HttpResponseMessage();
HttpResponseMessage resultSeenByGlobalFilter = null;
var globalFilterMock = CreateExceptionFilterMock((ec, ct) =>
{
log.Add("globalFilter");
resultSeenByGlobalFilter = ec.Response;
ec.Response = globalFilterResponse;
return Task.Factory.StartNew(() => { });
});
var actionFilterMock = CreateExceptionFilterMock((ec, ct) =>
{
log.Add("actionFilter");
ec.Response = actionFilterResponse;
return Task.Factory.StartNew(() => { });
});
var filters = new[] { globalFilterMock.Object, actionFilterMock.Object };
// Act
var result = ApiController.InvokeActionWithExceptionFilters(actionTask, _actionContextInstance, CancellationToken.None, filters);
// Assert
Assert.NotNull(result);
result.WaitUntilCompleted();
Assert.Equal(TaskStatus.RanToCompletion, result.Status);
Assert.Same(globalFilterResponse, result.Result);
Assert.Same(actionFilterResponse, resultSeenByGlobalFilter);
Assert.Equal(new string[] { "actionFilter", "globalFilter" }, log.ToArray());
}
[Fact, RestoreThreadPrincipal]
public void User_ReturnsThreadPrincipal()
{
// Arrange
ApiController controller = new Mock<ApiController>().Object;
IPrincipal principal = new GenericPrincipal(new GenericIdentity("joe"), new string[0]);
Thread.CurrentPrincipal = principal;
// Act
IPrincipal result = controller.User;
// Assert
Assert.Same(result, principal);
}
[Fact]
public void ApiControllerCannotBeReused()
{
// Arrange
var config = new HttpConfiguration() { IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always };
var singletonController = new Mock<ApiController> { CallBase = true }.Object;
var mockDescriptor = new Mock<HttpControllerDescriptor>(config, "MyMock", singletonController.GetType()) { CallBase = true };
mockDescriptor.Setup(d => d.CreateController(It.IsAny<HttpRequestMessage>())).Returns(singletonController);
var mockSelector = new Mock<DefaultHttpControllerSelector>(config) { CallBase = true };
mockSelector.Setup(s => s.SelectController(It.IsAny<HttpRequestMessage>())).Returns(mockDescriptor.Object);
config.Routes.MapHttpRoute("default", "", new { controller = "MyMock" });
config.Services.Replace(typeof(IHttpControllerSelector), mockSelector.Object);
var server = new HttpServer(config);
var invoker = new HttpMessageInvoker(server);
// Act
HttpResponseMessage response1 = invoker.SendAsync(new HttpRequestMessage(HttpMethod.Get, "http://localhost/"), CancellationToken.None).Result;
HttpResponseMessage response2 = invoker.SendAsync(new HttpRequestMessage(HttpMethod.Get, "http://localhost/"), CancellationToken.None).Result;
// Assert
Assert.NotEqual(HttpStatusCode.InternalServerError, response1.StatusCode);
Assert.Equal(HttpStatusCode.InternalServerError, response2.StatusCode);
Assert.Contains("Cannot reuse an 'ApiController' instance. 'ApiController' has to be constructed per incoming message.", response2.Content.ReadAsStringAsync().Result);
}
[Fact]
public void ApiControllerPutsSelfInRequestResourcesToBeDisposed()
{
// Arrange
var config = new HttpConfiguration();
config.Routes.MapHttpRoute("default", "", new { controller = "SpyDispose" });
var server = new HttpServer(config);
var invoker = new HttpMessageInvoker(server);
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/");
invoker.SendAsync(request, CancellationToken.None).WaitUntilCompleted();
// Act
request.DisposeRequestResources();
// Assert
Assert.True(SpyDisposeController.DisposeWasCalled);
}
private Mock<IAuthorizationFilter> CreateAuthorizationFilterMock(Func<HttpActionContext, CancellationToken, Func<Task<HttpResponseMessage>>, Task<HttpResponseMessage>> implementation)
{
Mock<IAuthorizationFilter> filterMock = new Mock<IAuthorizationFilter>();
filterMock.Setup(f => f.ExecuteAuthorizationFilterAsync(It.IsAny<HttpActionContext>(),
CancellationToken.None,
It.IsAny<Func<Task<HttpResponseMessage>>>()))
.Returns(implementation)
.Verifiable();
return filterMock;
}
private Mock<IActionFilter> CreateActionFilterMock(Func<HttpActionContext, CancellationToken, Func<Task<HttpResponseMessage>>, Task<HttpResponseMessage>> implementation)
{
Mock<IActionFilter> filterMock = new Mock<IActionFilter>();
filterMock.Setup(f => f.ExecuteActionFilterAsync(It.IsAny<HttpActionContext>(),
CancellationToken.None,
It.IsAny<Func<Task<HttpResponseMessage>>>()))
.Returns(implementation)
.Verifiable();
return filterMock;
}
private Mock<IExceptionFilter> CreateExceptionFilterMock(Func<HttpActionExecutedContext, CancellationToken, Task> implementation)
{
Mock<IExceptionFilter> filterMock = new Mock<IExceptionFilter>();
filterMock.Setup(f => f.ExecuteExceptionFilterAsync(It.IsAny<HttpActionExecutedContext>(),
CancellationToken.None))
.Returns(implementation)
.Verifiable();
return filterMock;
}
private static Mock<DefaultServices> BuildFilterProvidingServicesMock(HttpConfiguration configuration, HttpActionDescriptor action, params FilterInfo[] filters)
{
var servicesMock = new Mock<DefaultServices> { CallBase = true };
var filterProviderMock = new Mock<IFilterProvider>();
servicesMock.Setup(r => r.GetServices(typeof(IFilterProvider))).Returns(new[] { filterProviderMock.Object });
filterProviderMock.Setup(fp => fp.GetFilters(configuration, action)).Returns(filters);
return servicesMock;
}
/// <summary>
/// Simple IFilter implementation with AllowMultiple = true
/// </summary>
public class TestMultiFilter : IFilter
{
public bool AllowMultiple
{
get { return true; }
}
}
/// <summary>
/// Simple IFilter implementation with AllowMultiple = false
/// </summary>
public class TestUniqueFilter : IFilter
{
public bool AllowMultiple
{
get { return false; }
}
}
}
public class SpyDisposeController : System.Web.Http.ApiController
{
public static bool DisposeWasCalled = false;
public SpyDisposeController()
{
}
public void Get() { }
protected override void Dispose(bool disposing)
{
DisposeWasCalled = true;
base.Dispose(disposing);
}
}
}