ThreadingTests.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Linq;
  3. using System.Runtime.CompilerServices;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using Avalonia.Threading;
  7. namespace Avalonia.Headless.UnitTests;
  8. public class ThreadingTests
  9. {
  10. #if NUNIT
  11. [AvaloniaTest, Timeout(10000)]
  12. #elif XUNIT
  13. [AvaloniaFact]
  14. #endif
  15. public void Should_Be_On_Dispatcher_Thread()
  16. {
  17. ValidateTestContext();
  18. Dispatcher.UIThread.VerifyAccess();
  19. }
  20. #if NUNIT
  21. [AvaloniaTest, Ignore("This test should always fail, enable to test if it fails")]
  22. #elif XUNIT
  23. [AvaloniaFact(Skip = "This test should always fail, enable to test if it fails")]
  24. #endif
  25. public void Should_Fail_Test_On_Delayed_Post_When_FlushDispatcher()
  26. {
  27. Dispatcher.UIThread.Post(() => throw new InvalidOperationException(), DispatcherPriority.Default);
  28. }
  29. #if NUNIT
  30. [AvaloniaTheory, Timeout(10000), TestCase(1), TestCase(10), TestCase(100)]
  31. #elif XUNIT
  32. [AvaloniaTheory(Timeout = 10000), InlineData(1), InlineData(10), InlineData(100)]
  33. #endif
  34. public async Task DispatcherTimer_Works_On_The_Same_Thread(int interval)
  35. {
  36. Assert.NotNull(SynchronizationContext.Current);
  37. ValidateTestContext();
  38. var currentThread = Thread.CurrentThread;
  39. await Task.Delay(100);
  40. ValidateTestContext();
  41. Assert.True(currentThread == Thread.CurrentThread);
  42. var tcs = new TaskCompletionSource();
  43. DispatcherTimer.RunOnce(() =>
  44. {
  45. try
  46. {
  47. ValidateTestContext();
  48. Assert.True(currentThread == Thread.CurrentThread);
  49. tcs.SetResult();
  50. }
  51. catch (Exception ex)
  52. {
  53. tcs.SetException(ex);
  54. }
  55. }, TimeSpan.FromTicks(interval));
  56. await tcs.Task;
  57. }
  58. private void ValidateTestContext([CallerMemberName] string runningMethodName = null)
  59. {
  60. #if NUNIT
  61. var testName = TestContext.CurrentContext.Test.Name;
  62. // Test.Name also includes parameters.
  63. Assert.AreEqual(testName.Split('(').First(), runningMethodName);
  64. #endif
  65. }
  66. }