Unity-jump-proj

This commit is contained in:
2024-09-09 11:07:16 +03:00
parent 2c29906bbf
commit fd96a5627d
13707 changed files with 866380 additions and 0 deletions

View File

@ -0,0 +1,34 @@
#if TEST_FRAMEWORK
using System;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEditor;
namespace Packages.Rider.Editor.UnitTesting
{
internal class CallbackData : ScriptableSingleton<CallbackData>
{
/// <summary>
/// identifies that tests were started from Rider
/// </summary>
public bool isRider;
[UsedImplicitly] // Is used by Rider Unity plugin by reflection
public static event EventHandler Changed = (sender, args) => { };
internal void RaiseChangedEvent()
{
Changed(null, EventArgs.Empty);
}
[UsedImplicitly] // Is used by Rider Unity plugin by reflection
public List<TestEvent> events = new List<TestEvent>();
[UsedImplicitly] // Is used by Rider Unity plugin by reflection
public void Clear()
{
events.Clear();
}
}
}
#endif

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 010246a07de7cb34185a2a7b1c1fad59
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,18 @@
#if TEST_FRAMEWORK
using UnityEditor;
using UnityEditor.TestTools.TestRunner.Api;
using UnityEngine;
namespace Packages.Rider.Editor.UnitTesting
{
[InitializeOnLoad]
internal static class CallbackInitializer
{
static CallbackInitializer()
{
if (CallbackData.instance.isRider)
ScriptableObject.CreateInstance<TestRunnerApi>().RegisterCallbacks(ScriptableObject.CreateInstance<TestsCallback>(), 0);
}
}
}
#endif

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: aa1c6b1a353ab464782fc1e7c051eb02
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,129 @@
using JetBrains.Annotations;
using UnityEngine;
#if TEST_FRAMEWORK
using System.IO;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEditor.TestTools.TestRunner.Api;
#else
using System;
#endif
namespace Packages.Rider.Editor.UnitTesting
{
/// <summary>
/// Is called by Rider Unity plugin via reflections
/// </summary>
[UsedImplicitly]
public static class RiderTestRunner
{
#if TEST_FRAMEWORK
private static readonly TestsCallback Callback = ScriptableObject.CreateInstance<TestsCallback>();
private static string _sessionGuid;
#endif
/// <summary>
/// Is called by Rider Unity plugin via reflections
/// </summary>
/// <param name="sessionId"></param>
/// <param name="testMode"></param>
/// <param name="assemblyNames"></param>
/// <param name="testNames"></param>
/// <param name="categoryNames"></param>
/// <param name="groupNames"></param>
/// <param name="buildTarget"></param>
/// <param name="callbacksHandlerCodeBase"></param>
/// <param name="callbacksHandlerTypeName"></param>
/// <param name="callbacksHandlerDependencies"></param>
[UsedImplicitly]
public static void RunTestsWithSyncCallbacks(string sessionId, int testMode, string[] assemblyNames,
string[] testNames, string[] categoryNames, string[] groupNames, int? buildTarget,
string callbacksHandlerCodeBase, string callbacksHandlerTypeName, string[] callbacksHandlerDependencies)
{
#if !TEST_FRAMEWORK
Debug.LogError("Update Test Framework package to v.1.1.8+ to run tests from Rider.");
throw new NotSupportedException("Incompatible `Test Framework` package in Unity. Update to v.1.1.8+");
#else
SyncTestRunEventsHandler.instance.InitRun(sessionId, callbacksHandlerCodeBase, callbacksHandlerTypeName, callbacksHandlerDependencies);
RunTests(testMode, assemblyNames, testNames, categoryNames, groupNames, buildTarget);
#endif
}
/// <summary>
/// Is called by Rider Unity plugin via reflections
/// </summary>
/// <param name="testMode"></param>
/// <param name="assemblyNames"></param>
/// <param name="testNames"></param>
/// <param name="categoryNames"></param>
/// <param name="groupNames"></param>
/// <param name="buildTarget"></param>
[UsedImplicitly]
public static void RunTests(int testMode, string[] assemblyNames, string[] testNames, string[] categoryNames, string[] groupNames, int? buildTarget)
{
#if !TEST_FRAMEWORK
Debug.LogError("Update Test Framework package to v.1.1.8+ to run tests from Rider.");
throw new NotSupportedException("Incompatible `Test Framework` package in Unity. Update to v.1.1.8+");
#else
CallbackData.instance.isRider = true;
var api = ScriptableObject.CreateInstance<TestRunnerApi>();
var settings = new ExecutionSettings();
var filter = new Filter
{
assemblyNames = assemblyNames,
testNames = testNames,
categoryNames = categoryNames,
groupNames = groupNames,
targetPlatform = (BuildTarget?) buildTarget
};
if (testMode > 0) // for future use - test-framework would allow running both Edit and Play test at once
{
filter.testMode = (TestMode) testMode;
}
api.RetrieveTestList(filter.testMode, adaptor =>
{
// start tests if there any, otherwise send a RunFinished signal // see RIDER-91705
if (adaptor.Children.Any(a => a.IsTestAssembly && assemblyNames.Contains(Path.GetFileNameWithoutExtension(a.Name))))
{
settings.filters = new[]
{
filter
};
_sessionGuid = api.Execute(settings);
api.UnregisterCallbacks(Callback); // avoid multiple registrations
api.RegisterCallbacks(Callback); // receive information about when the test suite and individual tests starts and stops.
}
else
{
CallbackData.instance.isRider = false;
CallbackData.instance.events.Add(
new TestEvent(EventType.RunFinished, "", "", "", 0, NUnit.Framework.Interfaces.TestStatus.Inconclusive, ""));
CallbackData.instance.RaiseChangedEvent();
}
});
#endif
}
[UsedImplicitly]
internal static void CancelTestRun()
{
#if !TEST_FRAMEWORK
Debug.LogError("Update Test Framework package to v.1.1.8+ to run tests from Rider.");
throw new NotSupportedException("Incompatible `Test Framework` package in Unity. Update to v.1.1.8+");
#else
var methodInfo = typeof(TestRunnerApi).GetMethod("CancelTestRun");
if (methodInfo == null)
methodInfo = typeof(TestRunnerApi).GetMethod("CancelTestRun", BindingFlags.Static | BindingFlags.NonPublic);
methodInfo.Invoke(null, new object[] { _sessionGuid });
#endif
}
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5c3b27069cb3ddf42ba1260eeefcdd1c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,49 @@
#if TEST_FRAMEWORK
using NUnit.Framework.Interfaces;
using Packages.Rider.Editor.UnitTesting;
using UnityEngine.TestRunner;
[assembly: TestRunCallback(typeof(SyncTestRunCallback))]
namespace Packages.Rider.Editor.UnitTesting
{
internal class SyncTestRunCallback : ITestRunCallback
{
public void RunStarted(ITest testsToRun)
{
}
public void RunFinished(ITestResult testResults)
{
SyncTestRunEventsHandler.instance.OnRunFinished();
}
public void TestStarted(ITest test)
{
if (!test.IsSuite)
SyncTestRunEventsHandler.instance.OnTestStarted(GenerateId(test));
}
public void TestFinished(ITestResult result)
{
if (!result.Test.IsSuite)
SyncTestRunEventsHandler.instance.OnTestFinished();
}
// https://jetbrains.team/p/net/code/dotnet-libs/files/f04cde7d1dd70ee13bf5532e30f929b9b5ed08a4/ReSharperTestRunner/src/Adapters/TestRunner.Adapters.NUnit3/RemoteTaskDepot.cs?tab=source&line=129
private static string GenerateId(ITest node)
{
// ES: Parameterized tests defined in a parametrized test fixture, though
// constructed for a particular test fixture with the given parameter, have identical fullname that does
// not include parameters of parent testfixture (name of the without parameters is used instead).
// This leads to 'Test with {id} id is already running' message.
var typeName = node.GetType().Name;
if (typeName == "ParameterizedMethod" ||
typeName == "GenericMethod")
return $"{node.Parent.FullName}.{node.Name}";
return node.FullName;
}
}
}
#endif

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 58ab3828fb407c742a48b82bc5983a87
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,148 @@
#if TEST_FRAMEWORK
using System;
using System.Reflection;
using UnityEditor;
using UnityEngine;
namespace Packages.Rider.Editor.UnitTesting
{
internal class SyncTestRunEventsHandler : ScriptableSingleton<SyncTestRunEventsHandler>
{
[SerializeField] private string m_SessionId;
[SerializeField] private string m_HandlerCodeBase;
[SerializeField] private string m_HandlerTypeName;
[SerializeField] private string[] m_HandlerDependencies;
[SerializeField] private bool m_RunInitialized;
private object m_Handler;
private MethodInfo m_OnSessionStartedMethodInfo;
private MethodInfo m_OnTestStartedMethodInfo;
private MethodInfo m_OnTestFinishedMethodInfo;
private MethodInfo m_OnSessionFinishedMethodInfo;
internal void InitRun(string sessionId, string handlerCodeBase, string handlerTypeName, string[] handlerDependencies)
{
if (PluginSettings.SelectedLoggingLevel >= LoggingLevel.TRACE)
Debug.Log("Rider Test Runner: initializing sync callbacks handler: " +
$"sessionId={sessionId}, " +
$"codeBase={handlerCodeBase}, " +
$"typeName={handlerTypeName}, " +
$"dependencies={(handlerDependencies == null ? "" : string.Join("; ", handlerDependencies))}");
m_SessionId = sessionId;
m_HandlerCodeBase = handlerCodeBase;
m_HandlerTypeName = handlerTypeName;
m_HandlerDependencies = handlerDependencies;
m_RunInitialized = true;
CreateHandlerInstance();
SafeInvokeHandlerMethod(m_OnSessionStartedMethodInfo, Array.Empty<object>());
}
private void OnEnable()
{
if (m_RunInitialized)
CreateHandlerInstance();
}
internal void OnTestStarted(string testId)
{
if (m_RunInitialized)
SafeInvokeHandlerMethod(m_OnTestStartedMethodInfo, new object[] {testId});
}
internal void OnTestFinished()
{
if (m_RunInitialized)
SafeInvokeHandlerMethod(m_OnTestFinishedMethodInfo, Array.Empty<object>());
}
internal void OnRunFinished()
{
if (!m_RunInitialized)
return;
SafeInvokeHandlerMethod(m_OnSessionFinishedMethodInfo, Array.Empty<object>());
CleanUp();
m_RunInitialized = false;
}
private void SafeInvokeHandlerMethod(MethodInfo methodInfo, object[] args)
{
try
{
methodInfo?.Invoke(m_Handler, args);
}
catch (Exception e)
{
Debug.LogException(e);
}
}
private void CreateHandlerInstance()
{
try
{
if (m_HandlerDependencies != null)
foreach (var dependency in m_HandlerDependencies)
{
if (PluginSettings.SelectedLoggingLevel >= LoggingLevel.TRACE)
Debug.Log($"Rider Test Runner: loading assembly from {dependency}");
Assembly.LoadFrom(dependency);
}
if (PluginSettings.SelectedLoggingLevel >= LoggingLevel.TRACE)
Debug.Log($"Rider Test Runner: loading assembly from {m_HandlerCodeBase}");
var assembly = Assembly.LoadFrom(m_HandlerCodeBase);
var type = assembly.GetType(m_HandlerTypeName);
if (type == null)
{
Debug.LogError($"Rider Test Runner: type '{m_HandlerTypeName}' not found in assembly '{assembly.FullName}'");
return;
}
if (PluginSettings.SelectedLoggingLevel >= LoggingLevel.TRACE)
Debug.Log($"Rider Test Runner: creating instance of type '{type.AssemblyQualifiedName}'");
m_Handler = Activator.CreateInstance(type, m_SessionId);
m_OnSessionStartedMethodInfo = type.GetMethod("OnSessionStarted", BindingFlags.Instance | BindingFlags.Public);
if (m_OnSessionStartedMethodInfo == null)
{
Debug.LogError($"Rider Test Runner: OnSessionStarted method not found in type='{type.AssemblyQualifiedName}'");
return;
}
m_OnTestStartedMethodInfo = type.GetMethod("OnTestStarted", BindingFlags.Instance | BindingFlags.Public);
if (m_OnTestStartedMethodInfo == null)
{
Debug.LogError($"Rider Test Runner: OnTestStarted method not found in type='{type.AssemblyQualifiedName}'");
return;
}
m_OnTestFinishedMethodInfo = type.GetMethod("OnTestFinished", BindingFlags.Instance | BindingFlags.Public);
if (m_OnTestFinishedMethodInfo == null)
{
Debug.LogError($"Rider Test Runner: OnTestFinished method not found in type='{type.AssemblyQualifiedName}'");
return;
}
m_OnSessionFinishedMethodInfo = type.GetMethod("OnSessionFinished", BindingFlags.Instance | BindingFlags.Public);
if (m_OnSessionFinishedMethodInfo == null)
Debug.LogError($"Rider Test Runner: OnSessionFinished method not found in type='{type.AssemblyQualifiedName}'");
}
catch (Exception e)
{
Debug.LogException(e);
}
}
private void CleanUp()
{
m_Handler = null;
m_OnSessionStartedMethodInfo = null;
m_OnSessionFinishedMethodInfo = null;
m_OnTestStartedMethodInfo = null;
m_OnTestFinishedMethodInfo = null;
}
}
}
#endif

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 48483563a64de3a4e8690122762055f1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,39 @@
#if TEST_FRAMEWORK
using System;
using NUnit.Framework.Interfaces;
namespace Packages.Rider.Editor.UnitTesting
{
/// <summary>
/// Is used by Rider Unity plugin by reflection
/// </summary>
[Serializable]
internal enum EventType { TestStarted, TestFinished, RunFinished, RunStarted } // do not reorder
/// <summary>
/// Is used by Rider Unity plugin by reflection
/// </summary>
[Serializable]
internal class TestEvent
{
public EventType type;
public string id;
public string assemblyName;
public string output;
public TestStatus testStatus;
public double duration;
public string parentId;
public TestEvent(EventType type, string id, string assemblyName, string output, double duration, TestStatus testStatus, string parentID)
{
this.type = type;
this.id = id;
this.assemblyName = assemblyName;
this.output = output;
this.testStatus = testStatus;
this.duration = duration;
parentId = parentID;
}
}
}
#endif

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f9413c47b3a14a64e8810ce76d1a6032
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,105 @@
#if TEST_FRAMEWORK
using System;
using System.Linq;
using System.Text;
using UnityEditor.TestTools.TestRunner.Api;
using UnityEngine;
namespace Packages.Rider.Editor.UnitTesting
{
internal class TestsCallback : ScriptableObject, IErrorCallbacks
{
public void RunFinished(ITestResultAdaptor result)
{
CallbackData.instance.isRider = false;
CallbackData.instance.events.Add(
new TestEvent(EventType.RunFinished, "", "","", 0, ParseTestStatus(result.TestStatus), ""));
CallbackData.instance.RaiseChangedEvent();
}
public void RunStarted(ITestAdaptor testsToRun)
{
CallbackData.instance.events.Add(
new TestEvent(EventType.RunStarted, "", "","", 0, NUnit.Framework.Interfaces.TestStatus.Passed, ""));
CallbackData.instance.RaiseChangedEvent();
}
public void TestStarted(ITestAdaptor result)
{
// RIDER-69927 "Test not run" status is shown for the test suite when running unit tests for Unity project
var method = result.Method ?? result.Children.Select(a=>a.Method).FirstOrDefault(b => b != null);
if (method == null) return;
CallbackData.instance.events.Add(
new TestEvent(EventType.TestStarted, GenerateId(result), method.TypeInfo.Assembly.GetName().Name, "", 0, NUnit.Framework.Interfaces.TestStatus.Passed, GenerateId(result.Parent)));
CallbackData.instance.RaiseChangedEvent();
}
public void TestFinished(ITestResultAdaptor result)
{
var method = result.Test.Method ?? result.Children.Select(a=>a.Test.Method).FirstOrDefault(b => b != null);
if (method == null) return;
CallbackData.instance.events.Add(
new TestEvent(EventType.TestFinished, GenerateId(result.Test), method.TypeInfo.Assembly.GetName().Name, ExtractOutput(result), (result.EndTime-result.StartTime).Milliseconds, ParseTestStatus(result.TestStatus), GenerateId(result.Test.Parent)));
CallbackData.instance.RaiseChangedEvent();
}
public void OnError(string message)
{
CallbackData.instance.isRider = false;
CallbackData.instance.events.Add(
new TestEvent(EventType.RunFinished, "", "",message, 0, NUnit.Framework.Interfaces.TestStatus.Failed, ""));
CallbackData.instance.RaiseChangedEvent();
}
// see explanation in https://jetbrains.team/p/net/code/dotnet-libs/files/f04cde7d1dd70ee13bf5532e30f929b9b5ed08a4/ReSharperTestRunner/src/Adapters/TestRunner.Adapters.NUnit3/RemoteTaskDepot.cs?tab=source&line=129
private static string GenerateId(ITestAdaptor node)
{
// ES: Parameterized tests defined in a parametrized test fixture, though
// constructed for a particular test fixture with the given parameter, have identical fullname that does
// not include parameters of parent testfixture (name of the without parameters is used instead).
// This leads to 'Test with {id} id is already running' message.
if (node.TypeInfo == null)
return $"{node.Parent.FullName}.{node.Name}";
return node.FullName;
}
private static NUnit.Framework.Interfaces.TestStatus ParseTestStatus(TestStatus testStatus)
{
return (NUnit.Framework.Interfaces.TestStatus)Enum.Parse(typeof(NUnit.Framework.Interfaces.TestStatus), testStatus.ToString());
}
private static string ExtractOutput(ITestResultAdaptor testResult)
{
var stringBuilder = new StringBuilder();
if (testResult.Message != null)
{
stringBuilder.AppendLine("Message: ");
stringBuilder.AppendLine(testResult.Message);
}
if (!string.IsNullOrEmpty(testResult.Output))
{
stringBuilder.AppendLine("Output: ");
stringBuilder.AppendLine(testResult.Output);
}
if (!string.IsNullOrEmpty(testResult.StackTrace))
{
stringBuilder.AppendLine("Stacktrace: ");
stringBuilder.AppendLine(testResult.StackTrace);
}
var result = stringBuilder.ToString();
if (result.Length > 0)
return result;
return testResult.Output ?? string.Empty;
}
}
}
#endif

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 58aa570dbe0761f43b25ff6c2265bbe2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: