BuildActionTaskBase.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using NUnit.Framework.Interfaces;
  6. using UnityEngine;
  7. using UnityEngine.TestTools.Logging;
  8. using UnityEngine.TestTools.TestRunner;
  9. namespace UnityEditor.TestTools.TestRunner.TestRun.Tasks
  10. {
  11. internal abstract class BuildActionTaskBase<T> : TestTaskBase
  12. {
  13. private string typeName;
  14. internal IAttributeFinder attributeFinder;
  15. internal RuntimePlatform targetPlatform = Application.platform;
  16. internal Action<string> logAction = Debug.Log;
  17. internal Func<ILogScope> logScopeProvider = () => new LogScope();
  18. internal Func<Type, object> createInstance = Activator.CreateInstance;
  19. protected BuildActionTaskBase(IAttributeFinder attributeFinder)
  20. {
  21. this.attributeFinder = attributeFinder;
  22. typeName = typeof(T).Name;
  23. }
  24. protected abstract void Action(T target);
  25. public override IEnumerator Execute(TestJobData testJobData)
  26. {
  27. if (testJobData.testTree == null)
  28. {
  29. throw new Exception($"Test tree is not available for {GetType().Name}.");
  30. }
  31. var enumerator = ExecuteMethods(testJobData.testTree, testJobData.executionSettings.BuildNUnitFilter());
  32. while (enumerator.MoveNext())
  33. {
  34. yield return null;
  35. }
  36. }
  37. protected IEnumerator ExecuteMethods(ITest testTree, ITestFilter testRunnerFilter)
  38. {
  39. var exceptions = new List<Exception>();
  40. foreach (var targetClassType in attributeFinder.Search(testTree, testRunnerFilter, targetPlatform))
  41. {
  42. try
  43. {
  44. var targetClass = (T) createInstance(targetClassType);
  45. logAction($"Executing {typeName} for: {targetClassType.FullName}.");
  46. using (var logScope = logScopeProvider())
  47. {
  48. Action(targetClass);
  49. if (logScope.AnyFailingLogs())
  50. {
  51. var failingLog = logScope.FailingLogs.First();
  52. throw new UnhandledLogMessageException(failingLog);
  53. }
  54. if (logScope.ExpectedLogs.Any())
  55. {
  56. var expectedLogs = logScope.ExpectedLogs.First();
  57. throw new UnexpectedLogMessageException(expectedLogs);
  58. }
  59. }
  60. }
  61. catch (Exception ex)
  62. {
  63. exceptions.Add(ex);
  64. }
  65. yield return null;
  66. }
  67. if (exceptions.Count > 0)
  68. {
  69. throw new AggregateException($"One or more exceptions when executing {typeName}.", exceptions);
  70. }
  71. }
  72. }
  73. }