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.

297 lines
8.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 GamecraftModdingAPI.App;
  11. using GamecraftModdingAPI.Tasks;
  12. using GamecraftModdingAPI.Utility;
  13. namespace GamecraftModdingAPI.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 = "GamecraftModdingAPI_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.Lean.EveryFrameStepRunner_RUNS_IN_TIME_STOPPED_AND_RUNNING); };
  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. // returning from a new game without saving will hard lock GC (it's an invalid state)
  128. //Game newGame = Game.NewGame();
  129. //yield return new WaitForSecondsEnumerator(5).Continue(); // wait for sync
  130. //newGame.EnterGame();
  131. }
  132. private static IEnumerator<TaskContract> GameTests()
  133. {
  134. yield return Yield.It;
  135. Game currentGame = Game.CurrentGame();
  136. // in-game tests
  137. yield return new WaitForSecondsEnumerator(5).Continue(); // wait for game to finish loading
  138. foreach (Type t in testTypes)
  139. {
  140. foreach (MethodBase m in t.GetMethods())
  141. {
  142. APITestCaseAttribute a = m.GetCustomAttribute<APITestCaseAttribute>();
  143. if (a != null && a.TestType == TestType.Game)
  144. {
  145. try
  146. {
  147. m.Invoke(null, new object[0]);
  148. }
  149. catch (Exception e)
  150. {
  151. Assert.Fail($"Game test '{m}' raised an exception: {e.ToString()}");
  152. }
  153. yield return Yield.It;
  154. }
  155. }
  156. }
  157. currentGame.ToggleTimeMode();
  158. yield return new WaitForSecondsEnumerator(5).Continue();
  159. // simulation tests
  160. foreach (Type t in testTypes)
  161. {
  162. foreach (MethodBase m in t.GetMethods())
  163. {
  164. APITestCaseAttribute a = m.GetCustomAttribute<APITestCaseAttribute>();
  165. if (a != null && a.TestType == TestType.SimulationMode)
  166. {
  167. try
  168. {
  169. m.Invoke(null, new object[0]);
  170. }
  171. catch (Exception e)
  172. {
  173. Assert.Fail($"Simulation test '{m}' raised an exception: {e.ToString()}");
  174. }
  175. yield return Yield.It;
  176. }
  177. }
  178. }
  179. currentGame.ToggleTimeMode();
  180. yield return new WaitForSecondsEnumerator(5).Continue();
  181. // build tests
  182. foreach (Type t in testTypes)
  183. {
  184. foreach (MethodBase m in t.GetMethods())
  185. {
  186. APITestCaseAttribute a = m.GetCustomAttribute<APITestCaseAttribute>();
  187. if (a != null && a.TestType == TestType.EditMode)
  188. {
  189. try
  190. {
  191. m.Invoke(null, new object[0]);
  192. }
  193. catch (Exception e)
  194. {
  195. Assert.Fail($"Build test '{m}' raised an exception: {e.ToString()}");
  196. }
  197. yield return Yield.It;
  198. }
  199. }
  200. }
  201. // exit game
  202. yield return new WaitForSecondsEnumerator(5).Continue();
  203. yield return ReturnToMenu().Continue();
  204. }
  205. private static IEnumerator<TaskContract> ReturnToMenu()
  206. {
  207. Logging.MetaLog("Returning to main menu");
  208. yield return Yield.It;
  209. Game.CurrentGame().ExitGame();
  210. }
  211. private static IEnumerator<TaskContract> TearDown()
  212. {
  213. yield return new WaitForSecondsEnumerator(5).Continue();
  214. Logging.MetaLog("Tearing down test run");
  215. // dispose tests here
  216. foreach (Type t in testTypes)
  217. {
  218. foreach (MethodBase m in t.GetMethods())
  219. {
  220. if (m.GetCustomAttribute<APITestTearDownAttribute>() != null)
  221. {
  222. try
  223. {
  224. m.Invoke(null, new object[0]);
  225. }
  226. catch (Exception e)
  227. {
  228. Assert.Warn($"Tear down method '{m}' raised an exception: {e.ToString()}");
  229. }
  230. yield return Yield.It;
  231. }
  232. }
  233. }
  234. // finish up
  235. Assert.CallsComplete();
  236. timer.Stop();
  237. string verdict = _testsPassed ? "--- PASSED :) ---" : "--- FAILED :( ---";
  238. Assert.Log($"VERDICT: {verdict} ({_testsCountPassed}/{_testsCountFailed}/{_testsCount} P/F/T in {timer.ElapsedMilliseconds}ms)");
  239. yield return Yield.It;
  240. // end game
  241. Logging.MetaLog("Completed test run: " + verdict);
  242. yield return Yield.It;
  243. Assert.CloseLog();
  244. if (AutoShutdown) Application.Quit();
  245. }
  246. private static void FindTests(Assembly asm)
  247. {
  248. testTypes = new List<Type>();
  249. foreach (Type t in asm.GetTypes())
  250. {
  251. if (t.GetCustomAttribute<APITestClassAttribute>() != null)
  252. {
  253. testTypes.Add(t);
  254. }
  255. }
  256. }
  257. /// <summary>
  258. /// Runs the tests.
  259. /// </summary>
  260. /// <param name="asm">Assembly to search for tests. When set to null, this uses the GamecraftModdingAPI assembly. </param>
  261. public static void RunTests(Assembly asm = null)
  262. {
  263. if (asm == null) asm = Assembly.GetExecutingAssembly();
  264. FindTests(asm);
  265. Logging.MetaLog("Starting test run");
  266. // log metadata
  267. Assert.Log($"Unity {Application.unityVersion}");
  268. Assert.Log($"Gamecraft {Application.version}");
  269. Assert.Log($"GamecraftModdingAPI {Assembly.GetExecutingAssembly().GetName().Version}");
  270. Assert.Log($"Testing {asm.GetName().Name} {asm.GetName().Version}");
  271. Assert.Log($"START: --- {DateTime.Now.ToString()} --- ({testTypes.Count} tests classes detected)");
  272. StartUp();
  273. Logging.MetaLog("Test StartUp complete");
  274. }
  275. }
  276. }