IsolationTests.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System;
  2. using System.Reflection;
  3. using Avalonia.Threading;
  4. namespace Avalonia.Headless.UnitTests;
  5. public class IsolationTests
  6. {
  7. private static WeakReference<Application> s_previousAppRef;
  8. private static WeakReference<Dispatcher> s_previousDispatcherRef;
  9. #if NUNIT
  10. [AvaloniaTheory, Timeout(10000)]
  11. [TestCase(1), TestCase(2), TestCase(3)]
  12. #elif XUNIT
  13. [AvaloniaTheory]
  14. [InlineData(1), InlineData(2), InlineData(3)]
  15. [System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessage(
  16. "Usage",
  17. "xUnit1026:Theory methods should use all of their parameters",
  18. Justification = "Used to run the test several times with the proper isolation level")]
  19. #endif
  20. public void Application_Instance_Should_Match_Isolation_Level(int runIndex)
  21. {
  22. var currentApp = Application.Current;
  23. var currentDispatcher = Dispatcher.UIThread;
  24. if (s_previousAppRef is not null && s_previousDispatcherRef is not null)
  25. {
  26. var isolationLevel =
  27. GetType().Assembly.GetCustomAttribute<AvaloniaTestIsolationAttribute>()?.IsolationLevel ??
  28. AvaloniaTestIsolationLevel.PerTest;
  29. if (isolationLevel == AvaloniaTestIsolationLevel.PerTest)
  30. {
  31. GC.Collect();
  32. GC.WaitForPendingFinalizers();
  33. GC.Collect();
  34. Assert.False(s_previousAppRef.TryGetTarget(out var previousApp),
  35. "Previous Application instance should have been collected.");
  36. Assert.False(s_previousDispatcherRef.TryGetTarget(out var previousDispatcher),
  37. "Previous Dispatcher instance should have been collected.");
  38. Assert.False(previousApp == currentApp);
  39. Assert.False(previousDispatcher == currentDispatcher);
  40. }
  41. else if (isolationLevel == AvaloniaTestIsolationLevel.PerAssembly)
  42. {
  43. Assert.True(s_previousAppRef.TryGetTarget(out var previousApp),
  44. "Previous Application instance should still be alive.");
  45. Assert.True(s_previousDispatcherRef.TryGetTarget(out var previousDispatcher),
  46. "Previous Dispatcher instance should still be alive.");
  47. Assert.True(previousApp == currentApp);
  48. Assert.True(previousDispatcher == currentDispatcher);
  49. }
  50. else
  51. {
  52. throw new InvalidOperationException($"Unknown isolation level: {isolationLevel}");
  53. }
  54. }
  55. s_previousAppRef = new WeakReference<Application>(currentApp);
  56. s_previousDispatcherRef = new WeakReference<Dispatcher>(currentDispatcher);
  57. }
  58. }