ActionDelegator.cs
2.27 KB
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
using System;
using System.Linq;
using UnityEngine.TestRunner.NUnitExtensions.Runner;
using UnityEngine.TestTools.Logging;
using UnityEngine.TestTools.TestRunner;
namespace UnityEngine.TestTools.NUnitExtensions
{
/// <summary>
/// This class delegates actions from the NUnit thread that should be executed on the main thread.
/// NUnit thread calls Delegate which blocks the execution on the thread until the action is executed.
/// The main thread will poll for awaiting actions (HasAction) and invoke them (Execute).
/// Once the action is executed, the main thread releases the lock and executino on the NUnit thread is continued.
/// </summary>
internal class ActionDelegator : BaseDelegator
{
private Func<object> m_Action;
public object Delegate(Action action)
{
return Delegate(() => { action(); return null; });
}
public object Delegate(Func<object> action)
{
if (m_Aborted)
{
return null;
}
AssertState();
m_Context = UnityTestExecutionContext.CurrentContext;
m_Signal.Reset();
m_Action = action;
WaitForSignal();
return HandleResult();
}
private void AssertState()
{
if (m_Action != null)
{
throw new Exception("Action not executed yet");
}
}
public bool HasAction()
{
return m_Action != null;
}
public void Execute(LogScope logScope)
{
try
{
SetCurrentTestContext();
m_Result = m_Action();
if (logScope.AnyFailingLogs())
{
var failingLog = logScope.FailingLogs.First();
throw new UnhandledLogMessageException(failingLog);
}
if (logScope.ExpectedLogs.Any())
throw new UnexpectedLogMessageException(LogScope.Current.ExpectedLogs.Peek());
}
catch (Exception e)
{
m_Exception = e;
}
finally
{
m_Action = null;
m_Signal.Set();
}
}
}
}