Commit af571a61 authored by BlackAngle233's avatar BlackAngle233
Browse files

212

parent 1d9b5391
using System.Collections; using System.Collections;
using NUnit.Framework.Interfaces; using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal; using NUnit.Framework.Internal;
namespace UnityEngine.TestRunner.NUnitExtensions.Runner namespace UnityEngine.TestRunner.NUnitExtensions.Runner
{ {
internal abstract class WorkItemFactory internal abstract class WorkItemFactory
{ {
public UnityWorkItem Create(ITest loadedTest, ITestFilter filter) public UnityWorkItem Create(ITest loadedTest, ITestFilter filter)
{ {
TestSuite suite = loadedTest as TestSuite; TestSuite suite = loadedTest as TestSuite;
if (suite != null) if (suite != null)
{ {
return new CompositeWorkItem(suite, filter, this); return new CompositeWorkItem(suite, filter, this);
} }
var testMethod = (TestMethod)loadedTest; var testMethod = (TestMethod)loadedTest;
if (testMethod.Method.ReturnType.Type != typeof(IEnumerator)) if (testMethod.Method.ReturnType.Type != typeof(IEnumerator))
{ {
return new DefaultTestWorkItem(testMethod, filter); return new DefaultTestWorkItem(testMethod, filter);
} }
return Create(testMethod, filter, loadedTest); return Create(testMethod, filter, loadedTest);
} }
protected abstract UnityWorkItem Create(TestMethod method, ITestFilter filter, ITest loadedTest); protected abstract UnityWorkItem Create(TestMethod method, ITestFilter filter, ITest loadedTest);
} }
} }
fileFormatVersion: 2 fileFormatVersion: 2
guid: 5c15bf0966eb95847a4260d830a30d30 guid: 5c15bf0966eb95847a4260d830a30d30
MonoImporter: MonoImporter:
externalObjects: {} externalObjects: {}
serializedVersion: 2 serializedVersion: 2
defaultReferences: [] defaultReferences: []
executionOrder: 0 executionOrder: 0
icon: {instanceID: 0} icon: {instanceID: 0}
userData: userData:
assetBundleName: assetBundleName:
assetBundleVariant: assetBundleVariant:
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using NUnit.Framework.Interfaces; using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal; using NUnit.Framework.Internal;
using UnityEngine.TestRunner.NUnitExtensions.Filters; using UnityEngine.TestRunner.NUnitExtensions.Filters;
namespace UnityEngine.TestRunner.NUnitExtensions namespace UnityEngine.TestRunner.NUnitExtensions
{ {
internal static class TestExtensions internal static class TestExtensions
{ {
private static IEnumerable<string> GetTestCategories(this ITest test) private static IEnumerable<string> GetTestCategories(this ITest test)
{ {
var categories = test.Properties[PropertyNames.Category].Cast<string>().ToList(); var categories = test.Properties[PropertyNames.Category].Cast<string>().ToList();
if (categories.Count == 0 && test is TestMethod) if (categories.Count == 0 && test is TestMethod)
{ {
// only mark tests as Uncategorized if the test fixture doesn't have a category, // only mark tests as Uncategorized if the test fixture doesn't have a category,
// otherwise the test inherits the Fixture category // otherwise the test inherits the Fixture category
var fixtureCategories = test.Parent.Properties[PropertyNames.Category].Cast<string>().ToList(); var fixtureCategories = test.Parent.Properties[PropertyNames.Category].Cast<string>().ToList();
if (fixtureCategories.Count == 0) if (fixtureCategories.Count == 0)
categories.Add(CategoryFilterExtended.k_DefaultCategory); categories.Add(CategoryFilterExtended.k_DefaultCategory);
} }
return categories; return categories;
} }
public static bool HasCategory(this ITest test, string[] categoryFilter) public static bool HasCategory(this ITest test, string[] categoryFilter)
{ {
var categories = test.GetAllCategoriesFromTest().Distinct(); var categories = test.GetAllCategoriesFromTest().Distinct();
return categoryFilter.Any(c => categories.Any(r => r == c)); return categoryFilter.Any(c => categories.Any(r => r == c));
} }
public static List<string> GetAllCategoriesFromTest(this ITest test) public static List<string> GetAllCategoriesFromTest(this ITest test)
{ {
if (test.Parent == null) if (test.Parent == null)
return test.GetTestCategories().ToList(); return test.GetTestCategories().ToList();
var categories = GetAllCategoriesFromTest(test.Parent); var categories = GetAllCategoriesFromTest(test.Parent);
categories.AddRange(test.GetTestCategories()); categories.AddRange(test.GetTestCategories());
return categories; return categories;
} }
public static void ParseForNameDuplicates(this ITest test) public static void ParseForNameDuplicates(this ITest test)
{ {
var duplicates = new Dictionary<string, int>(); var duplicates = new Dictionary<string, int>();
for (var i = 0; i < test.Tests.Count; i++) for (var i = 0; i < test.Tests.Count; i++)
{ {
var child = test.Tests[i]; var child = test.Tests[i];
int count; int count;
if (duplicates.TryGetValue(child.FullName, out count)) if (duplicates.TryGetValue(child.FullName, out count))
{ {
count++; count++;
child.Properties.Add("childIndex", count); child.Properties.Add("childIndex", count);
duplicates[child.FullName] = count; duplicates[child.FullName] = count;
} }
else else
{ {
duplicates.Add(child.FullName, 1); duplicates.Add(child.FullName, 1);
} }
ParseForNameDuplicates(child); ParseForNameDuplicates(child);
} }
} }
public static int GetChildIndex(this ITest test) public static int GetChildIndex(this ITest test)
{ {
var index = test.Properties["childIndex"]; var index = test.Properties["childIndex"];
return (int)index[0]; return (int)index[0];
} }
public static bool HasChildIndex(this ITest test) public static bool HasChildIndex(this ITest test)
{ {
var index = test.Properties["childIndex"]; var index = test.Properties["childIndex"];
return index.Count > 0; return index.Count > 0;
} }
static string GetAncestorPath(ITest test) static string GetAncestorPath(ITest test)
{ {
var path = ""; var path = "";
var testParent = test.Parent; var testParent = test.Parent;
while (testParent != null && testParent.Parent != null && !string.IsNullOrEmpty(testParent.Name)) while (testParent != null && testParent.Parent != null && !string.IsNullOrEmpty(testParent.Name))
{ {
path = testParent.Name + "/" + path; path = testParent.Name + "/" + path;
testParent = testParent.Parent; testParent = testParent.Parent;
} }
return path; return path;
} }
public static string GetUniqueName(this ITest test) public static string GetUniqueName(this ITest test)
{ {
var id = GetAncestorPath(test) + GetFullName(test); var id = GetAncestorPath(test) + GetFullName(test);
if (test.HasChildIndex()) if (test.HasChildIndex())
{ {
var index = test.GetChildIndex(); var index = test.GetChildIndex();
if (index >= 0) if (index >= 0)
id += index; id += index;
} }
if (test.IsSuite) if (test.IsSuite)
{ {
id += "[suite]"; id += "[suite]";
} }
return id; return id;
} }
public static string GetFullName(ITest test) public static string GetFullName(ITest test)
{ {
var typeInfo = test.TypeInfo ?? test.Parent?.TypeInfo ?? test.Tests.FirstOrDefault()?.TypeInfo; var typeInfo = test.TypeInfo ?? test.Parent?.TypeInfo ?? test.Tests.FirstOrDefault()?.TypeInfo;
if (typeInfo == null) if (typeInfo == null)
{ {
return "[" + test.Name + "]"; return "[" + test.Name + "]";
} }
var assemblyId = typeInfo.Assembly.GetName().Name; var assemblyId = typeInfo.Assembly.GetName().Name;
if (assemblyId == test.Name) if (assemblyId == test.Name)
{ {
return $"[{test.Name}]"; return $"[{test.Name}]";
} }
return string.Format("[{0}][{1}]", assemblyId, test.FullName); return string.Format("[{0}][{1}]", assemblyId, test.FullName);
} }
public static string GetSkipReason(this ITest test) public static string GetSkipReason(this ITest test)
{ {
if (test.Properties.ContainsKey(PropertyNames.SkipReason)) if (test.Properties.ContainsKey(PropertyNames.SkipReason))
return (string)test.Properties.Get(PropertyNames.SkipReason); return (string)test.Properties.Get(PropertyNames.SkipReason);
return null; return null;
} }
public static string GetParentId(this ITest test) public static string GetParentId(this ITest test)
{ {
if (test.Parent != null) if (test.Parent != null)
return test.Parent.Id; return test.Parent.Id;
return null; return null;
} }
public static string GetParentFullName(this ITest test) public static string GetParentFullName(this ITest test)
{ {
if (test.Parent != null) if (test.Parent != null)
return test.Parent.FullName; return test.Parent.FullName;
return null; return null;
} }
public static string GetParentUniqueName(this ITest test) public static string GetParentUniqueName(this ITest test)
{ {
if (test.Parent != null) if (test.Parent != null)
return GetUniqueName(test.Parent); return GetUniqueName(test.Parent);
return null; return null;
} }
} }
} }
fileFormatVersion: 2 fileFormatVersion: 2
guid: 8bc74398aa3944646ade4ee78cd57484 guid: 8bc74398aa3944646ade4ee78cd57484
MonoImporter: MonoImporter:
externalObjects: {} externalObjects: {}
serializedVersion: 2 serializedVersion: 2
defaultReferences: [] defaultReferences: []
executionOrder: 0 executionOrder: 0
icon: {instanceID: 0} icon: {instanceID: 0}
userData: userData:
assetBundleName: assetBundleName:
assetBundleVariant: assetBundleVariant:
using System; using System;
using NUnit.Framework; using NUnit.Framework;
using NUnit.Framework.Interfaces; using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal; using NUnit.Framework.Internal;
namespace UnityEngine.TestRunner.NUnitExtensions namespace UnityEngine.TestRunner.NUnitExtensions
{ {
internal static class TestResultExtensions internal static class TestResultExtensions
{ {
public static void RecordPrefixedException(this TestResult testResult, string prefix, Exception ex, ResultState resultState = null) public static void RecordPrefixedException(this TestResult testResult, string prefix, Exception ex, ResultState resultState = null)
{ {
if (ex is NUnitException) if (ex is NUnitException)
{ {
ex = ex.InnerException; ex = ex.InnerException;
} }
if (resultState == null) if (resultState == null)
{ {
resultState = testResult.ResultState == ResultState.Cancelled resultState = testResult.ResultState == ResultState.Cancelled
? ResultState.Cancelled ? ResultState.Cancelled
: ResultState.Error; : ResultState.Error;
} }
var exceptionMessage = ExceptionHelper.BuildMessage(ex); var exceptionMessage = ExceptionHelper.BuildMessage(ex);
string stackTrace = "--" + prefix + NUnit.Env.NewLine + ExceptionHelper.BuildStackTrace(ex); string stackTrace = "--" + prefix + NUnit.Env.NewLine + ExceptionHelper.BuildStackTrace(ex);
if (testResult.StackTrace != null) if (testResult.StackTrace != null)
{ {
stackTrace = testResult.StackTrace + NUnit.Env.NewLine + stackTrace; stackTrace = testResult.StackTrace + NUnit.Env.NewLine + stackTrace;
} }
if (testResult.Test.IsSuite) if (testResult.Test.IsSuite)
{ {
resultState = resultState.WithSite(FailureSite.TearDown); resultState = resultState.WithSite(FailureSite.TearDown);
} }
if (ex is ResultStateException) if (ex is ResultStateException)
{ {
exceptionMessage = ex.Message; exceptionMessage = ex.Message;
resultState = ((ResultStateException)ex).ResultState; resultState = ((ResultStateException)ex).ResultState;
stackTrace = StackFilter.Filter(ex.StackTrace); stackTrace = StackFilter.Filter(ex.StackTrace);
} }
string message = (string.IsNullOrEmpty(prefix) ? "" : (prefix + " : ")) + exceptionMessage; string message = (string.IsNullOrEmpty(prefix) ? "" : (prefix + " : ")) + exceptionMessage;
if (testResult.Message != null) if (testResult.Message != null)
{ {
message = testResult.Message + NUnit.Env.NewLine + message; message = testResult.Message + NUnit.Env.NewLine + message;
} }
testResult.SetResult(resultState, message, stackTrace); testResult.SetResult(resultState, message, stackTrace);
} }
public static void RecordPrefixedError(this TestResult testResult, string prefix, string error, ResultState resultState = null) public static void RecordPrefixedError(this TestResult testResult, string prefix, string error, ResultState resultState = null)
{ {
if (resultState == null) if (resultState == null)
{ {
resultState = testResult.ResultState == ResultState.Cancelled resultState = testResult.ResultState == ResultState.Cancelled
? ResultState.Cancelled ? ResultState.Cancelled
: ResultState.Error; : ResultState.Error;
} }
if (testResult.Test.IsSuite) if (testResult.Test.IsSuite)
{ {
resultState = resultState.WithSite(FailureSite.TearDown); resultState = resultState.WithSite(FailureSite.TearDown);
} }
string message = (string.IsNullOrEmpty(prefix) ? "" : (prefix + " : ")) + error; string message = (string.IsNullOrEmpty(prefix) ? "" : (prefix + " : ")) + error;
if (testResult.Message != null) if (testResult.Message != null)
{ {
message = testResult.Message + NUnit.Env.NewLine + message; message = testResult.Message + NUnit.Env.NewLine + message;
} }
testResult.SetResult(resultState, message); testResult.SetResult(resultState, message);
} }
} }
} }
\ No newline at end of file
fileFormatVersion: 2 fileFormatVersion: 2
guid: 65fb6da362a78334ab360a125cfafdaf guid: 65fb6da362a78334ab360a125cfafdaf
MonoImporter: MonoImporter:
externalObjects: {} externalObjects: {}
serializedVersion: 2 serializedVersion: 2
defaultReferences: [] defaultReferences: []
executionOrder: 0 executionOrder: 0
icon: {instanceID: 0} icon: {instanceID: 0}
userData: userData:
assetBundleName: assetBundleName:
assetBundleVariant: assetBundleVariant:
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Reflection; using System.Reflection;
using NUnit; using NUnit;
using NUnit.Framework.Api; using NUnit.Framework.Api;
using NUnit.Framework.Interfaces; using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal; using NUnit.Framework.Internal;
namespace UnityEngine.TestTools.NUnitExtensions namespace UnityEngine.TestTools.NUnitExtensions
{ {
internal class UnityTestAssemblyBuilder : DefaultTestAssemblyBuilder, IAsyncTestAssemblyBuilder internal class UnityTestAssemblyBuilder : DefaultTestAssemblyBuilder, IAsyncTestAssemblyBuilder
{ {
private readonly string m_ProductName; private readonly string m_ProductName;
public UnityTestAssemblyBuilder() public UnityTestAssemblyBuilder()
{ {
m_ProductName = Application.productName; m_ProductName = Application.productName;
} }
public ITest Build(Assembly[] assemblies, TestPlatform[] testPlatforms, IDictionary<string, object> options) public ITest Build(Assembly[] assemblies, TestPlatform[] testPlatforms, IDictionary<string, object> options)
{ {
var test = BuildAsync(assemblies, testPlatforms, options); var test = BuildAsync(assemblies, testPlatforms, options);
while (test.MoveNext()) while (test.MoveNext())
{ {
} }
return test.Current; return test.Current;
} }
public IEnumerator<ITest> BuildAsync(Assembly[] assemblies, TestPlatform[] testPlatforms, IDictionary<string, object> options) public IEnumerator<ITest> BuildAsync(Assembly[] assemblies, TestPlatform[] testPlatforms, IDictionary<string, object> options)
{ {
var productName = string.Join("_", m_ProductName.Split(Path.GetInvalidFileNameChars())); var productName = string.Join("_", m_ProductName.Split(Path.GetInvalidFileNameChars()));
var suite = new TestSuite(productName); var suite = new TestSuite(productName);
for (var index = 0; index < assemblies.Length; index++) for (var index = 0; index < assemblies.Length; index++)
{ {
var assembly = assemblies[index]; var assembly = assemblies[index];
var platform = testPlatforms[index]; var platform = testPlatforms[index];
var assemblySuite = Build(assembly, options) as TestSuite; var assemblySuite = Build(assembly, options) as TestSuite;
if (assemblySuite != null && assemblySuite.HasChildren) if (assemblySuite != null && assemblySuite.HasChildren)
{ {
assemblySuite.Properties.Set("platform", platform); assemblySuite.Properties.Set("platform", platform);
suite.Add(assemblySuite); suite.Add(assemblySuite);
} }
yield return null; yield return null;
} }
yield return suite; yield return suite;
} }
public static Dictionary<string, object> GetNUnitTestBuilderSettings(TestPlatform testPlatform) public static Dictionary<string, object> GetNUnitTestBuilderSettings(TestPlatform testPlatform)
{ {
var emptySettings = new Dictionary<string, object>(); var emptySettings = new Dictionary<string, object>();
emptySettings.Add(FrameworkPackageSettings.TestParameters, "platform=" + testPlatform); emptySettings.Add(FrameworkPackageSettings.TestParameters, "platform=" + testPlatform);
return emptySettings; return emptySettings;
} }
} }
} }
fileFormatVersion: 2 fileFormatVersion: 2
guid: 98ba0396e4b4ee8498a8f097affcfddf guid: 98ba0396e4b4ee8498a8f097affcfddf
MonoImporter: MonoImporter:
externalObjects: {} externalObjects: {}
serializedVersion: 2 serializedVersion: 2
defaultReferences: [] defaultReferences: []
executionOrder: 0 executionOrder: 0
icon: {instanceID: 0} icon: {instanceID: 0}
userData: userData:
assetBundleName: assetBundleName:
assetBundleVariant: assetBundleVariant:
fileFormatVersion: 2 fileFormatVersion: 2
guid: 1ddb9e1c877ea80479d1eab4ddaa5d0d guid: 1ddb9e1c877ea80479d1eab4ddaa5d0d
folderAsset: yes folderAsset: yes
DefaultImporter: DefaultImporter:
externalObjects: {} externalObjects: {}
userData: userData:
assetBundleName: assetBundleName:
assetBundleVariant: assetBundleVariant:
fileFormatVersion: 2 fileFormatVersion: 2
guid: 61e236e8570a95e4eb754fb291e102e0 guid: 61e236e8570a95e4eb754fb291e102e0
folderAsset: yes folderAsset: yes
DefaultImporter: DefaultImporter:
externalObjects: {} externalObjects: {}
userData: userData:
assetBundleName: assetBundleName:
assetBundleVariant: assetBundleVariant:
using NUnit.Framework; using NUnit.Framework;
using NUnit.Framework.Interfaces; using NUnit.Framework.Interfaces;
namespace UnityEngine.TestTools.TestRunner.Callbacks namespace UnityEngine.TestTools.TestRunner.Callbacks
{ {
[AddComponentMenu("")] [AddComponentMenu("")]
internal class PlayModeRunnerCallback : MonoBehaviour, ITestRunnerListener internal class PlayModeRunnerCallback : MonoBehaviour, ITestRunnerListener
{ {
private TestResultRenderer m_ResultRenderer; private TestResultRenderer m_ResultRenderer;
public void RunFinished(ITestResult testResults) public void RunFinished(ITestResult testResults)
{ {
Application.logMessageReceivedThreaded -= LogRecieved; Application.logMessageReceivedThreaded -= LogRecieved;
if (Camera.main == null) if (Camera.main == null)
{ {
gameObject.AddComponent<Camera>(); gameObject.AddComponent<Camera>();
} }
m_ResultRenderer = new TestResultRenderer(testResults); m_ResultRenderer = new TestResultRenderer(testResults);
m_ResultRenderer.ShowResults(); m_ResultRenderer.ShowResults();
} }
public void TestFinished(ITestResult result) public void TestFinished(ITestResult result)
{ {
} }
public void OnGUI() public void OnGUI()
{ {
if (m_ResultRenderer != null) if (m_ResultRenderer != null)
m_ResultRenderer.Draw(); m_ResultRenderer.Draw();
} }
public void RunStarted(ITest testsToRun) public void RunStarted(ITest testsToRun)
{ {
Application.logMessageReceivedThreaded += LogRecieved; Application.logMessageReceivedThreaded += LogRecieved;
} }
public void TestStarted(ITest test) public void TestStarted(ITest test)
{ {
} }
private void LogRecieved(string message, string stacktrace, LogType type) private void LogRecieved(string message, string stacktrace, LogType type)
{ {
if (TestContext.Out != null) if (TestContext.Out != null)
TestContext.Out.WriteLine(message); TestContext.Out.WriteLine(message);
} }
} }
} }
fileFormatVersion: 2 fileFormatVersion: 2
guid: 3cf5cb9e1ef590c48b1f919f2a7bd895 guid: 3cf5cb9e1ef590c48b1f919f2a7bd895
MonoImporter: MonoImporter:
externalObjects: {} externalObjects: {}
serializedVersion: 2 serializedVersion: 2
defaultReferences: [] defaultReferences: []
executionOrder: 0 executionOrder: 0
icon: {instanceID: 0} icon: {instanceID: 0}
userData: userData:
assetBundleName: assetBundleName:
assetBundleVariant: assetBundleVariant:
using NUnit.Framework.Interfaces; using NUnit.Framework.Interfaces;
using UnityEngine.Networking.PlayerConnection; using UnityEngine.Networking.PlayerConnection;
using UnityEngine.TestRunner.TestLaunchers; using UnityEngine.TestRunner.TestLaunchers;
namespace UnityEngine.TestTools.TestRunner.Callbacks namespace UnityEngine.TestTools.TestRunner.Callbacks
{ {
internal class PlayerQuitHandler : MonoBehaviour, ITestRunnerListener internal class PlayerQuitHandler : MonoBehaviour, ITestRunnerListener
{ {
public void Start() public void Start()
{ {
PlayerConnection.instance.Register(PlayerConnectionMessageIds.quitPlayerMessageId, ProcessPlayerQuiteMessage); PlayerConnection.instance.Register(PlayerConnectionMessageIds.quitPlayerMessageId, ProcessPlayerQuiteMessage);
} }
private void ProcessPlayerQuiteMessage(MessageEventArgs arg0) private void ProcessPlayerQuiteMessage(MessageEventArgs arg0)
{ {
//Some platforms don't quit, so we need to disconnect to make sure they will not connect to another editor instance automatically. //Some platforms don't quit, so we need to disconnect to make sure they will not connect to another editor instance automatically.
PlayerConnection.instance.DisconnectAll(); PlayerConnection.instance.DisconnectAll();
//XBOX has an error when quitting //XBOX has an error when quitting
if (Application.platform == RuntimePlatform.XboxOne) if (Application.platform == RuntimePlatform.XboxOne)
{ {
return; return;
} }
Application.Quit(); Application.Quit();
} }
public void RunStarted(ITest testsToRun) public void RunStarted(ITest testsToRun)
{ {
} }
public void RunFinished(ITestResult testResults) public void RunFinished(ITestResult testResults)
{ {
} }
public void TestStarted(ITest test) public void TestStarted(ITest test)
{ {
} }
public void TestFinished(ITestResult result) public void TestFinished(ITestResult result)
{ {
} }
} }
} }
fileFormatVersion: 2 fileFormatVersion: 2
guid: f8ed0b11850145c4995dd76170bb2500 guid: f8ed0b11850145c4995dd76170bb2500
MonoImporter: MonoImporter:
externalObjects: {} externalObjects: {}
serializedVersion: 2 serializedVersion: 2
defaultReferences: [] defaultReferences: []
executionOrder: 0 executionOrder: 0
icon: {instanceID: 0} icon: {instanceID: 0}
userData: userData:
assetBundleName: assetBundleName:
assetBundleVariant: assetBundleVariant:
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using NUnit.Framework.Interfaces; using NUnit.Framework.Interfaces;
using UnityEngine.Networking.PlayerConnection; using UnityEngine.Networking.PlayerConnection;
using UnityEngine.TestRunner.TestLaunchers; using UnityEngine.TestRunner.TestLaunchers;
namespace UnityEngine.TestTools.TestRunner.Callbacks namespace UnityEngine.TestTools.TestRunner.Callbacks
{ {
[AddComponentMenu("")] [AddComponentMenu("")]
internal class RemoteTestResultSender : MonoBehaviour, ITestRunnerListener internal class RemoteTestResultSender : MonoBehaviour, ITestRunnerListener
{ {
private class QueueData private class QueueData
{ {
public Guid id { get; set; } public Guid id { get; set; }
public byte[] data { get; set; } public byte[] data { get; set; }
} }
private const int k_aliveMessageFrequency = 120; private const int k_aliveMessageFrequency = 120;
private float m_NextliveMessage = k_aliveMessageFrequency; private float m_NextliveMessage = k_aliveMessageFrequency;
private readonly Queue<QueueData> m_SendQueue = new Queue<QueueData>(); private readonly Queue<QueueData> m_SendQueue = new Queue<QueueData>();
private readonly object m_LockQueue = new object(); private readonly object m_LockQueue = new object();
private readonly IRemoteTestResultDataFactory m_TestResultDataFactory = new RemoteTestResultDataFactory(); private readonly IRemoteTestResultDataFactory m_TestResultDataFactory = new RemoteTestResultDataFactory();
public void Start() public void Start()
{ {
StartCoroutine(SendDataRoutine()); StartCoroutine(SendDataRoutine());
} }
private byte[] SerializeObject(object objectToSerialize) private byte[] SerializeObject(object objectToSerialize)
{ {
return Encoding.UTF8.GetBytes(JsonUtility.ToJson(objectToSerialize)); return Encoding.UTF8.GetBytes(JsonUtility.ToJson(objectToSerialize));
} }
public void RunStarted(ITest testsToRun) public void RunStarted(ITest testsToRun)
{ {
var data = SerializeObject(m_TestResultDataFactory.CreateFromTest(testsToRun)); var data = SerializeObject(m_TestResultDataFactory.CreateFromTest(testsToRun));
lock (m_LockQueue) lock (m_LockQueue)
{ {
m_SendQueue.Enqueue(new QueueData m_SendQueue.Enqueue(new QueueData
{ {
id = PlayerConnectionMessageIds.runStartedMessageId, id = PlayerConnectionMessageIds.runStartedMessageId,
data = data data = data
}); });
} }
} }
public void RunFinished(ITestResult testResults) public void RunFinished(ITestResult testResults)
{ {
var data = SerializeObject(m_TestResultDataFactory.CreateFromTestResult(testResults)); var data = SerializeObject(m_TestResultDataFactory.CreateFromTestResult(testResults));
lock (m_LockQueue) lock (m_LockQueue)
{ {
m_SendQueue.Enqueue(new QueueData { id = PlayerConnectionMessageIds.runFinishedMessageId, data = data, }); m_SendQueue.Enqueue(new QueueData { id = PlayerConnectionMessageIds.runFinishedMessageId, data = data, });
} }
} }
public void TestStarted(ITest test) public void TestStarted(ITest test)
{ {
var data = SerializeObject(m_TestResultDataFactory.CreateFromTest(test)); var data = SerializeObject(m_TestResultDataFactory.CreateFromTest(test));
lock (m_LockQueue) lock (m_LockQueue)
{ {
m_SendQueue.Enqueue(new QueueData m_SendQueue.Enqueue(new QueueData
{ {
id = PlayerConnectionMessageIds.testStartedMessageId, id = PlayerConnectionMessageIds.testStartedMessageId,
data = data data = data
}); });
} }
} }
public void TestFinished(ITestResult result) public void TestFinished(ITestResult result)
{ {
var testRunnerResultForApi = m_TestResultDataFactory.CreateFromTestResult(result); var testRunnerResultForApi = m_TestResultDataFactory.CreateFromTestResult(result);
var resultData = SerializeObject(testRunnerResultForApi); var resultData = SerializeObject(testRunnerResultForApi);
lock (m_LockQueue) lock (m_LockQueue)
{ {
m_SendQueue.Enqueue(new QueueData m_SendQueue.Enqueue(new QueueData
{ {
id = PlayerConnectionMessageIds.testFinishedMessageId, id = PlayerConnectionMessageIds.testFinishedMessageId,
data = resultData, data = resultData,
}); });
} }
} }
public IEnumerator SendDataRoutine() public IEnumerator SendDataRoutine()
{ {
while (!PlayerConnection.instance.isConnected) while (!PlayerConnection.instance.isConnected)
{ {
yield return new WaitForSeconds(1); yield return new WaitForSeconds(1);
} }
while (true) while (true)
{ {
lock (m_LockQueue) lock (m_LockQueue)
{ {
if (PlayerConnection.instance.isConnected && m_SendQueue.Count > 0) if (PlayerConnection.instance.isConnected && m_SendQueue.Count > 0)
{ {
ResetNextPlayerAliveMessageTime(); ResetNextPlayerAliveMessageTime();
var queueData = m_SendQueue.Dequeue(); var queueData = m_SendQueue.Dequeue();
PlayerConnection.instance.Send(queueData.id, queueData.data); PlayerConnection.instance.Send(queueData.id, queueData.data);
yield return null; yield return null;
} }
//This is needed so we dont stall the player totally //This is needed so we dont stall the player totally
if (!m_SendQueue.Any()) if (!m_SendQueue.Any())
{ {
SendAliveMessageIfNeeded(); SendAliveMessageIfNeeded();
yield return new WaitForSeconds(0.02f); yield return new WaitForSeconds(0.02f);
} }
} }
} }
} }
private void SendAliveMessageIfNeeded() private void SendAliveMessageIfNeeded()
{ {
if (Time.timeSinceLevelLoad < m_NextliveMessage) if (Time.timeSinceLevelLoad < m_NextliveMessage)
{ {
return; return;
} }
Debug.Log("Sending player alive message back to editor."); Debug.Log("Sending player alive message back to editor.");
ResetNextPlayerAliveMessageTime(); ResetNextPlayerAliveMessageTime();
PlayerConnection.instance.Send(PlayerConnectionMessageIds.playerAliveHeartbeat, new byte[0]); PlayerConnection.instance.Send(PlayerConnectionMessageIds.playerAliveHeartbeat, new byte[0]);
} }
private void ResetNextPlayerAliveMessageTime() private void ResetNextPlayerAliveMessageTime()
{ {
m_NextliveMessage = Time.timeSinceLevelLoad + k_aliveMessageFrequency; m_NextliveMessage = Time.timeSinceLevelLoad + k_aliveMessageFrequency;
} }
} }
} }
fileFormatVersion: 2 fileFormatVersion: 2
guid: 20793418366caf14293b29c55df5e9ec guid: 20793418366caf14293b29c55df5e9ec
MonoImporter: MonoImporter:
externalObjects: {} externalObjects: {}
serializedVersion: 2 serializedVersion: 2
defaultReferences: [] defaultReferences: []
executionOrder: 0 executionOrder: 0
icon: {instanceID: 0} icon: {instanceID: 0}
userData: userData:
assetBundleName: assetBundleName:
assetBundleVariant: assetBundleVariant:
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using NUnit.Framework.Interfaces; using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal; using NUnit.Framework.Internal;
namespace UnityEngine.TestTools.TestRunner.Callbacks namespace UnityEngine.TestTools.TestRunner.Callbacks
{ {
internal class TestResultRenderer internal class TestResultRenderer
{ {
private static class Styles private static class Styles
{ {
public static readonly GUIStyle SucceedLabelStyle; public static readonly GUIStyle SucceedLabelStyle;
public static readonly GUIStyle FailedLabelStyle; public static readonly GUIStyle FailedLabelStyle;
public static readonly GUIStyle FailedMessagesStyle; public static readonly GUIStyle FailedMessagesStyle;
static Styles() static Styles()
{ {
SucceedLabelStyle = new GUIStyle("label"); SucceedLabelStyle = new GUIStyle("label");
SucceedLabelStyle.normal.textColor = Color.green; SucceedLabelStyle.normal.textColor = Color.green;
SucceedLabelStyle.fontSize = 48; SucceedLabelStyle.fontSize = 48;
FailedLabelStyle = new GUIStyle("label"); FailedLabelStyle = new GUIStyle("label");
FailedLabelStyle.normal.textColor = Color.red; FailedLabelStyle.normal.textColor = Color.red;
FailedLabelStyle.fontSize = 32; FailedLabelStyle.fontSize = 32;
FailedMessagesStyle = new GUIStyle("label"); FailedMessagesStyle = new GUIStyle("label");
FailedMessagesStyle.wordWrap = false; FailedMessagesStyle.wordWrap = false;
FailedMessagesStyle.richText = true; FailedMessagesStyle.richText = true;
} }
} }
private readonly List<ITestResult> m_FailedTestCollection; private readonly List<ITestResult> m_FailedTestCollection;
private bool m_ShowResults; private bool m_ShowResults;
private Vector2 m_ScrollPosition; private Vector2 m_ScrollPosition;
public TestResultRenderer(ITestResult testResults) public TestResultRenderer(ITestResult testResults)
{ {
m_FailedTestCollection = new List<ITestResult>(); m_FailedTestCollection = new List<ITestResult>();
GetFailedTests(testResults); GetFailedTests(testResults);
} }
private void GetFailedTests(ITestResult testResults) private void GetFailedTests(ITestResult testResults)
{ {
if (testResults is TestCaseResult) if (testResults is TestCaseResult)
{ {
if (testResults.ResultState.Status == TestStatus.Failed) if (testResults.ResultState.Status == TestStatus.Failed)
m_FailedTestCollection.Add(testResults); m_FailedTestCollection.Add(testResults);
} }
else if (testResults.HasChildren) else if (testResults.HasChildren)
{ {
foreach (var testResultsChild in testResults.Children) foreach (var testResultsChild in testResults.Children)
{ {
GetFailedTests(testResultsChild); GetFailedTests(testResultsChild);
} }
} }
} }
private const int k_MaxStringLength = 15000; private const int k_MaxStringLength = 15000;
public void ShowResults() public void ShowResults()
{ {
m_ShowResults = true; m_ShowResults = true;
Cursor.visible = true; Cursor.visible = true;
} }
public void Draw() public void Draw()
{ {
if (!m_ShowResults) return; if (!m_ShowResults) return;
if (m_FailedTestCollection.Count == 0) if (m_FailedTestCollection.Count == 0)
{ {
GUILayout.Label("All test(s) succeeded", Styles.SucceedLabelStyle, GUILayout.Width(600)); GUILayout.Label("All test(s) succeeded", Styles.SucceedLabelStyle, GUILayout.Width(600));
} }
else else
{ {
int count = m_FailedTestCollection.Count; int count = m_FailedTestCollection.Count;
GUILayout.Label(count + " tests failed!", Styles.FailedLabelStyle); GUILayout.Label(count + " tests failed!", Styles.FailedLabelStyle);
m_ScrollPosition = GUILayout.BeginScrollView(m_ScrollPosition, GUILayout.ExpandWidth(true)); m_ScrollPosition = GUILayout.BeginScrollView(m_ScrollPosition, GUILayout.ExpandWidth(true));
var text = ""; var text = "";
text += "<b><size=18>Code-based tests</size></b>\n"; text += "<b><size=18>Code-based tests</size></b>\n";
text += string.Join("\n", m_FailedTestCollection text += string.Join("\n", m_FailedTestCollection
.Select(result => result.Name + " " + result.ResultState + "\n" + result.Message) .Select(result => result.Name + " " + result.ResultState + "\n" + result.Message)
.ToArray()); .ToArray());
if (text.Length > k_MaxStringLength) if (text.Length > k_MaxStringLength)
text = text.Substring(0, k_MaxStringLength); text = text.Substring(0, k_MaxStringLength);
GUILayout.TextArea(text, Styles.FailedMessagesStyle); GUILayout.TextArea(text, Styles.FailedMessagesStyle);
GUILayout.EndScrollView(); GUILayout.EndScrollView();
} }
if (GUILayout.Button("Close")) if (GUILayout.Button("Close"))
Application.Quit(); Application.Quit();
} }
} }
} }
fileFormatVersion: 2 fileFormatVersion: 2
guid: 5ebb87899ca30b743bb4274bc00c02b4 guid: 5ebb87899ca30b743bb4274bc00c02b4
MonoImporter: MonoImporter:
externalObjects: {} externalObjects: {}
serializedVersion: 2 serializedVersion: 2
defaultReferences: [] defaultReferences: []
executionOrder: 0 executionOrder: 0
icon: {instanceID: 0} icon: {instanceID: 0}
userData: userData:
assetBundleName: assetBundleName:
assetBundleVariant: assetBundleVariant:
using NUnit.Framework.Interfaces; using NUnit.Framework.Interfaces;
namespace UnityEngine.TestTools.TestRunner.Callbacks namespace UnityEngine.TestTools.TestRunner.Callbacks
{ {
internal class TestResultRendererCallback : MonoBehaviour, ITestRunnerListener internal class TestResultRendererCallback : MonoBehaviour, ITestRunnerListener
{ {
private TestResultRenderer m_ResultRenderer; private TestResultRenderer m_ResultRenderer;
public void RunStarted(ITest testsToRun) public void RunStarted(ITest testsToRun)
{ {
} }
public void RunFinished(ITestResult testResults) public void RunFinished(ITestResult testResults)
{ {
if (Camera.main == null) if (Camera.main == null)
{ {
gameObject.AddComponent<Camera>(); gameObject.AddComponent<Camera>();
} }
m_ResultRenderer = new TestResultRenderer(testResults); m_ResultRenderer = new TestResultRenderer(testResults);
m_ResultRenderer.ShowResults(); m_ResultRenderer.ShowResults();
} }
public void OnGUI() public void OnGUI()
{ {
if (m_ResultRenderer != null) if (m_ResultRenderer != null)
m_ResultRenderer.Draw(); m_ResultRenderer.Draw();
} }
public void TestStarted(ITest test) public void TestStarted(ITest test)
{ {
} }
public void TestFinished(ITestResult result) public void TestFinished(ITestResult result)
{ {
} }
} }
} }
fileFormatVersion: 2 fileFormatVersion: 2
guid: dfc336f10b83bd74eaded16a658275c7 guid: dfc336f10b83bd74eaded16a658275c7
MonoImporter: MonoImporter:
externalObjects: {} externalObjects: {}
serializedVersion: 2 serializedVersion: 2
defaultReferences: [] defaultReferences: []
executionOrder: 0 executionOrder: 0
icon: {instanceID: 0} icon: {instanceID: 0}
userData: userData:
assetBundleName: assetBundleName:
assetBundleVariant: assetBundleVariant:
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment