ThreadPrincipalTests.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. using NUnit.Framework;
  5. using System.Security;
  6. using System.Security.Permissions;
  7. using System.Security.Principal;
  8. namespace MonoTests.System.Threading.Tasks
  9. {
  10. [TestFixture]
  11. public class ThreadPrincipalTests
  12. {
  13. [Test]
  14. public void PrincipalFlowsToAsyncTask ()
  15. {
  16. var t = _PrincipalFlowsToAsyncTask();
  17. t.GetAwaiter().GetResult();
  18. }
  19. public async Task _PrincipalFlowsToAsyncTask ()
  20. {
  21. var mockIdentity = new MockIdentity {
  22. AuthenticationType = "authtype",
  23. IsAuthenticated = true,
  24. Name = "name"
  25. };
  26. var mockPrincipal = new MockPrincipal {
  27. Identity = mockIdentity
  28. };
  29. var oldPrincipal = Thread.CurrentPrincipal;
  30. Thread.CurrentPrincipal = mockPrincipal;
  31. try {
  32. await Task.Factory.StartNew(async () =>
  33. {
  34. var newThreadId = Thread.CurrentThread.ManagedThreadId; // on different thread.
  35. Assert.IsTrue(Thread.CurrentPrincipal.Identity.IsAuthenticated);
  36. Assert.AreEqual(mockPrincipal, Thread.CurrentPrincipal);
  37. await Task.Factory.StartNew(() =>
  38. {
  39. // still works even when nesting..
  40. newThreadId = Thread.CurrentThread.ManagedThreadId;
  41. Assert.IsTrue(Thread.CurrentPrincipal.Identity.IsAuthenticated);
  42. Assert.AreEqual(mockPrincipal, Thread.CurrentPrincipal);
  43. }, TaskCreationOptions.LongRunning);
  44. }, TaskCreationOptions.LongRunning);
  45. await Task.Run(() =>
  46. {
  47. // Following works on NET4.7 and fails under Xamarin.Android.
  48. var newThreadId = Thread.CurrentThread.ManagedThreadId;
  49. Assert.IsTrue(Thread.CurrentPrincipal.Identity.IsAuthenticated);
  50. Assert.AreEqual(mockPrincipal, Thread.CurrentPrincipal);
  51. });
  52. } finally {
  53. Thread.CurrentPrincipal = oldPrincipal;
  54. }
  55. }
  56. }
  57. public class MockPrincipal : IPrincipal {
  58. public IIdentity Identity { get; set; }
  59. public bool IsInRole (string role) {
  60. return true;
  61. }
  62. }
  63. public class MockIdentity : IIdentity {
  64. public string AuthenticationType { get; set; }
  65. public bool IsAuthenticated { get; set; }
  66. public string Name { get; set; }
  67. }
  68. }