using System; using UnitTestSharp; namespace Vellum.UnitTests { public class GridAccessorsTests : TestFixture { public static readonly GridAccessor TwoDimensions = GridAccessors.ForRank(2); public static readonly int[,] Table = new int[2, 2]; public static readonly int[] OnePosition = { 1, 1 }; /// /// Returns an array of dimensions that is as long as three only along /// , so an index that lands on the wrong axis lands on the wrong item. /// public static Array LongAlong(int rank, int axis) { var lengths = new int[rank]; for (int dimension = 0; dimension < rank; ++dimension) { lengths[dimension] = 1; } lengths[axis] = 3; return Array.CreateInstance(typeof(int), lengths); } public class ForRankTests : TestFixture { public void EachRankFromTwoToThirtyTwo_GetsTheAccessorNamedForIt() { for (int rank = 2; rank <= 32; ++rank) { CheckEqual("GridAccessor" + rank + "`1", GridAccessors.ForRank(rank).GetType().Name); } } public void AccessorIsGenericOverTheItemType() { CheckTrue(GridAccessors.ForRank(3).GetType() == typeof(GridAccessor3)); } public void OneDimension_Throws() { CheckThrow(typeof(ArgumentOutOfRangeException)); GridAccessors.ForRank(1); } public void NoDimensions_Throws() { CheckThrow(typeof(ArgumentOutOfRangeException)); GridAccessors.ForRank(0); } public void MoreThanThirtyTwoDimensions_Throws() { CheckThrow(typeof(ArgumentOutOfRangeException)); GridAccessors.ForRank(33); } } public class AccessTests : TestFixture { public void EveryAxisOfEveryRank_IsWrittenAndReadAtItsOwnIndex() { for (int rank = 2; rank <= 32; ++rank) { GridAccessor accessor = GridAccessors.ForRank(rank); for (int axis = 0; axis < rank; ++axis) { Array grid = LongAlong(rank, axis); var position = new int[rank]; position[axis] = 2; int value = rank * 100 + axis; accessor.Set(grid, position, value); CheckEqual(value, grid.GetValue(position)); grid.SetValue(-value, position); CheckEqual(-value, accessor.Get(grid, position)); } } } public void ReferenceItems_AreStoredAsTheyAre() { var grid = new string[2, 2, 2]; string text = new string('s', 3); GridAccessors.ForRank(3).Set(grid, new[] { 1, 0, 1 }, text); CheckTrue(ReferenceEquals(text, grid[1, 0, 1])); CheckTrue(ReferenceEquals(text, GridAccessors.ForRank(3).Get(grid, new[] { 1, 0, 1 }))); } public void ArrayOfAnotherRank_Throws() { CheckThrow(typeof(InvalidCastException)); TwoDimensions.Get(new int[2, 2, 2], new[] { 0, 0 }); } public void PositionOutsideTheArray_Throws() { CheckThrow(typeof(IndexOutOfRangeException)); TwoDimensions.Get(new int[2, 2], new[] { 2, 0 }); } [AllocationTest] public void ValueItems_AreNotBoxed() { TwoDimensions.Set(Table, OnePosition, 5); int value = TwoDimensions.Get(Table, OnePosition); CheckNoAllocations(); CheckEqual(5, value); } } } }