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
|
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Moq;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Mvc.Async.Test
{
public class TaskAsyncActionDescriptorTest
{
private readonly MethodInfo _taskMethod = typeof(ExecuteController).GetMethod("SimpleTask");
[Fact]
public void Constructor_SetsProperties()
{
// Arrange
string actionName = "SomeAction";
ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;
// Act
TaskAsyncActionDescriptor ad = new TaskAsyncActionDescriptor(_taskMethod, actionName, cd);
// Assert
Assert.Equal(_taskMethod, ad.TaskMethodInfo);
Assert.Equal(actionName, ad.ActionName);
Assert.Equal(cd, ad.ControllerDescriptor);
}
[Fact]
public void Constructor_ThrowsIfActionNameIsEmpty()
{
// Arrange
ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;
// Act & assert
Assert.ThrowsArgumentNullOrEmpty(
delegate { new TaskAsyncActionDescriptor(_taskMethod, "", cd); }, "actionName");
}
[Fact]
public void Constructor_ThrowsIfActionNameIsNull()
{
// Arrange
ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;
// Act & assert
Assert.ThrowsArgumentNullOrEmpty(
delegate { new TaskAsyncActionDescriptor(_taskMethod, null, cd); }, "actionName");
}
[Fact]
public void Constructor_ThrowsIfTaskMethodInfoIsInvalid()
{
// Arrange
ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;
MethodInfo getHashCodeMethod = typeof(object).GetMethod("GetHashCode");
// Act & assert
Assert.Throws<ArgumentException>(
delegate { new TaskAsyncActionDescriptor(getHashCodeMethod, "SomeAction", cd); },
@"Cannot create a descriptor for instance method 'Int32 GetHashCode()' on type 'System.Object' because the type does not derive from ControllerBase.
Parameter name: taskMethodInfo");
}
[Fact]
public void Constructor_ThrowsIfTaskMethodInfoIsNull()
{
// Arrange
ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;
// Act & assert
Assert.ThrowsArgumentNull(
delegate { new TaskAsyncActionDescriptor(null, "SomeAction", cd); }, "taskMethodInfo");
}
[Fact]
public void Constructor_ThrowsIfControllerDescriptorIsNull()
{
// Act & assert
Assert.ThrowsArgumentNull(
delegate { new TaskAsyncActionDescriptor(_taskMethod, "SomeAction", null); }, "controllerDescriptor");
}
[Fact]
public void ExecuteTask()
{
// Arrange
TaskAsyncActionDescriptor actionDescriptor = GetActionDescriptor(GetExecuteControllerMethodInfo("SimpleTask"));
Dictionary<string, object> parameters = new Dictionary<string, object>()
{
{ "doWork", true }
};
ControllerContext controllerContext = GetControllerContext();
// Act
object retVal = ExecuteHelper(actionDescriptor, parameters, controllerContext);
// Assert
Assert.Null(retVal);
Assert.True((controllerContext.Controller as ExecuteController).WorkDone);
}
[Fact]
public void ExecuteTaskGeneric()
{
// Arrange
TaskAsyncActionDescriptor actionDescriptor = GetActionDescriptor(GetExecuteControllerMethodInfo("GenericTask"));
Dictionary<string, object> parameters = new Dictionary<string, object>()
{
{ "taskId", "foo" }
};
// Act
object retVal = ExecuteHelper(actionDescriptor, parameters);
// Assert
Assert.Equal("foo", retVal);
}
[Fact]
public void ExecuteTaskPreservesStackTraceOnException()
{
// Arrange
TaskAsyncActionDescriptor actionDescriptor = GetActionDescriptor(GetExecuteControllerMethodInfo("SimpleTaskException"));
Dictionary<string, object> parameters = new Dictionary<string, object>()
{
{ "doWork", true }
};
// Act
IAsyncResult result = actionDescriptor.BeginExecute(GetControllerContext(), parameters, null, null);
// Assert
InvalidOperationException ex = Assert.Throws<InvalidOperationException>(
() => actionDescriptor.EndExecute(result),
"Test exception from action"
);
Assert.True(ex.StackTrace.Contains("System.Web.Mvc.Async.Test.TaskAsyncActionDescriptorTest.ExecuteController."));
}
[Fact]
public void ExecuteTaskGenericPreservesStackTraceOnException()
{
// Arrange
TaskAsyncActionDescriptor actionDescriptor = GetActionDescriptor(GetExecuteControllerMethodInfo("GenericTaskException"));
Dictionary<string, object> parameters = new Dictionary<string, object>()
{
{ "taskId", "foo" },
{ "throwException", true }
};
// Act
IAsyncResult result = actionDescriptor.BeginExecute(GetControllerContext(), parameters, null, null);
// Assert
InvalidOperationException ex = Assert.Throws<InvalidOperationException>(
() => actionDescriptor.EndExecute(result),
"Test exception from action"
);
Assert.True(ex.StackTrace.Contains("System.Web.Mvc.Async.Test.TaskAsyncActionDescriptorTest.ExecuteController."));
}
[Fact]
public void ExecuteTaskOfPrivateT()
{
// Arrange
TaskAsyncActionDescriptor actionDescriptor = GetActionDescriptor(GetExecuteControllerMethodInfo("TaskOfPrivateT"));
ControllerContext controllerContext = GetControllerContext();
Dictionary<string, object> parameters = new Dictionary<string, object>();
// Act
object retVal = ExecuteHelper(actionDescriptor, parameters, controllerContext);
// Assert
Assert.Null(retVal);
Assert.True((controllerContext.Controller as ExecuteController).WorkDone);
}
[Fact]
public void ExecuteTaskPreservesState()
{
// Arrange
TaskAsyncActionDescriptor actionDescriptor = GetActionDescriptor(GetExecuteControllerMethodInfo("SimpleTask"));
Dictionary<string, object> parameters = new Dictionary<string, object>()
{
{ "doWork", true }
};
ControllerContext controllerContext = GetControllerContext();
// Act
TaskWrapperAsyncResult result = (TaskWrapperAsyncResult)actionDescriptor.BeginExecute(GetControllerContext(), parameters, callback: null, state: "state");
// Assert
Assert.Equal("state", result.AsyncState);
}
[Fact]
public void ExecuteTaskWithNullParameterAndTimeout()
{
// Arrange
TaskAsyncActionDescriptor actionDescriptor = GetActionDescriptor(GetExecuteControllerMethodInfo("TaskTimeoutWithNullParam"));
Dictionary<string, object> token = new Dictionary<string, object>()
{
{ "nullParam", null },
{ "cancellationToken", new CancellationToken() }
};
// Act & assert
Assert.Throws<TimeoutException>(
() => actionDescriptor.EndExecute(actionDescriptor.BeginExecute(GetControllerContext(0), parameters: token, callback: null, state: null)),
"The operation has timed out."
);
}
[Fact]
public void ExecuteWithInfiniteTimeout()
{
// Arrange
TaskAsyncActionDescriptor actionDescriptor = GetActionDescriptor(GetExecuteControllerMethodInfo("TaskWithInfiniteTimeout"));
ControllerContext controllerContext = GetControllerContext(Timeout.Infinite);
Dictionary<string, object> parameters = new Dictionary<string, object>()
{
{ "cancellationToken", new CancellationToken() }
};
// Act
object retVal = ExecuteHelper(actionDescriptor, parameters);
// Assert
Assert.Equal("Task Completed", retVal);
}
[Fact]
public void ExecuteTaskWithImmediateTimeout()
{
// Arrange
TaskAsyncActionDescriptor actionDescriptor = GetActionDescriptor(GetExecuteControllerMethodInfo("TaskTimeout"));
Dictionary<string, object> token = new Dictionary<string, object>()
{
{ "cancellationToken", new CancellationToken() }
};
// Act & assert
Assert.Throws<TimeoutException>(
() => actionDescriptor.EndExecute(actionDescriptor.BeginExecute(GetControllerContext(0), parameters: token, callback: null, state: null)),
"The operation has timed out."
);
}
[Fact]
public void ExecuteTaskWithTimeout()
{
// Arrange
TaskAsyncActionDescriptor actionDescriptor = GetActionDescriptor(GetExecuteControllerMethodInfo("TaskTimeout"));
Dictionary<string, object> token = new Dictionary<string, object>()
{
{ "cancellationToken", new CancellationToken() }
};
// Act & assert
Assert.Throws<TimeoutException>(
() => actionDescriptor.EndExecute(actionDescriptor.BeginExecute(GetControllerContext(2000), parameters: token, callback: null, state: null)),
"The operation has timed out."
);
}
[Fact]
public void SynchronousExecuteThrows()
{
// Arrange
TaskAsyncActionDescriptor actionDescriptor = GetActionDescriptor(GetExecuteControllerMethodInfo("SimpleTask"));
// Act & assert
Assert.Throws<InvalidOperationException>(
delegate { actionDescriptor.Execute(new ControllerContext(), new Dictionary<string, object>()); }, "The asynchronous action method 'someName' returns a Task, which cannot be executed synchronously.");
}
[Fact]
public void Execute_ThrowsIfControllerContextIsNull()
{
// Arrange
TaskAsyncActionDescriptor ad = GetActionDescriptor(_taskMethod);
// Act & assert
Assert.ThrowsArgumentNull(
delegate { ad.BeginExecute(null, new Dictionary<string, object>(), null, null); }, "controllerContext");
}
[Fact]
public void Execute_ThrowsIfControllerIsNotAsyncManagerContainer()
{
// Arrange
TaskAsyncActionDescriptor ad = GetActionDescriptor(_taskMethod);
ControllerContext controllerContext = new ControllerContext()
{
Controller = new RegularSyncController()
};
Dictionary<string, object> parameters = new Dictionary<string, object>()
{
{ "doWork", true }
};
// Act & assert
Assert.Throws<InvalidOperationException>(
delegate { ad.BeginExecute(controllerContext, parameters, null, null); },
@"The controller of type 'System.Web.Mvc.Async.Test.TaskAsyncActionDescriptorTest+RegularSyncController' must subclass AsyncController or implement the IAsyncManagerContainer interface.");
}
[Fact]
public void Execute_ThrowsIfParametersIsNull()
{
// Arrange
TaskAsyncActionDescriptor ad = GetActionDescriptor(_taskMethod);
// Act & assert
Assert.ThrowsArgumentNull(
delegate { ad.BeginExecute(new ControllerContext(), null, null, null); }, "parameters");
}
[Fact]
public void GetCustomAttributesCallsMethodInfoGetCustomAttributes()
{
// Arrange
object[] expected = new object[0];
Mock<MethodInfo> mockMethod = new Mock<MethodInfo>();
mockMethod.Setup(mi => mi.GetCustomAttributes(true)).Returns(expected);
TaskAsyncActionDescriptor ad = new TaskAsyncActionDescriptor(mockMethod.Object, "someName", new Mock<ControllerDescriptor>().Object, validateMethod: false)
{
DispatcherCache = new ActionMethodDispatcherCache()
};
// Act
object[] returned = ad.GetCustomAttributes(true);
// Assert
Assert.Same(expected, returned);
}
[Fact]
public void GetCustomAttributesWithAttributeTypeCallsMethodInfoGetCustomAttributes()
{
// Arrange
object[] expected = new object[0];
Mock<MethodInfo> mockMethod = new Mock<MethodInfo>();
mockMethod.Setup(mi => mi.GetCustomAttributes(typeof(ObsoleteAttribute), true)).Returns(expected);
TaskAsyncActionDescriptor ad = new TaskAsyncActionDescriptor(mockMethod.Object, "someName", new Mock<ControllerDescriptor>().Object, validateMethod: false)
{
DispatcherCache = new ActionMethodDispatcherCache()
};
// Act
object[] returned = ad.GetCustomAttributes(typeof(ObsoleteAttribute), true);
// Assert
Assert.Same(expected, returned);
}
[Fact]
public void GetParameters()
{
// Arrange
ParameterInfo pInfo = _taskMethod.GetParameters()[0];
TaskAsyncActionDescriptor ad = GetActionDescriptor(_taskMethod);
// Act
ParameterDescriptor[] pDescsFirstCall = ad.GetParameters();
ParameterDescriptor[] pDescsSecondCall = ad.GetParameters();
// Assert
Assert.NotSame(pDescsFirstCall, pDescsSecondCall); // Should get a new array every time
Assert.Equal(pDescsFirstCall, pDescsSecondCall);
Assert.Single(pDescsFirstCall);
ReflectedParameterDescriptor pDesc = pDescsFirstCall[0] as ReflectedParameterDescriptor;
Assert.NotNull(pDesc);
Assert.Same(ad, pDesc.ActionDescriptor);
Assert.Same(pInfo, pDesc.ParameterInfo);
}
[Fact]
public void GetSelectors()
{
// Arrange
ControllerContext controllerContext = new Mock<ControllerContext>().Object;
Mock<MethodInfo> mockMethod = new Mock<MethodInfo>();
Mock<ActionMethodSelectorAttribute> mockAttr = new Mock<ActionMethodSelectorAttribute>();
mockAttr.Setup(attr => attr.IsValidForRequest(controllerContext, mockMethod.Object)).Returns(true).Verifiable();
mockMethod.Setup(m => m.GetCustomAttributes(typeof(ActionMethodSelectorAttribute), true)).Returns(new ActionMethodSelectorAttribute[] { mockAttr.Object });
TaskAsyncActionDescriptor ad = new TaskAsyncActionDescriptor(mockMethod.Object, "someName", new Mock<ControllerDescriptor>().Object, validateMethod: false)
{
DispatcherCache = new ActionMethodDispatcherCache()
};
// Act
ICollection<ActionSelector> selectors = ad.GetSelectors();
bool executedSuccessfully = selectors.All(s => s(controllerContext));
// Assert
Assert.Single(selectors);
Assert.True(executedSuccessfully);
mockAttr.Verify();
}
[Fact]
public void IsDefined()
{
// Arrange
TaskAsyncActionDescriptor ad = GetActionDescriptor(_taskMethod);
// Act
bool isDefined = ad.IsDefined(typeof(AuthorizeAttribute), inherit: true);
// Assert
Assert.True(isDefined);
}
public static object ExecuteHelper(TaskAsyncActionDescriptor actionDescriptor, Dictionary<string, object> parameters, ControllerContext controllerContext = null)
{
SignalContainer<object> resultContainer = new SignalContainer<object>();
AsyncCallback callback = ar =>
{
object o = actionDescriptor.EndExecute(ar);
resultContainer.Signal(o);
};
actionDescriptor.BeginExecute(controllerContext ?? GetControllerContext(), parameters, callback, state: null);
return resultContainer.Wait();
}
private static TaskAsyncActionDescriptor GetActionDescriptor(MethodInfo taskMethod)
{
return new TaskAsyncActionDescriptor(taskMethod, "someName", new Mock<ControllerDescriptor>().Object)
{
DispatcherCache = new ActionMethodDispatcherCache()
};
}
private static ControllerContext GetControllerContext(int timeout = 45 * 1000)
{
Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();
ExecuteController controller = new ExecuteController();
controller.AsyncManager.Timeout = timeout;
mockControllerContext.Setup(c => c.Controller).Returns(controller);
return mockControllerContext.Object;
}
private static MethodInfo GetExecuteControllerMethodInfo(string methodName)
{
return typeof(ExecuteController).GetMethod(methodName);
}
private class ExecuteController : AsyncController
{
public bool WorkDone { get; set; }
public Task<ActionResult> ReturnedTask { get; set; }
public Task<string> GenericTask(string taskId)
{
return Task.Factory.StartNew(() => taskId);
}
public Task<string> GenericTaskException(string taskId, bool throwException)
{
return Task.Factory.StartNew(() =>
{
if (throwException)
{
ThrowException();
}
;
return taskId;
});
}
private void ThrowException()
{
throw new InvalidOperationException("Test exception from action");
}
[Authorize]
public Task SimpleTask(bool doWork)
{
return Task.Factory.StartNew(() => { WorkDone = doWork; });
}
public Task SimpleTaskException(bool doWork)
{
return Task.Factory.StartNew(() => { ThrowException(); });
}
public Task<ActionResult> TaskTimeoutWithNullParam(Object nullParam, CancellationToken cancellationToken)
{
return TaskTimeout(cancellationToken);
}
public Task<string> TaskWithInfiniteTimeout(CancellationToken cancellationToken)
{
return Task.Factory.StartNew(() => "Task Completed");
}
public Task<ActionResult> TaskTimeout(CancellationToken cancellationToken)
{
TaskCompletionSource<ActionResult> completionSource = new TaskCompletionSource<ActionResult>();
cancellationToken.Register(() => completionSource.TrySetCanceled());
ReturnedTask = completionSource.Task;
return ReturnedTask;
}
public Task TaskOfPrivateT()
{
var completionSource = new TaskCompletionSource<PrivateObject>();
completionSource.SetResult(new PrivateObject());
WorkDone = true;
return completionSource.Task;
}
private class PrivateObject
{
public override string ToString()
{
return "Private Object";
}
}
}
// Controller is async, so derive from ControllerBase to get sync behavior.
private class RegularSyncController : ControllerBase
{
protected override void ExecuteCore()
{
throw new NotImplementedException();
}
}
}
}
|