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.

222 line
12KB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using DataLoader;
  6. using Svelto.Tasks;
  7. using Unity.Mathematics;
  8. using TechbloxModdingAPI.App;
  9. using TechbloxModdingAPI.Tests;
  10. using TechbloxModdingAPI.Utility;
  11. namespace TechbloxModdingAPI.Blocks
  12. {
  13. #if TEST
  14. /// <summary>
  15. /// Block test cases. Not accessible in release versions.
  16. /// </summary>
  17. [APITestClass]
  18. public static class BlockTests
  19. {
  20. [APITestCase(TestType.Game)] //At least one block must be placed for simulation to work
  21. public static void TestPlaceNew()
  22. {
  23. Block newBlock = Block.PlaceNew(BlockIDs.Cube, float3.zero);
  24. Assert.NotNull(newBlock.Id, "Newly placed block is missing Id. This should be populated when the block is placed.", "Newly placed block Id is not null, block successfully placed.");
  25. }
  26. [APITestCase(TestType.EditMode)]
  27. public static void TestInitProperty()
  28. {
  29. Block newBlock = Block.PlaceNew(BlockIDs.Cube, float3.zero + 2);
  30. if (!Assert.CloseTo(newBlock.Position, (float3.zero + 2), $"Newly placed block at {newBlock.Position} is expected at {Unity.Mathematics.float3.zero + 2}.", "Newly placed block position matches.")) return;
  31. //Assert.Equal(newBlock.Exists, true, "Newly placed block does not exist, possibly because Sync() skipped/missed/failed.", "Newly placed block exists, Sync() successful.");
  32. }
  33. [APITestCase(TestType.EditMode)]
  34. public static void TestBlockIDCoverage()
  35. {
  36. Assert.Equal(
  37. FullGameFields._dataDb.GetValues<CubeListData>().Keys.Select(ushort.Parse).OrderBy(id => id)
  38. .SequenceEqual(Enum.GetValues(typeof(BlockIDs)).Cast<ushort>().OrderBy(id => id)
  39. .Except(new[] {(ushort) BlockIDs.Invalid})), true,
  40. "Block ID enum is different than the known block types, update needed.",
  41. "Block ID enum matches the known block types.");
  42. }
  43. [APITestCase(TestType.EditMode)]
  44. public static void TestBlockIDs()
  45. {
  46. float3 pos = new float3();
  47. foreach (BlockIDs id in Enum.GetValues(typeof(BlockIDs)))
  48. {
  49. if (id == BlockIDs.Invalid) continue;
  50. try
  51. {
  52. Block.PlaceNew(id, pos);
  53. pos += 0.2f;
  54. }
  55. catch (Exception e)
  56. { //Only print failed case
  57. Assert.Fail($"Failed to place block type {id}: {e}");
  58. return;
  59. }
  60. }
  61. Assert.Pass("Placing all possible block types succeeded.");
  62. }
  63. [APITestCase(TestType.EditMode)]
  64. public static IEnumerator<TaskContract> TestBlockProperties()
  65. { //Uses the result of the previous test case
  66. var blocks = Game.CurrentGame().GetBlocksInGame();
  67. yield return Yield.It;
  68. for (var index = 0; index < blocks.Length; index++)
  69. {
  70. if (index % 50 == 0) yield return Yield.It; //The material or flipped status can only be changed 130 times per submission
  71. var block = blocks[index];
  72. if (!block.Exists) continue;
  73. foreach (var property in block.GetType().GetProperties())
  74. {
  75. //Includes specialised block properties
  76. if (property.SetMethod == null) continue;
  77. var testValues = new (Type, object, Predicate<object>)[]
  78. {
  79. //(type, default value, predicate or null for equality)
  80. (typeof(long), 3, null),
  81. (typeof(int), 4, null),
  82. (typeof(double), 5.2f, obj => Math.Abs((double) obj - 5.2f) < float.Epsilon),
  83. (typeof(float), 5.2f, obj => Math.Abs((float) obj - 5.2f) < float.Epsilon),
  84. (typeof(bool), true, obj => (bool) obj),
  85. (typeof(string), "Test", obj => (string) obj == "Test"), //String equality check
  86. (typeof(float3), (float3) 2, obj => math.all((float3) obj - 2 < (float3) float.Epsilon)),
  87. (typeof(BlockColor), new BlockColor(BlockColors.Aqua, 2), null),
  88. (typeof(float4), (float4) 5, obj => math.all((float4) obj - 5 < (float4) float.Epsilon))
  89. };
  90. var propType = property.PropertyType;
  91. if (!propType.IsValueType) continue;
  92. (object valueToUse, Predicate<object> predicateToUse) = (null, null);
  93. foreach (var (type, value, predicate) in testValues)
  94. {
  95. if (type.IsAssignableFrom(propType))
  96. {
  97. valueToUse = value;
  98. predicateToUse = predicate ?? (obj => Equals(obj, value));
  99. break;
  100. }
  101. }
  102. if (propType.IsEnum)
  103. {
  104. var values = propType.GetEnumValues();
  105. valueToUse = values.GetValue(values.Length / 2);
  106. predicateToUse = val => Equals(val, valueToUse);
  107. }
  108. if (valueToUse == null)
  109. {
  110. Assert.Fail($"Property {block.GetType().Name}.{property.Name} has an unknown type {propType}, test needs fixing.");
  111. yield break;
  112. }
  113. property.SetValue(block, valueToUse);
  114. object got = property.GetValue(block);
  115. var attr = property.GetCustomAttribute<TestValueAttribute>();
  116. if (!predicateToUse(got) && (attr == null || !Equals(attr.PossibleValue, got)))
  117. {
  118. Assert.Fail($"Property {block.GetType().Name}.{property.Name} value {got} does not equal {valueToUse} for block {block}.");
  119. yield break;
  120. }
  121. }
  122. }
  123. Assert.Pass("Setting all possible properties of all registered API block types succeeded.");
  124. }
  125. [APITestCase(TestType.EditMode)]
  126. public static IEnumerator<TaskContract> TestDefaultValue()
  127. {
  128. for (int i = 0; i < 2; i++)
  129. { //Tests shared defaults
  130. var block = Block.PlaceNew(BlockIDs.Cube, 1);
  131. while (!block.Exists)
  132. yield return Yield.It;
  133. block.Remove();
  134. while (block.Exists)
  135. yield return Yield.It;
  136. if(!Assert.Equal(block.Position, default,
  137. $"Block position default value {block.Position} is incorrect, should be 0.",
  138. $"Block position default value {block.Position} matches default."))
  139. yield break;
  140. block.Position = 4;
  141. }
  142. }
  143. [APITestCase(TestType.EditMode)]
  144. public static void TestDampedSpring()
  145. {
  146. Block newBlock = Block.PlaceNew(BlockIDs.DampedSpring, Unity.Mathematics.float3.zero + 1);
  147. DampedSpring b = null; // Note: the assignment operation is a lambda, which slightly confuses the compiler
  148. Assert.Errorless(() => { b = (DampedSpring) newBlock; }, "Casting block to DampedSpring raised an exception: ", "Casting block to DampedSpring completed without issue.");
  149. if (!Assert.CloseTo(b.Stiffness, 1f, $"DampedSpring.Stiffness {b.Stiffness} does not equal default value, possibly because it failed silently.", "DampedSpring.Stiffness is close enough to default.")) return;
  150. if (!Assert.CloseTo(b.Damping, 0.1f, $"DampedSpring.Damping {b.Damping} does not equal default value, possibly because it failed silently.", "DampedSpring.Damping is close enough to default.")) return;
  151. if (!Assert.CloseTo(b.MaxExtension, 0.3f, $"DampedSpring.MaxExtension {b.MaxExtension} does not equal default value, possibly because it failed silently.", "DampedSpring.MaxExtension is close enough to default.")) return;
  152. }
  153. /*[APITestCase(TestType.Game)]
  154. public static void TestMusicBlock1()
  155. {
  156. Block newBlock = Block.PlaceNew(BlockIDs.MusicBlock, Unity.Mathematics.float3.zero + 2);
  157. MusicBlock b = null; // Note: the assignment operation is a lambda, which slightly confuses the compiler
  158. Assert.Errorless(() => { b = newBlock.Specialise<MusicBlock>(); }, "Block.Specialize<MusicBlock>() raised an exception: ", "Block.Specialize<MusicBlock>() completed without issue.");
  159. if (!Assert.NotNull(b, "Block.Specialize<MusicBlock>() returned null, possibly because it failed silently.", "Specialized MusicBlock is not null.")) return;
  160. if (!Assert.CloseTo(b.Volume, 100f, $"MusicBlock.Volume {b.Volume} does not equal default value, possibly because it failed silently.", "MusicBlock.Volume is close enough to default.")) return;
  161. if (!Assert.Equal(b.TrackIndex, 0, $"MusicBlock.TrackIndex {b.TrackIndex} does not equal default value, possibly because it failed silently.", "MusicBlock.TrackIndex is equal to default.")) return;
  162. _musicBlock = b;
  163. }
  164. private static MusicBlock _musicBlock;
  165. [APITestCase(TestType.EditMode)]
  166. public static void TestMusicBlock2()
  167. {
  168. //Block newBlock = Block.GetLastPlacedBlock();
  169. var b = _musicBlock;
  170. if (!Assert.NotNull(b, "Block.Specialize<MusicBlock>() returned null, possibly because it failed silently.", "Specialized MusicBlock is not null.")) return;
  171. b.IsPlaying = true; // play sfx
  172. if (!Assert.Equal(b.IsPlaying, true, $"MusicBlock.IsPlaying {b.IsPlaying} does not equal true, possibly because it failed silently.", "MusicBlock.IsPlaying is set properly.")) return;
  173. if (!Assert.Equal(b.ChannelType, ChannelType.None, $"MusicBlock.ChannelType {b.ChannelType} does not equal default value, possibly because it failed silently.", "MusicBlock.ChannelType is equal to default.")) return;
  174. //Assert.Log(b.Track.ToString());
  175. if (!Assert.Equal(b.Track.ToString(), new Guid("3237ff8f-f5f2-4f84-8144-496ca280f8c0").ToString(), $"MusicBlock.Track {b.Track} does not equal default value, possibly because it failed silently.", "MusicBlock.Track is equal to default.")) return;
  176. }
  177. [APITestCase(TestType.EditMode)]
  178. public static void TestLogicGate()
  179. {
  180. Block newBlock = Block.PlaceNew(BlockIDs.NOTLogicBlock, Unity.Mathematics.float3.zero + 1);
  181. LogicGate b = null; // Note: the assignment operation is a lambda, which slightly confuses the compiler
  182. Assert.Errorless(() => { b = newBlock.Specialise<LogicGate>(); }, "Block.Specialize<LogicGate>() raised an exception: ", "Block.Specialize<LogicGate>() completed without issue.");
  183. if (!Assert.NotNull(b, "Block.Specialize<LogicGate>() returned null, possibly because it failed silently.", "Specialized LogicGate is not null.")) return;
  184. if (!Assert.Equal(b.InputCount, 1u, $"LogicGate.InputCount {b.InputCount} does not equal default value, possibly because it failed silently.", "LogicGate.InputCount is default.")) return;
  185. if (!Assert.Equal(b.OutputCount, 1u, $"LogicGate.OutputCount {b.OutputCount} does not equal default value, possibly because it failed silently.", "LogicGate.OutputCount is default.")) return;
  186. if (!Assert.NotNull(b, "Block.Specialize<LogicGate>() returned null, possibly because it failed silently.", "Specialized LogicGate is not null.")) return;
  187. //if (!Assert.Equal(b.PortName(0, true), "Input", $"LogicGate.PortName(0, input:true) {b.PortName(0, true)} does not equal default value, possibly because it failed silently.", "LogicGate.PortName(0, input:true) is close enough to default.")) return;
  188. LogicGate target = null;
  189. if (!Assert.Errorless(() => { target = Block.PlaceNew<LogicGate>(BlockIDs.ANDLogicBlock, Unity.Mathematics.float3.zero + 2); })) return;
  190. Wire newWire = null;
  191. if (!Assert.Errorless(() => { newWire = b.Connect(0, target, 0);})) return;
  192. if (!Assert.NotNull(newWire, "SignalingBlock.Connect(...) returned null, possible because it failed silently.", "SignalingBlock.Connect(...) returned a non-null value.")) return;
  193. }*/
  194. /*[APITestCase(TestType.EditMode)]
  195. public static void TestSpecialiseError()
  196. {
  197. Block newBlock = Block.PlaceNew(BlockIDs.Bench, new float3(1, 1, 1));
  198. if (Assert.Errorful<BlockTypeException>(() => newBlock.Specialise<MusicBlock>(), "Block.Specialise<MusicBlock>() was expected to error on a bench block.", "Block.Specialise<MusicBlock>() errored as expected for a bench block.")) return;
  199. }*/
  200. }
  201. #endif
  202. }