A stable modding interface between Techblox and mods https://mod.exmods.org/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

283 lines
7.8KB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Reflection;
  5. using System.Linq; // welcome to the dark side
  6. using Svelto.Tasks;
  7. using Svelto.Tasks.Lean;
  8. using Svelto.Tasks.Enumerators;
  9. using UnityEngine;
  10. using TechbloxModdingAPI.App;
  11. using TechbloxModdingAPI.Tasks;
  12. using TechbloxModdingAPI.Utility;
  13. namespace TechbloxModdingAPI.Tests
  14. {
  15. /// <summary>
  16. /// API test system root class.
  17. /// </summary>
  18. public static class TestRoot
  19. {
  20. public static bool AutoShutdown = true;
  21. public const string ReportFile = "TechbloxModdingAPI_tests.log";
  22. private static bool _testsPassed = false;
  23. private static uint _testsCount = 0;
  24. private static uint _testsCountPassed = 0;
  25. private static uint _testsCountFailed = 0;
  26. private static string state = "StartingUp";
  27. private static Stopwatch timer;
  28. private static List<Type> testTypes = null;
  29. public static bool TestsPassed
  30. {
  31. get => _testsPassed;
  32. set
  33. {
  34. _testsPassed = _testsPassed && value;
  35. _testsCount++;
  36. if (value)
  37. {
  38. _testsCountPassed++;
  39. }
  40. else
  41. {
  42. _testsCountFailed++;
  43. }
  44. }
  45. }
  46. private static void StartUp()
  47. {
  48. // init
  49. timer = Stopwatch.StartNew();
  50. _testsPassed = true;
  51. _testsCount = 0;
  52. _testsCountPassed = 0;
  53. _testsCountFailed = 0;
  54. // flow control
  55. Game.Enter += (sender, args) => { GameTests().RunOn(RobocraftX.Schedulers.ClientLean.EveryFrameStepRunner_TimeRunningAndStopped); };
  56. Game.Exit += (s, a) => state = "ReturningFromGame";
  57. Client.EnterMenu += (sender, args) =>
  58. {
  59. if (state == "EnteringMenu")
  60. {
  61. MenuTests().RunOn(Scheduler.leanRunner);
  62. state = "EnteringGame";
  63. }
  64. if (state == "ReturningFromGame")
  65. {
  66. TearDown().RunOn(Scheduler.leanRunner);
  67. state = "ShuttingDown";
  68. }
  69. };
  70. // init tests here
  71. foreach (Type t in testTypes)
  72. {
  73. foreach (MethodBase m in t.GetMethods())
  74. {
  75. if (m.GetCustomAttribute<APITestStartUpAttribute>() != null)
  76. {
  77. try
  78. {
  79. m.Invoke(null, new object[0]);
  80. }
  81. catch (Exception e)
  82. {
  83. Assert.Fail($"Start up method '{m}' raised an exception: {e.ToString()}");
  84. }
  85. }
  86. }
  87. }
  88. state = "EnteringMenu";
  89. }
  90. private static IEnumerator<TaskContract> MenuTests()
  91. {
  92. yield return Yield.It;
  93. // menu tests
  94. foreach (Type t in testTypes)
  95. {
  96. foreach (MethodBase m in t.GetMethods())
  97. {
  98. APITestCaseAttribute a = m.GetCustomAttribute<APITestCaseAttribute>();
  99. if (a != null && a.TestType == TestType.Menu)
  100. {
  101. try
  102. {
  103. m.Invoke(null, new object[0]);
  104. }
  105. catch (Exception e)
  106. {
  107. Assert.Fail($"Menu test '{m}' raised an exception: {e.ToString()}");
  108. }
  109. yield return Yield.It;
  110. }
  111. }
  112. }
  113. // load game
  114. yield return GoToGameTests().Continue();
  115. }
  116. private static IEnumerator<TaskContract> GoToGameTests()
  117. {
  118. Client app = new Client();
  119. int oldLength = 0;
  120. while (app.MyGames.Length == 0 || oldLength != app.MyGames.Length)
  121. {
  122. oldLength = app.MyGames.Length;
  123. yield return new WaitForSecondsEnumerator(1).Continue();
  124. }
  125. yield return Yield.It;
  126. app.MyGames[0].EnterGame();
  127. /*Game newGame = Game.NewGame();
  128. yield return new WaitForSecondsEnumerator(5).Continue(); // wait for sync
  129. newGame.EnterGame();*/
  130. }
  131. private static IEnumerator<TaskContract> GameTests()
  132. {
  133. yield return Yield.It;
  134. Game currentGame = Game.CurrentGame();
  135. // in-game tests
  136. yield return new WaitForSecondsEnumerator(5).Continue(); // wait for game to finish loading
  137. var testTypesToRun = new[]
  138. {
  139. TestType.Game,
  140. TestType.SimulationMode,
  141. TestType.EditMode
  142. };
  143. for (var index = 0; index < testTypesToRun.Length; index++)
  144. {
  145. foreach (Type t in testTypes)
  146. {
  147. foreach (MethodBase m in t.GetMethods())
  148. {
  149. APITestCaseAttribute a = m.GetCustomAttribute<APITestCaseAttribute>();
  150. if (a == null || a.TestType != testTypesToRun[index]) continue;
  151. object ret = null;
  152. try
  153. {
  154. ret = m.Invoke(null, new object[0]);
  155. }
  156. catch (Exception e)
  157. {
  158. Assert.Fail($"{a.TestType} test '{m}' raised an exception: {e}");
  159. }
  160. if (ret is IEnumerator<TaskContract> enumerator)
  161. { //Support enumerator methods with added exception handling
  162. bool cont;
  163. do
  164. { //Can't use yield return in a try block...
  165. try
  166. { //And with Continue() exceptions aren't caught
  167. cont = enumerator.MoveNext();
  168. }
  169. catch (Exception e)
  170. {
  171. Assert.Fail($"{a.TestType} test '{m}' raised an exception: {e}");
  172. cont = false;
  173. }
  174. yield return Yield.It;
  175. } while (cont);
  176. }
  177. yield return Yield.It;
  178. }
  179. }
  180. if (index + 1 < testTypesToRun.Length) //Don't toggle on the last test
  181. currentGame.ToggleTimeMode();
  182. yield return new WaitForSecondsEnumerator(5).Continue();
  183. }
  184. // exit game
  185. yield return ReturnToMenu().Continue();
  186. }
  187. private static IEnumerator<TaskContract> ReturnToMenu()
  188. {
  189. Logging.MetaLog("Returning to main menu");
  190. yield return Yield.It;
  191. Game.CurrentGame().ExitGame();
  192. }
  193. private static IEnumerator<TaskContract> TearDown()
  194. {
  195. yield return new WaitForSecondsEnumerator(5).Continue();
  196. Logging.MetaLog("Tearing down test run");
  197. // dispose tests here
  198. foreach (Type t in testTypes)
  199. {
  200. foreach (MethodBase m in t.GetMethods())
  201. {
  202. if (m.GetCustomAttribute<APITestTearDownAttribute>() != null)
  203. {
  204. try
  205. {
  206. m.Invoke(null, new object[0]);
  207. }
  208. catch (Exception e)
  209. {
  210. Assert.Warn($"Tear down method '{m}' raised an exception: {e.ToString()}");
  211. }
  212. yield return Yield.It;
  213. }
  214. }
  215. }
  216. // finish up
  217. Assert.CallsComplete();
  218. timer.Stop();
  219. string verdict = _testsPassed ? "--- PASSED :) ---" : "--- FAILED :( ---";
  220. Assert.Log($"VERDICT: {verdict} ({_testsCountPassed}/{_testsCountFailed}/{_testsCount} P/F/T in {timer.ElapsedMilliseconds}ms)");
  221. yield return Yield.It;
  222. // end game
  223. Logging.MetaLog("Completed test run: " + verdict);
  224. yield return Yield.It;
  225. Assert.CloseLog();
  226. if (AutoShutdown) Application.Quit();
  227. }
  228. private static void FindTests(Assembly asm)
  229. {
  230. testTypes = new List<Type>();
  231. foreach (Type t in asm.GetTypes())
  232. {
  233. if (t.GetCustomAttribute<APITestClassAttribute>() != null)
  234. {
  235. testTypes.Add(t);
  236. }
  237. }
  238. }
  239. /// <summary>
  240. /// Runs the tests.
  241. /// </summary>
  242. /// <param name="asm">Assembly to search for tests. When set to null, this uses the TechbloxModdingAPI assembly. </param>
  243. public static void RunTests(Assembly asm = null)
  244. {
  245. if (asm == null) asm = Assembly.GetExecutingAssembly();
  246. FindTests(asm);
  247. Logging.MetaLog("Starting test run");
  248. // log metadata
  249. Assert.Log($"Unity {Application.unityVersion}");
  250. Assert.Log($"Techblox {Application.version}");
  251. Assert.Log($"TechbloxModdingAPI {Assembly.GetExecutingAssembly().GetName().Version}");
  252. Assert.Log($"Testing {asm.GetName().Name} {asm.GetName().Version}");
  253. Assert.Log($"START: --- {DateTime.Now.ToString()} --- ({testTypes.Count} tests classes detected)");
  254. StartUp();
  255. Logging.MetaLog("Test StartUp complete");
  256. }
  257. }
  258. }