Skip to content

Commit

Permalink
feat: fix some small issues, updated dependency and added tests
Browse files Browse the repository at this point in the history
  • Loading branch information
jonaslagoni committed Oct 16, 2022
1 parent a04b0ed commit 92830fd
Show file tree
Hide file tree
Showing 8 changed files with 206 additions and 25 deletions.
2 changes: 1 addition & 1 deletion Oxide.Ext.GamingApi/DefaultPluginInformation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public static string GetServerId()
if (value == null)
{
Interface.Oxide.LogInfo($"{envName} environment variable not sat using default value.");
return "" + 0;
return "0";
}
else
{
Expand Down
10 changes: 4 additions & 6 deletions Oxide.Ext.GamingApi/MessageQueue/GamingApiMessageQueue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -132,13 +132,12 @@ private void CallMessageInQueue(object source, ElapsedEventArgs e)
actionToCall(() =>
{
//Message was successfull
currentMessageCount--;
}, () =>
{
//If action was not successfull, add it do the retryMessageQueue
AddMessageToQueue(retryMessageQueue, messageImportance, actionToCall);
shouldRetryMessageQueue = true;
AddToRetryMessageQueue(messageImportance, actionToCall);
});
currentMessageCount--;
return;
}
}
Expand All @@ -153,10 +152,8 @@ private void CallMessageInQueue(object source, ElapsedEventArgs e)
}, () =>
{
//If action was not successfull, add it do the retryMessageQueue
AddMessageToQueue(retryMessageQueue, messageImportance, actionToCall);
shouldRetryMessageQueue = true;
AddToRetryMessageQueue(messageImportance, actionToCall);
});
currentMessageCount--;
return;
}
else
Expand Down Expand Up @@ -188,6 +185,7 @@ private void AddMessageToQueue(Dictionary<MessageImportance, Queue<Action<Action
public void AddToRetryMessageQueue(MessageImportance importance, Action<Action, Action> action)
{
AddMessageToQueue(retryMessageQueue, importance, action);
shouldRetryMessageQueue = true;
}
public void AddToMessageQueue(MessageImportance importance, Action<Action, Action> action)
{
Expand Down
35 changes: 18 additions & 17 deletions Oxide.Ext.GamingApi/Oxide.Ext.GamingApi.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@
<WarningLevel>1</WarningLevel>
</PropertyGroup>
<ItemGroup>
<None Remove="NATS.Client"/>
<None Remove="RustPublicAPI"/>
<None Remove="RustGameAPI"/>
<None Remove="NATS.Client" />
<None Remove="RustPublicAPI" />
<None Remove="RustGameAPI" />
</ItemGroup>
<ItemGroup>
<Reference Include="Microsoft.CSharp"/>
<Reference Include="Microsoft.CSharp" />
<Reference Include="Oxide.Core, Version=2.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\dependencies\Oxide.Core.dll</HintPath>
Expand All @@ -35,18 +35,19 @@
<Reference Include="Rust.UI">
<HintPath>..\dependencies\Rust.UI.dll</HintPath>
</Reference>
<PackageReference Include="NATS.Client" Version="1.0.1"/>
<Reference Include="System"/>
<Reference Include="System.Configuration"/>
<Reference Include="System.Configuration.Install"/>
<Reference Include="System.Data"/>
<Reference Include="System.Drawing"/>
<Reference Include="System.Numerics"/>
<Reference Include="System.Runtime.Serialization"/>
<Reference Include="System.Security"/>
<Reference Include="System.Transactions"/>
<Reference Include="System.Xml"/>
<Reference Include="System.Xml.Linq"/>
<PackageReference Include="Moq" Version="4.18.2" />
<PackageReference Include="NATS.Client" Version="1.0.1" />
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Configuration.Install" />
<Reference Include="System.Data" />
<Reference Include="System.Drawing" />
<Reference Include="System.Numerics" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.Security" />
<Reference Include="System.Transactions" />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" />
<Reference Include="Unity.TextMeshPro">
<HintPath>..\dependencies\Unity.TextMeshPro.dll</HintPath>
</Reference>
Expand Down Expand Up @@ -230,6 +231,6 @@
<Reference Include="UnityEngine.XRModule">
<HintPath>..\dependencies\UnityEngine.XRModule.dll</HintPath>
</Reference>
<PackageReference Include="RustGameAPI" Version="0.8.0"/>
<PackageReference Include="RustGameAPI" Version="0.8.0" />
</ItemGroup>
</Project>
75 changes: 75 additions & 0 deletions Oxide.Ext.GamingApiTests/AsyncVerifyForMoqExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
using Moq;
using NUnit.Framework;
using System;
using System.Diagnostics;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace AsyncVerifyForMoq
{
/// <summary>
/// Allows to do a async Verify() that wait for the Verification expression to become verified within a given timeout.
/// </summary>
public static class MoqAsyncVerifyExtensions
{
const int GRANULARITY = 100;

/// <summary>
/// Prevents having multiple implementations for the timeout handling.
/// </summary>
/// <param name="action">The verification action that is called.</param>
/// <param name="timeout">The timeout within the Verification should be successful.</param>
/// <returns></returns>
public async static Task SomeVerifyWithTimeout(Action action, TimeSpan timeout)
{
var stopWatch = new Stopwatch();
stopWatch.Start();
Exception verificationException = null;

while (stopWatch.Elapsed < timeout)
{
try
{
action();
return;
}
catch (Exception mockException)
{
verificationException = mockException;
await Task.Delay(GRANULARITY);
}
}
throw new TimeoutException($"Verification expression always failed within given timespan of {timeout}.", verificationException);
}

/// <summary>
/// Extension for Mock<typeparamref name="T"/> allowing a asynchronous Verify() that should be successful in a specified time period.
/// </summary>
/// <typeparam name="T">Type to mock, which can be an interface, a class, or a delegate.</typeparam>
/// <typeparam name="TExpressionResult">Result type of the expression used for verification.</typeparam>
/// <param name="mock">The mock that is used as this for this extension</param>
/// <param name="expression">Expression to verify.</param>
/// <param name="times">The number of times a method is expected to be called as in the regular Verify() call.</param>
/// <param name="timeout">The timeout within the verify should be successful.</param>
/// <returns>A task to wait on. The task will fail with a TimeoutException in case the Verify() was not successful within the given timeout.</returns>
public async static Task AsyncVerify<T, TExpressionResult>(this Mock<T> mock, Expression<Func<T, TExpressionResult>> expression, Times times, TimeSpan timeout) where T : class
{
await SomeVerifyWithTimeout(() => mock.Verify(expression, times), timeout);
}

/// <summary>
/// Extension for Mock<typeparamref name="T"/> allowing a asynchronous Verify() that should be successful in a specified time period.
/// Variant for expressions without a return value and one parameter.
/// </summary>
/// <typeparam name="T">Type to mock, which can be an interface, a class, or a delegate.</typeparam>
/// <param name="mock">The mock that is used as this for this extension</param>
/// <param name="expression">Expression to verify.</param>
/// <param name="times">The number of times a method is expected to be called as in the regular Verify() call.</param>
/// <param name="timeout">The timeout within the verify should be successful.</param>
/// <returns>A task to wait on. The task will fail with a TimeoutException in case the Verify() was not successful within the given timeout.</returns>
public async static Task AsyncVerify<T>(this Mock<T> mock, Expression<Action<T>> expression, Times times, TimeSpan timeout) where T : class
{
await SomeVerifyWithTimeout(() => mock.Verify(expression, times), timeout);
}
}
}
88 changes: 88 additions & 0 deletions Oxide.Ext.GamingApiTests/GamingApiMessageQueueTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;
using NUnit.Framework;
using Oxide.Ext.GamingApi.MessageQueue;
using System;
using AsyncVerifyForMoq;
using Moq;

namespace Oxide.Ext.GamingApi.Tests
{
[TestFixture()]
public class GamingApiMessageQueueTest
{
GamingApiMessageQueue queue;

[SetUp()]
public void setup()
{
queue = GamingApiMessageQueue.Instance;
}

[Test()]
public async Task shouldConsumeMessage()
{
var timeSpan = TimeSpan.FromSeconds(10);
var mock = new Mock<Action<Action, Action>>();
mock.Setup((m) => m(It.IsAny<Action>(), It.IsAny<Action>()))
.Callback((Action success, Action failure) => success());

queue.AddToMessageQueue(MessageImportance.LOW, mock.Object);

var asyncVerification = new List<Task>()
{
MoqAsyncVerifyExtensions.SomeVerifyWithTimeout(() =>
{
//Cannot use assertion as it will be caught by the test itself
if(0 != queue.GetCurrentMessagesInQueue()) throw new Exception($"{queue.GetCurrentMessagesInQueue()}");
}, timeSpan)
};
await Task.WhenAll(asyncVerification);
}
[Test()]
public async Task shouldConsumeRetryMessage()
{
var timeSpan = TimeSpan.FromSeconds(10);
var mock = new Mock<Action<Action, Action>>();
mock.Setup((m) => m(It.IsAny<Action>(), It.IsAny<Action>()))
.Callback((Action success, Action failure) => success());

queue.AddToRetryMessageQueue(MessageImportance.LOW, mock.Object);

var asyncVerification = new List<Task>()
{
MoqAsyncVerifyExtensions.SomeVerifyWithTimeout(() =>
{
//Cannot use assertion as it will be caught by the test itself
if(0 != queue.GetCurrentMessagesInQueue()) throw new Exception($"{queue.GetCurrentMessagesInQueue()}");
}, timeSpan)
};
await Task.WhenAll(asyncVerification);
}
[Test()]
public async Task shouldBeAbleToProcessMessagesInDueTime()
{
var timeSpan = TimeSpan.FromSeconds(12);
queue.SetInterval(1000);
var mock = new Mock<Action<Action, Action>>();
mock.Setup((m) => m(It.IsAny<Action>(), It.IsAny<Action>()))
.Callback((Action success, Action failure) => success());

for (int i = 0; i < 10; i++)
{
queue.AddToRetryMessageQueue(MessageImportance.LOW, mock.Object);
}

var asyncVerification = new List<Task>()
{
MoqAsyncVerifyExtensions.SomeVerifyWithTimeout(() =>
{
//Cannot use assertion as it will be caught by the test itself
if(0 != queue.GetCurrentMessagesInQueue()) throw new Exception($"{queue.GetCurrentMessagesInQueue()}");
}, timeSpan)
};
await Task.WhenAll(asyncVerification);
}
}
}
14 changes: 14 additions & 0 deletions Oxide.Ext.GamingApiTests/Oxide.Ext.GamingApiTests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,16 @@
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Castle.Core, Version=5.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL">
<HintPath>..\packages\Castle.Core.5.1.0\lib\netstandard2.0\Castle.Core.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Bcl.AsyncInterfaces, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Bcl.AsyncInterfaces.5.0.0\lib\net461\Microsoft.Bcl.AsyncInterfaces.dll</HintPath>
</Reference>
<Reference Include="Microsoft.CSharp" />
<Reference Include="Moq, Version=4.18.0.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL">
<HintPath>..\packages\Moq.4.18.2\lib\netstandard2.0\Moq.dll</HintPath>
</Reference>
<Reference Include="NATS.Client, Version=1.0.1.0, Culture=neutral, PublicKeyToken=5b58bc7249e111a9, processorArchitecture=MSIL">
<HintPath>..\packages\NATS.Client.1.0.1\lib\net46\NATS.Client.dll</HintPath>
<Private>True</Private>
Expand All @@ -64,6 +70,9 @@
<Reference Include="System.Collections.Specialized, Version=4.0.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Collections.Specialized.4.3.0\lib\net46\System.Collections.Specialized.dll</HintPath>
</Reference>
<Reference Include="System.Diagnostics.EventLog, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Diagnostics.EventLog.4.7.0\lib\net461\System.Diagnostics.EventLog.dll</HintPath>
</Reference>
<Reference Include="System.Memory, Version=4.0.1.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Memory.4.5.4\lib\net461\System.Memory.dll</HintPath>
</Reference>
Expand All @@ -89,6 +98,9 @@
<Reference Include="System.Security.Cryptography.X509Certificates, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net46\System.Security.Cryptography.X509Certificates.dll</HintPath>
</Reference>
<Reference Include="System.Security.Principal.Windows, Version=4.1.3.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Security.Principal.Windows.4.7.0\lib\net461\System.Security.Principal.Windows.dll</HintPath>
</Reference>
<Reference Include="System.Text.Encodings.Web, Version=5.0.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Text.Encodings.Web.5.0.1\lib\net461\System.Text.Encodings.Web.dll</HintPath>
</Reference>
Expand All @@ -111,6 +123,8 @@
<Otherwise />
</Choose>
<ItemGroup>
<Compile Include="AsyncVerifyForMoqExtensions.cs" />
<Compile Include="GamingApiMessageQueueTests.cs" />
<Compile Include="GamingApiNatsTests.cs" />
</ItemGroup>
<ItemGroup>
Expand Down
2 changes: 1 addition & 1 deletion Oxide.Ext.GamingApiTests/app.config
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="NATS.Client" publicKeyToken="5b58bc7249e111a9" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-0.14.6.0" newVersion="0.14.6.0" />
<bindingRedirect oldVersion="0.0.0.0-1.0.1.0" newVersion="1.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
Expand Down
5 changes: 5 additions & 0 deletions Oxide.Ext.GamingApiTests/packages.config
Original file line number Diff line number Diff line change
@@ -1,22 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Castle.Core" version="5.1.0" targetFramework="net461" />
<package id="Microsoft.Bcl.AsyncInterfaces" version="5.0.0" targetFramework="net461" />
<package id="Microsoft.CSharp" version="4.7.0" targetFramework="net461" />
<package id="Moq" version="4.18.2" targetFramework="net461" />
<package id="NATS.Client" version="1.0.1" targetFramework="net461" />
<package id="Newtonsoft.Json" version="13.0.1" targetFramework="net46" />
<package id="NUnit" version="3.12.0" targetFramework="net46" />
<package id="NUnit3TestAdapter" version="3.15.1" targetFramework="net46" />
<package id="RustGameAPI" version="0.5.0" targetFramework="net461" />
<package id="System.Buffers" version="4.5.1" targetFramework="net461" />
<package id="System.Collections.Specialized" version="4.3.0" targetFramework="net46" />
<package id="System.Diagnostics.EventLog" version="4.7.0" targetFramework="net461" />
<package id="System.Memory" version="4.5.4" targetFramework="net461" />
<package id="System.Net.Http" version="4.3.4" targetFramework="net46" />
<package id="System.Numerics.Vectors" version="4.5.0" targetFramework="net461" />
<package id="System.Reflection.Emit" version="4.7.0" targetFramework="net461" />
<package id="System.Runtime.CompilerServices.Unsafe" version="5.0.0" targetFramework="net461" />
<package id="System.Security.Cryptography.Algorithms" version="4.3.0" targetFramework="net46" requireReinstallation="true" />
<package id="System.Security.Cryptography.Encoding" version="4.3.0" targetFramework="net46" />
<package id="System.Security.Cryptography.Primitives" version="4.3.0" targetFramework="net46" />
<package id="System.Security.Cryptography.X509Certificates" version="4.3.0" targetFramework="net46" requireReinstallation="true" />
<package id="System.Security.Principal.Windows" version="4.7.0" targetFramework="net461" />
<package id="System.Text.Encodings.Web" version="5.0.1" targetFramework="net461" />
<package id="System.Text.Json" version="5.0.2" targetFramework="net461" />
<package id="System.Text.RegularExpressions" version="4.3.1" targetFramework="net46" />
Expand Down

0 comments on commit 92830fd

Please sign in to comment.