Add tests and make minor fixes to PriorityQueue.

This commit is contained in:
RoosterDragon
2016-02-26 22:41:14 +00:00
parent 86e4a72dce
commit 0306a8de6c
3 changed files with 57 additions and 6 deletions

View File

@@ -76,17 +76,19 @@ namespace OpenRA.Primitives
return At(lastLevel, lastIndex);
}
public T Peek() { return At(0, 0); }
public T Peek()
{
if (level <= 0 && index <= 0)
throw new InvalidOperationException("PriorityQueue empty.");
return At(0, 0);
}
public T Pop()
{
if (level == 0 && index == 0)
throw new InvalidOperationException("Attempting to pop empty PriorityQueue");
var ret = At(0, 0);
var ret = Peek();
BubbleInto(0, 0, Last());
if (--index < 0)
index = (1 << --level) - 1;
return ret;
}

View File

@@ -0,0 +1,48 @@
#region Copyright & License Information
/*
* Copyright 2007-2016 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version. For more
* information, see COPYING.
*/
#endregion
using System;
using NUnit.Framework;
using OpenRA.Primitives;
namespace OpenRA.Test
{
[TestFixture]
class PriorityQueueTest
{
[TestCase(TestName = "PriorityQueue maintains invariants when adding and removing items.")]
public void PriorityQueueGeneralTest()
{
var queue = new PriorityQueue<int>();
Assert.IsTrue(queue.Empty, "New queue should start out empty.");
Assert.Throws<InvalidOperationException>(() => queue.Peek(), "Peeking at an empty queue should throw.");
Assert.Throws<InvalidOperationException>(() => queue.Pop(), "Popping an empty queue should throw.");
foreach (var value in new[] { 4, 3, 5, 1, 2 })
{
queue.Add(value);
Assert.IsFalse(queue.Empty, "Queue should not be empty - items have been added.");
}
foreach (var value in new[] { 1, 2, 3, 4, 5 })
{
Assert.AreEqual(value, queue.Peek(), "Peek returned the wrong item - should be in order.");
Assert.IsFalse(queue.Empty, "Queue should not be empty yet.");
Assert.AreEqual(value, queue.Pop(), "Pop returned the wrong item - should be in order.");
}
Assert.IsTrue(queue.Empty, "Queue should now be empty.");
Assert.Throws<InvalidOperationException>(() => queue.Peek(), "Peeking at an empty queue should throw.");
Assert.Throws<InvalidOperationException>(() => queue.Pop(), "Popping an empty queue should throw.");
}
}
}

View File

@@ -50,6 +50,7 @@
<Compile Include="OpenRA.Game\MiniYamlTest.cs" />
<Compile Include="OpenRA.Game\ActorInfoTest.cs" />
<Compile Include="OpenRA.Game\CoordinateTest.cs" />
<Compile Include="OpenRA.Game\PriorityQueueTest.cs" />
<Compile Include="OpenRA.Game\SpatiallyPartitionedTest.cs" />
<Compile Include="OpenRA.Mods.Common\ShapeTest.cs" />
<Compile Include="OpenRA.Game\OrderTest.cs" />