diff --git a/.editorconfig b/.editorconfig
index fa08a1f..f0ca40d 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -27,6 +27,13 @@ indent_size = 2
[*.json]
indent_size = 2
+# npm package files
+[package.json]
+indent_style = space
+indent_size = 2
+insert_final_newline = false
+charset = utf-8
+
# Powershell files
[*.ps1]
indent_size = 2
@@ -38,6 +45,13 @@ indent_size = 2
# Dotnet code style settings:
[*.{cs,vb}]
+dotnet_diagnostic.IDE0005.severity = suggestion
+dotnet_diagnostic.IDE0007.severity = none
+dotnet_diagnostic.IDE0008.severity = none
+dotnet_diagnostic.IDE0011.severity = none
+
+file_header_template = This Source Code Form is subject to the terms of the Mozilla Public\nLicense, v. 2.0. If a copy of the MPL was not distributed with this\nfile, You can obtain one at https://mozilla.org/MPL/2.0/.
+
# Sort using and Import directives with System.* appearing first and seperate groups
dotnet_sort_system_directives_first = true:error
dotnet_separate_import_directive_groups = true:suggestion
@@ -246,5 +260,5 @@ csharp_style_deconstructed_variable_declaration = true:suggestion
csharp_style_pattern_local_over_anonymous_function = true:error
csharp_using_directive_placement = outside_namespace:error
csharp_prefer_static_local_function = true:error
-csharp_prefer_simple_using_statement = true:error
+csharp_prefer_simple_using_statement = true:suggestion
csharp_style_prefer_switch_expression = true:suggestion
diff --git a/.gitattributes b/.gitattributes
deleted file mode 100644
index 1ff0c42..0000000
--- a/.gitattributes
+++ /dev/null
@@ -1,63 +0,0 @@
-###############################################################################
-# Set default behavior to automatically normalize line endings.
-###############################################################################
-* text=auto
-
-###############################################################################
-# Set default behavior for command prompt diff.
-#
-# This is need for earlier builds of msysgit that does not have it on by
-# default for csharp files.
-# Note: This is only used by command line
-###############################################################################
-#*.cs diff=csharp
-
-###############################################################################
-# Set the merge driver for project and solution files
-#
-# Merging from the command prompt will add diff markers to the files if there
-# are conflicts (Merging from VS is not affected by the settings below, in VS
-# the diff markers are never inserted). Diff markers may cause the following
-# file extensions to fail to load in VS. An alternative would be to treat
-# these files as binary and thus will always conflict and require user
-# intervention with every merge. To do so, just uncomment the entries below
-###############################################################################
-#*.sln merge=binary
-#*.csproj merge=binary
-#*.vbproj merge=binary
-#*.vcxproj merge=binary
-#*.vcproj merge=binary
-#*.dbproj merge=binary
-#*.fsproj merge=binary
-#*.lsproj merge=binary
-#*.wixproj merge=binary
-#*.modelproj merge=binary
-#*.sqlproj merge=binary
-#*.wwaproj merge=binary
-
-###############################################################################
-# behavior for image files
-#
-# image files are treated as binary by default.
-###############################################################################
-#*.jpg binary
-#*.png binary
-#*.gif binary
-
-###############################################################################
-# diff behavior for common document formats
-#
-# Convert binary document formats to text before diffing them. This feature
-# is only available from the command line. Turn it on by uncommenting the
-# entries below.
-###############################################################################
-#*.doc diff=astextplain
-#*.DOC diff=astextplain
-#*.docx diff=astextplain
-#*.DOCX diff=astextplain
-#*.dot diff=astextplain
-#*.DOT diff=astextplain
-#*.pdf diff=astextplain
-#*.PDF diff=astextplain
-#*.rtf diff=astextplain
-#*.RTF diff=astextplain
diff --git a/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md
similarity index 100%
rename from CODE_OF_CONDUCT.md
rename to .github/CODE_OF_CONDUCT.md
diff --git a/CONTRIBUTING.md b/.github/CONTRIBUTING.md
similarity index 100%
rename from CONTRIBUTING.md
rename to .github/CONTRIBUTING.md
diff --git a/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md
similarity index 100%
rename from ISSUE_TEMPLATE.md
rename to .github/ISSUE_TEMPLATE.md
diff --git a/.gitignore b/.gitignore
index f357a43..7a47522 100644
--- a/.gitignore
+++ b/.gitignore
@@ -212,6 +212,7 @@ _pkginfo.txt
ClientBin/
~$*
*~
+!*~/
*.dbmdl
*.dbproj.schemaview
*.jfm
@@ -313,3 +314,6 @@ OpenCover/
# SpecFlow autogenerated feature code
*.feature.cs
+
+# macOS
+**/.DS_Store
diff --git a/.npmignore b/.npmignore
new file mode 100644
index 0000000..99922ad
--- /dev/null
+++ b/.npmignore
@@ -0,0 +1,7 @@
+.github
+.gitattributes
+.gitmodules
+.gitignore
+.editorconfig
+.DS_Store
+MSBuild~
diff --git a/BUILDING.md b/BUILDING.md
deleted file mode 100644
index 1634766..0000000
--- a/BUILDING.md
+++ /dev/null
@@ -1,28 +0,0 @@
-To build the DarkRift 2 solution *you must have Microsoft Visual Studio 2022* installed. The Community edition is fine for open source projects, and is easily attained from https://visualstudio.microsoft.com/vs/community/
-
-## Configurations
-
-Currently, DarkRift can be built in the following configurations:
-* Debug: Self evident.
-* Free: The same as the old Free version.
-* Pro: The same as the old Pro version. This is probably want you want for release builds. Going forward, it is also what will be supported in future DR2 versions.
-
-## Output Assemblies
-
-Builds emit to the ./Build subdirectory. A subfolder is created for each configuration, which in turn has a subfolder for each output platform (e.g. .NET 4.0).
-
-In each platform subfolder, there is:
-* A Lib subfolder containing assembles, debug symbol .pdb files, etc.
-* A Run command to launch the standalone DarkRift server.
-* A default Server.config.
-* DarkRift Server.zip containing the files in the platform folder.
-
-Additionally, there is a ./Build/DarkRift Source.zip containing a cleaned copy of the project, which corresponds to the old way the DR2 source code used to be distributed with the Pro version. It is recommended to simply refer users to this GitHub repo instead.
-
-If you're looking to manually copy assemblies into your Unity assets, you should look for .dll files from the ./Build/($configuration)/net4.0/Lib subfolder. Remember to paste assemblies into a Plugins folder or subfolder in order for Unity to recognize them.
-
-## Producing a .unitypackage
-
-If you're an existing DarkRift 2 user, there's a decent chance you will want to reproduce the Free or Pro .unitypackage DarkRift 2 used to ship with in order to stick with the way DR2 in your Assets folder is organized. Even as a new user, a .unitypackage can be a practical way install the typical DarkRift version into your Unity project if you don't intend to make changes.
-
-*TODO: Fix package building in post_release.sh and write guide for how to export packages*
\ No newline at end of file
diff --git a/DarkRift.Server/Properties/AssemblyInfo.cs b/DarkRift.Client/AssemblyInfo.cs
similarity index 81%
rename from DarkRift.Server/Properties/AssemblyInfo.cs
rename to DarkRift.Client/AssemblyInfo.cs
index 9d05642..665b73e 100644
--- a/DarkRift.Server/Properties/AssemblyInfo.cs
+++ b/DarkRift.Client/AssemblyInfo.cs
@@ -4,6 +4,7 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
+using System.Reflection;
using System.Runtime.CompilerServices;
-[assembly: InternalsVisibleTo("DarkRift.Server.Testing")]
\ No newline at end of file
+[assembly: DarkRift.Preserve]
diff --git a/DarkRift.Testing/Properties/AssemblyInfo.cs b/DarkRift.Client/AssemblyInfo.gen.cs
similarity index 53%
rename from DarkRift.Testing/Properties/AssemblyInfo.cs
rename to DarkRift.Client/AssemblyInfo.gen.cs
index 4b4a452..47dbff7 100644
--- a/DarkRift.Testing/Properties/AssemblyInfo.cs
+++ b/DarkRift.Client/AssemblyInfo.gen.cs
@@ -4,3 +4,7 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
+//
+// Do not modify this file manually
+// This file is is updated based on the version found on package.json
+[assembly: System.Reflection.AssemblyVersion("2.10.1")]
diff --git a/DarkRift.Client/DarkRift.Client.asmdef b/DarkRift.Client/DarkRift.Client.asmdef
new file mode 100644
index 0000000..dc5591a
--- /dev/null
+++ b/DarkRift.Client/DarkRift.Client.asmdef
@@ -0,0 +1,18 @@
+{
+ "name": "DarkRift.Client",
+ "rootNamespace": "",
+ "references": [
+ "GUID:74b22b8f1e899468c828514608b766c6"
+ ],
+ "includePlatforms": [],
+ "excludePlatforms": [],
+ "allowUnsafeCode": false,
+ "overrideReferences": false,
+ "precompiledReferences": [],
+ "autoReferenced": false,
+ "defineConstraints": [
+ "!DARKRIFT_NO_CLIENT"
+ ],
+ "versionDefines": [],
+ "noEngineReferences": true
+}
\ No newline at end of file
diff --git a/DarkRift.Schemas/Cluster.config.xsd b/DarkRift.Schemas/Cluster.config.xsd
deleted file mode 100644
index 84f2e21..0000000
--- a/DarkRift.Schemas/Cluster.config.xsd
+++ /dev/null
@@ -1,29 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/DarkRift.Schemas/Server.config.xsd b/DarkRift.Schemas/Server.config.xsd
deleted file mode 100644
index 04da7ec..0000000
--- a/DarkRift.Schemas/Server.config.xsd
+++ /dev/null
@@ -1,183 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/DarkRift.Server.Console/App.config b/DarkRift.Server.Console/App.config
deleted file mode 100644
index 2153663..0000000
--- a/DarkRift.Server.Console/App.config
+++ /dev/null
@@ -1,12 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/DarkRift.Server.Console/DarkRift.Server.Console.csproj b/DarkRift.Server.Console/DarkRift.Server.Console.csproj
deleted file mode 100644
index 8bf48e1..0000000
--- a/DarkRift.Server.Console/DarkRift.Server.Console.csproj
+++ /dev/null
@@ -1,45 +0,0 @@
-
-
-
-
-
- net4.0;netcoreapp2.0;netcoreapp3.1;net5.0;net6.0
- netcoreapp2.0;netcoreapp3.1;net5.0;net6.0
- Debug;Release
-
-
- Exe
- DarkRift.Server.Console.Program
- true
-
-
- false
-
-
-
- DEBUG;TRACE
-
-
-
-
-
- PreserveNewest
-
-
-
-
-
-
- PreserveNewest
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/DarkRift.Server.Console/Program.cs b/DarkRift.Server.Console/Program.cs
deleted file mode 100644
index 2d69991..0000000
--- a/DarkRift.Server.Console/Program.cs
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
- */
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-using DarkRift.Server;
-using System.Threading;
-using System.IO;
-using System.Collections.Specialized;
-using System.Collections;
-using DarkRift.Server.Configuration;
-
-namespace DarkRift.Server.Console
-{
- internal class Program
- {
- ///
- /// The server instance.
- ///
- private static DarkRiftServer server;
-
- ///
- /// Main entry point of the server which starts a single server.
- ///
- ///
- private static void Main(string[] args)
- {
- string[] rawArguments = CommandEngine.ParseArguments(string.Join(" ", args));
- string[] arguments = CommandEngine.GetArguments(rawArguments);
- NameValueCollection variables = CommandEngine.GetFlags(rawArguments);
-
- foreach (DictionaryEntry environmentVariable in Environment.GetEnvironmentVariables())
- variables.Add((string)environmentVariable.Key, (string)environmentVariable.Value);
-
- string serverConfigFile;
- string clusterConfigFile;
- if (arguments.Length < 1)
- {
- serverConfigFile = "Server.config";
- clusterConfigFile = "Cluster.config";
- }
- else if (arguments.Length == 1)
- {
- serverConfigFile = arguments[0];
- clusterConfigFile = "Cluster.config";
- }
- else if (arguments.Length == 2)
- {
- serverConfigFile = arguments[0];
- clusterConfigFile = arguments[1];
- }
- else
- {
- System.Console.Error.WriteLine("Unexpected number of comand line arguments passed. Expected 0-2 but found " + arguments.Length + ".");
- System.Console.WriteLine("Press any key to exit...");
- System.Console.ReadKey();
- return;
- }
-
- DarkRiftServerConfigurationBuilder serverConfigurationBuilder;
-
- try
- {
- serverConfigurationBuilder = DarkRiftServerConfigurationBuilder.CreateFromXml(serverConfigFile, variables);
- }
- catch (IOException e)
- {
- System.Console.Error.WriteLine("Could not load the server config file needed to start (" + e.Message + "). Are you sure it's present and accessible?");
- System.Console.WriteLine("Press any key to exit...");
- System.Console.ReadKey();
- return;
- }
- catch (XmlConfigurationException e)
- {
- System.Console.Error.WriteLine($"Failed to load '{serverConfigFile}': {e.Message}");
- System.Console.Error.WriteLine();
- System.Console.Error.WriteLine(e.DocumentationLink != null ? $"See {e.DocumentationLink} for more information." : "No additional documentation available.");
- System.Console.Error.WriteLine();
- System.Console.Error.WriteLine(e.LineInfo != null && e.LineInfo.HasLineInfo() ? $"Line {e.LineInfo.LineNumber} Col: {e.LineInfo.LinePosition}" : "(Unknown location)");
- System.Console.Error.WriteLine();
- System.Console.WriteLine("Press any key to exit...");
- System.Console.ReadKey();
- return;
- }
-
- // Set this thread as the one executing dispatcher tasks
- serverConfigurationBuilder.WithDispatcherExecutorThreadID(Thread.CurrentThread.ManagedThreadId);
-
- if (File.Exists(clusterConfigFile))
- {
- DarkRiftClusterConfigurationBuilder clusterConfigurationBuilder;
- try
- {
- clusterConfigurationBuilder = DarkRiftClusterConfigurationBuilder.CreateFromXml(clusterConfigFile, variables);
- }
- catch (IOException e)
- {
- System.Console.Error.WriteLine("Could not load the cluster config file needed to start (" + e.Message + "). Are you sure it's present and accessible?");
- System.Console.WriteLine("Press any key to exit...");
- System.Console.ReadKey();
- return;
- }
- catch (XmlConfigurationException e)
- {
- System.Console.Error.WriteLine($"Failed to load '{clusterConfigFile}': {e.Message}");
- System.Console.Error.WriteLine();
- System.Console.Error.WriteLine(e.DocumentationLink != null ? $"See {e.DocumentationLink} for more information." : "No additional documentation available.");
- System.Console.Error.WriteLine();
- System.Console.Error.WriteLine(e.LineInfo != null && e.LineInfo.HasLineInfo() ? $"Line {e.LineInfo.LineNumber} Col: {e.LineInfo.LinePosition}" : "(Unknown location)");
- System.Console.Error.WriteLine();
- System.Console.WriteLine("Press any key to exit...");
- System.Console.ReadKey();
- return;
- }
-
- server = new DarkRiftServer(serverConfigurationBuilder.ServerSpawnData, clusterConfigurationBuilder.ClusterSpawnData);
- }
- else
- {
- server = new DarkRiftServer(serverConfigurationBuilder.ServerSpawnData);
- }
-
-
- server.StartServer();
-
- new Thread(new ThreadStart(ConsoleLoop)).Start();
-
- while (!server.Disposed)
- {
- server.DispatcherWaitHandle.WaitOne();
- server.ExecuteDispatcherTasks();
- }
- }
-
- ///
- /// Invoked from another thread to repeatedly execute commands from the console.
- ///
- private static void ConsoleLoop()
- {
- while (!server.Disposed)
- {
- string input = System.Console.ReadLine();
-
- if (input == null)
- {
- System.Console.WriteLine("Stopping input loop as we seem to be running without an input stream.");
- return;
- }
-
- server.ExecuteCommand(input);
- }
- }
- }
-}
diff --git a/DarkRift.Server.Console/Run.ps1 b/DarkRift.Server.Console/Run.ps1
deleted file mode 100644
index 5afd8e3..0000000
--- a/DarkRift.Server.Console/Run.ps1
+++ /dev/null
@@ -1 +0,0 @@
-dotnet Lib/DarkRift.Server.Console.dll
\ No newline at end of file
diff --git a/DarkRift.Server.Console/Server.config b/DarkRift.Server.Console/Server.config
deleted file mode 100644
index f2bc3ab..0000000
--- a/DarkRift.Server.Console/Server.config
+++ /dev/null
@@ -1,65 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/DarkRift.Server.Testing/DarkRift.Server.Testing.csproj b/DarkRift.Server.Testing/DarkRift.Server.Testing.csproj
deleted file mode 100644
index 44dae0c..0000000
--- a/DarkRift.Server.Testing/DarkRift.Server.Testing.csproj
+++ /dev/null
@@ -1,30 +0,0 @@
-
-
-
-
-
- net4.5;net6.0
- net6.0
- Debug;Release
- true
-
- NU1701
-
-
-
-
-
-
-
-
-
-
- TRACE;DEBUG
-
-
-
-
-
-
-
-
diff --git a/DarkRift.Server.Testing/PluginTestUtilTest.cs b/DarkRift.Server.Testing/PluginTestUtilTest.cs
deleted file mode 100644
index c1c523d..0000000
--- a/DarkRift.Server.Testing/PluginTestUtilTest.cs
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
- */
-
-using System;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Moq;
-
-namespace DarkRift.Server.Testing
-{
- [TestClass]
- public class PluginTestUtilTest
- {
- [TestMethod]
- public void TestRunCommandOnWhenCommandExists()
- {
- // GIVEN a mock event handler
- Mock> mockHandler = new Mock>();
- mockHandler.Setup(h => h(It.IsAny(), It.IsAny()));
-
- // AND a command with that handler
- Command command = new Command("my-command", "xyz", "abc", mockHandler.Object);
-
- // AND a mock plugin with that command
- Mock mockPlugin = new Mock(new PluginLoadData(null, null, null, null, (Logger)null, null));
- mockPlugin.Setup(p => p.Commands).Returns(new Command[] { command });
-
- // WHEN the command is run on the plugin through the test util
- PluginTestUtil pluginTestUtil = new PluginTestUtil();
- pluginTestUtil.RunCommandOn("my-command with arguments -and=many -f -l -a -g -s", mockPlugin.Object);
-
- // THEN the command handler was invoked with the correct args
- mockHandler.Verify(h => h(pluginTestUtil, It.Is(a =>
- a.OriginalCommand == "my-command with arguments -and=many -f -l -a -g -s"
- && a.Arguments.Length == 2
- && a.Arguments[1] == "arguments"
- && a.Command == command
- && a.Flags.Count == 6
- && a.Flags.Get("and") == "many"
- && a.RawArguments.Length == 8
- && a.RawArguments[3] == "-f"
- )), Times.Once);
- }
-
- [TestMethod]
- public void TestRunCommandOnWhenCommandDoesNotExists()
- {
- // GIVEN a mock event handler
- Mock> mockHandler = new Mock>();
- mockHandler.Setup(h => h(It.IsAny(), It.IsAny()));
-
- // AND a command with a different name
- Command command = new Command("not-this", "xyz", "abc", mockHandler.Object);
-
- // AND a mock plugin with that command
- Mock mockPlugin = new Mock(new PluginLoadData(null, null, null, null, (Logger)null, null));
- mockPlugin.Setup(p => p.Commands).Returns(new Command[] { command });
-
- // THEN an exception is thrown
- // TODO DR3 this is a poor choice of exception
- Assert.ThrowsException(() =>
- {
- // WHEN the command is run on the plugin through the test util
- PluginTestUtil pluginTestUtil = new PluginTestUtil();
- pluginTestUtil.RunCommandOn("my-command with arguments -and=many -f -l -a -g -s", mockPlugin.Object);
- });
- }
- }
-}
diff --git a/DarkRift.Server.Testing/packages.config b/DarkRift.Server.Testing/packages.config
deleted file mode 100644
index de82217..0000000
--- a/DarkRift.Server.Testing/packages.config
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/DarkRift.Server.Testing/Configuration/DarkRiftClusterConfigurationBuilderTests.cs b/DarkRift.Server.Tests/Configuration/DarkRiftClusterConfigurationBuilderTests.cs
similarity index 80%
rename from DarkRift.Server.Testing/Configuration/DarkRiftClusterConfigurationBuilderTests.cs
rename to DarkRift.Server.Tests/Configuration/DarkRiftClusterConfigurationBuilderTests.cs
index 2e4c673..2c072d8 100644
--- a/DarkRift.Server.Testing/Configuration/DarkRiftClusterConfigurationBuilderTests.cs
+++ b/DarkRift.Server.Tests/Configuration/DarkRiftClusterConfigurationBuilderTests.cs
@@ -4,20 +4,14 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
+using NUnit.Framework;
-namespace DarkRift.Server.Configuration.Testing
+namespace DarkRift.Server.Configuration.Tests
{
- [TestClass]
public class DarkRiftClusterConfigurationBuilderTests
{
- [TestMethod]
- public void TestAddGroup()
+ [Test]
+ public void AddGroup()
{
// GIVEN an empty config builder
DarkRiftClusterConfigurationBuilder builder = DarkRiftClusterConfigurationBuilder.Create();
diff --git a/DarkRift.Server.Testing/Configuration/DarkRiftServerConfigurationBuilderTests.cs b/DarkRift.Server.Tests/Configuration/DarkRiftServerConfigurationBuilderTests.cs
similarity index 89%
rename from DarkRift.Server.Testing/Configuration/DarkRiftServerConfigurationBuilderTests.cs
rename to DarkRift.Server.Tests/Configuration/DarkRiftServerConfigurationBuilderTests.cs
index 6d5761e..dffe7e8 100644
--- a/DarkRift.Server.Testing/Configuration/DarkRiftServerConfigurationBuilderTests.cs
+++ b/DarkRift.Server.Tests/Configuration/DarkRiftServerConfigurationBuilderTests.cs
@@ -4,22 +4,17 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
-using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
-using System.Collections.Generic;
using System.Collections.Specialized;
-using System.Linq;
using System.Net;
-using System.Text;
-using System.Threading.Tasks;
+using NUnit.Framework;
-namespace DarkRift.Server.Configuration.Testing
+namespace DarkRift.Server.Configuration.Tests
{
- [TestClass]
public class DarkRiftServerConfigurationBuilderTests
{
- [TestMethod]
- public void TestWithDataDirectory()
+ [Test]
+ public void WithDataDirectory()
{
// GIVEN an empty config builder
DarkRiftServerConfigurationBuilder builder = DarkRiftServerConfigurationBuilder.Create();
@@ -31,8 +26,8 @@ public void TestWithDataDirectory()
Assert.AreEqual("directory", builder.ServerSpawnData.Data.Directory);
}
- [TestMethod]
- public void TestWithDispatcherExecutorThreadID()
+ [Test]
+ public void WithDispatcherExecutorThreadID()
{
// GIVEN an empty config builder
DarkRiftServerConfigurationBuilder builder = DarkRiftServerConfigurationBuilder.Create();
@@ -44,8 +39,8 @@ public void TestWithDispatcherExecutorThreadID()
Assert.AreEqual(1234, builder.ServerSpawnData.DispatcherExecutorThreadID);
}
- [TestMethod]
- public void TestWithEventsFromDispatcher()
+ [Test]
+ public void WithEventsFromDispatcher()
{
// GIVEN an empty config builder
DarkRiftServerConfigurationBuilder builder = DarkRiftServerConfigurationBuilder.Create();
@@ -57,8 +52,8 @@ public void TestWithEventsFromDispatcher()
Assert.IsTrue(builder.ServerSpawnData.EventsFromDispatcher);
}
- [TestMethod]
- public void TestAddListener()
+ [Test]
+ public void AddListener()
{
// GIVEN an empty config builder
DarkRiftServerConfigurationBuilder builder = DarkRiftServerConfigurationBuilder.Create();
@@ -75,8 +70,8 @@ public void TestAddListener()
Assert.AreEqual(0, builder.ServerSpawnData.Listeners.NetworkListeners[0].Settings.Count);
}
- [TestMethod]
- public void TestAddListenerWithSettings()
+ [Test]
+ public void AddListenerWithSettings()
{
// GIVEN an empty config builder
DarkRiftServerConfigurationBuilder builder = DarkRiftServerConfigurationBuilder.Create();
@@ -98,8 +93,8 @@ public void TestAddListenerWithSettings()
Assert.AreEqual("value", builder.ServerSpawnData.Listeners.NetworkListeners[0].Settings["key"]);
}
- [TestMethod]
- public void TestWithStartupLogLevels()
+ [Test]
+ public void WithStartupLogLevels()
{
// GIVEN an empty config builder
DarkRiftServerConfigurationBuilder builder = DarkRiftServerConfigurationBuilder.Create();
@@ -113,8 +108,8 @@ public void TestWithStartupLogLevels()
Assert.AreEqual(LogType.Fatal, builder.ServerSpawnData.Logging.StartupLogLevels[1]);
}
- [TestMethod]
- public void TestAddLogWriter()
+ [Test]
+ public void AddLogWriter()
{
// GIVEN an empty config builder
DarkRiftServerConfigurationBuilder builder = DarkRiftServerConfigurationBuilder.Create();
@@ -131,8 +126,8 @@ public void TestAddLogWriter()
Assert.AreEqual(0, builder.ServerSpawnData.Logging.LogWriters[0].Settings.Count);
}
- [TestMethod]
- public void TestAddLogWriterWithSettings()
+ [Test]
+ public void AddLogWriterWithSettings()
{
// GIVEN an empty config builder
DarkRiftServerConfigurationBuilder builder = DarkRiftServerConfigurationBuilder.Create();
@@ -154,8 +149,8 @@ public void TestAddLogWriterWithSettings()
Assert.AreEqual("value", builder.ServerSpawnData.Logging.LogWriters[0].Settings["key"]);
}
- [TestMethod]
- public void TestWithPerMessageMetrics()
+ [Test]
+ public void WithPerMessageMetrics()
{
// GIVEN an empty config builder
DarkRiftServerConfigurationBuilder builder = DarkRiftServerConfigurationBuilder.Create();
@@ -167,8 +162,8 @@ public void TestWithPerMessageMetrics()
Assert.IsTrue(builder.ServerSpawnData.Metrics.EnablePerMessageMetrics);
}
- [TestMethod]
- public void TestWithMetricsWriter()
+ [Test]
+ public void WithMetricsWriter()
{
// GIVEN an empty config builder
DarkRiftServerConfigurationBuilder builder = DarkRiftServerConfigurationBuilder.Create();
@@ -181,8 +176,8 @@ public void TestWithMetricsWriter()
Assert.AreEqual(0, builder.ServerSpawnData.Metrics.MetricsWriter.Settings.Count);
}
- [TestMethod]
- public void TestWithMetricsWriterWithSettings()
+ [Test]
+ public void WithMetricsWriterWithSettings()
{
// GIVEN an empty config builder
DarkRiftServerConfigurationBuilder builder = DarkRiftServerConfigurationBuilder.Create();
@@ -200,8 +195,8 @@ public void TestWithMetricsWriterWithSettings()
Assert.AreEqual("value", builder.ServerSpawnData.Metrics.MetricsWriter.Settings["key"]);
}
- [TestMethod]
- public void TestWithLoadPluginsByDefault()
+ [Test]
+ public void WithLoadPluginsByDefault()
{
// GIVEN an empty config builder
DarkRiftServerConfigurationBuilder builder = DarkRiftServerConfigurationBuilder.Create();
@@ -213,8 +208,8 @@ public void TestWithLoadPluginsByDefault()
Assert.IsTrue(builder.ServerSpawnData.Plugins.LoadByDefault);
}
- [TestMethod]
- public void TestAddPlugin()
+ [Test]
+ public void AddPlugin()
{
// GIVEN an empty config builder
DarkRiftServerConfigurationBuilder builder = DarkRiftServerConfigurationBuilder.Create();
@@ -229,8 +224,8 @@ public void TestAddPlugin()
Assert.AreEqual(0, builder.ServerSpawnData.Plugins.Plugins[0].Settings.Count);
}
- [TestMethod]
- public void TestAddPluginWithSettings()
+ [Test]
+ public void AddPluginWithSettings()
{
// GIVEN an empty config builder
DarkRiftServerConfigurationBuilder builder = DarkRiftServerConfigurationBuilder.Create();
@@ -251,8 +246,8 @@ public void TestAddPluginWithSettings()
Assert.AreEqual("value", builder.ServerSpawnData.Plugins.Plugins[0].Settings["key"]);
}
- [TestMethod]
- public void TestExceptPlugin()
+ [Test]
+ public void ExceptPlugin()
{
// GIVEN an empty config builder
DarkRiftServerConfigurationBuilder builder = DarkRiftServerConfigurationBuilder.Create();
@@ -267,8 +262,8 @@ public void TestExceptPlugin()
Assert.AreEqual(0, builder.ServerSpawnData.Plugins.Plugins[0].Settings.Count);
}
- [TestMethod]
- public void TestAddPluginSearchPath()
+ [Test]
+ public void AddPluginSearchPath()
{
// GIVEN an empty config builder
DarkRiftServerConfigurationBuilder builder = DarkRiftServerConfigurationBuilder.Create();
@@ -283,8 +278,8 @@ public void TestAddPluginSearchPath()
Assert.AreEqual(DependencyResolutionStrategy.Standard, builder.ServerSpawnData.PluginSearch.PluginSearchPaths[0].DependencyResolutionStrategy);
}
- [TestMethod]
- public void TestAddPluginSearchPathWithCreateDir()
+ [Test]
+ public void AddPluginSearchPathWithCreateDir()
{
// GIVEN an empty config builder
DarkRiftServerConfigurationBuilder builder = DarkRiftServerConfigurationBuilder.Create();
@@ -299,8 +294,8 @@ public void TestAddPluginSearchPathWithCreateDir()
Assert.AreEqual(DependencyResolutionStrategy.Standard, builder.ServerSpawnData.PluginSearch.PluginSearchPaths[0].DependencyResolutionStrategy);
}
- [TestMethod]
- public void TestAddPluginSearchPathWithDependencyResolutionStrategy()
+ [Test]
+ public void AddPluginSearchPathWithDependencyResolutionStrategy()
{
// GIVEN an empty config builder
DarkRiftServerConfigurationBuilder builder = DarkRiftServerConfigurationBuilder.Create();
@@ -315,8 +310,8 @@ public void TestAddPluginSearchPathWithDependencyResolutionStrategy()
Assert.AreEqual(DependencyResolutionStrategy.RecursiveFromDirectory, builder.ServerSpawnData.PluginSearch.PluginSearchPaths[0].DependencyResolutionStrategy);
}
- [TestMethod]
- public void TestAddPluginSearchPathWithCreateDirAndDependencyResolutionStrategy()
+ [Test]
+ public void AddPluginSearchPathWithCreateDirAndDependencyResolutionStrategy()
{
// GIVEN an empty config builder
DarkRiftServerConfigurationBuilder builder = DarkRiftServerConfigurationBuilder.Create();
@@ -331,8 +326,8 @@ public void TestAddPluginSearchPathWithCreateDirAndDependencyResolutionStrategy(
Assert.AreEqual(DependencyResolutionStrategy.RecursiveFromDirectory, builder.ServerSpawnData.PluginSearch.PluginSearchPaths[0].DependencyResolutionStrategy);
}
- [TestMethod]
- public void TestAddPluginType()
+ [Test]
+ public void AddPluginType()
{
// GIVEN an empty config builder
DarkRiftServerConfigurationBuilder builder = DarkRiftServerConfigurationBuilder.Create();
@@ -345,8 +340,8 @@ public void TestAddPluginType()
Assert.AreSame(typeof(DateTime), builder.ServerSpawnData.PluginSearch.PluginTypes[0]);
}
- [TestMethod]
- public void TestWithMaxStrikes()
+ [Test]
+ public void WithMaxStrikes()
{
// GIVEN an empty config builder
DarkRiftServerConfigurationBuilder builder = DarkRiftServerConfigurationBuilder.Create();
@@ -358,8 +353,8 @@ public void TestWithMaxStrikes()
Assert.AreEqual(123, builder.ServerSpawnData.Server.MaxStrikes);
}
- [TestMethod]
- public void TestWithMaxReconnectAttempts()
+ [Test]
+ public void WithMaxReconnectAttempts()
{
// GIVEN an empty config builder
DarkRiftServerConfigurationBuilder builder = DarkRiftServerConfigurationBuilder.Create();
@@ -371,8 +366,8 @@ public void TestWithMaxReconnectAttempts()
Assert.AreEqual(123, builder.ServerSpawnData.Server.ReconnectAttempts);
}
- [TestMethod]
- public void TestWithServerGroup()
+ [Test]
+ public void WithServerGroup()
{
// GIVEN an empty config builder
DarkRiftServerConfigurationBuilder builder = DarkRiftServerConfigurationBuilder.Create();
@@ -384,8 +379,8 @@ public void TestWithServerGroup()
Assert.AreEqual("group", builder.ServerSpawnData.Server.ServerGroup);
}
- [TestMethod]
- public void TestWithAdvertisedHost()
+ [Test]
+ public void WithAdvertisedHost()
{
// GIVEN an empty config builder
DarkRiftServerConfigurationBuilder builder = DarkRiftServerConfigurationBuilder.Create();
@@ -397,8 +392,8 @@ public void TestWithAdvertisedHost()
Assert.AreEqual("host", builder.ServerSpawnData.ServerRegistry.AdvertisedHost);
}
- [TestMethod]
- public void TestWithAdvertisedPort()
+ [Test]
+ public void WithAdvertisedPort()
{
// GIVEN an empty config builder
DarkRiftServerConfigurationBuilder builder = DarkRiftServerConfigurationBuilder.Create();
@@ -410,8 +405,8 @@ public void TestWithAdvertisedPort()
Assert.AreEqual(1234, builder.ServerSpawnData.ServerRegistry.AdvertisedPort);
}
- [TestMethod]
- public void TestWithServerRegistryConnector()
+ [Test]
+ public void WithServerRegistryConnector()
{
// GIVEN an empty config builder
DarkRiftServerConfigurationBuilder builder = DarkRiftServerConfigurationBuilder.Create();
@@ -424,8 +419,8 @@ public void TestWithServerRegistryConnector()
Assert.AreEqual(0, builder.ServerSpawnData.ServerRegistry.ServerRegistryConnector.Settings.Count);
}
- [TestMethod]
- public void TestWithServerRegistryConnectorWithSettings()
+ [Test]
+ public void WithServerRegistryConnectorWithSettings()
{
// GIVEN an empty config builder
DarkRiftServerConfigurationBuilder builder = DarkRiftServerConfigurationBuilder.Create();
diff --git a/DarkRift.Server.Tests/DarkRift.Server.Tests.asmdef b/DarkRift.Server.Tests/DarkRift.Server.Tests.asmdef
new file mode 100644
index 0000000..3ff96ec
--- /dev/null
+++ b/DarkRift.Server.Tests/DarkRift.Server.Tests.asmdef
@@ -0,0 +1,25 @@
+{
+ "name": "DarkRift.Server.Tests",
+ "rootNamespace": "",
+ "references": [
+ "GUID:27619889b8ba8c24980f49ee34dbb44a",
+ "GUID:0acc523941302664db1f4e527237feb3",
+ "GUID:74b22b8f1e899468c828514608b766c6",
+ "GUID:946957ecf1ca94f148ed5fbadd24e3de"
+ ],
+ "includePlatforms": [
+ "Editor"
+ ],
+ "excludePlatforms": [],
+ "allowUnsafeCode": false,
+ "overrideReferences": true,
+ "precompiledReferences": [
+ "nunit.framework.dll"
+ ],
+ "autoReferenced": false,
+ "defineConstraints": [
+ "UNITY_INCLUDE_TESTS"
+ ],
+ "versionDefines": [],
+ "noEngineReferences": false
+}
\ No newline at end of file
diff --git a/DarkRift.Server.Tests/PluginTestUtilTest.cs b/DarkRift.Server.Tests/PluginTestUtilTest.cs
new file mode 100644
index 0000000..2b73fa6
--- /dev/null
+++ b/DarkRift.Server.Tests/PluginTestUtilTest.cs
@@ -0,0 +1,85 @@
+/*
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
+ */
+
+using System;
+using NUnit.Framework;
+
+namespace DarkRift.Server.Tests
+{
+ public class PluginTestUtilTest
+ {
+ private class MockPlugin : ExtendedPluginBase
+ {
+ public MockPlugin(ExtendedPluginBaseLoadData pluginLoadData) : base(pluginLoadData)
+ {
+ }
+
+ private Command[] commands;
+
+ public override bool ThreadSafe => throw new NotImplementedException();
+ public override Version Version => throw new NotImplementedException();
+ public override Command[] Commands => commands;
+
+ public void SetCommands(Command[] value)
+ {
+ commands = value;
+ }
+ }
+
+ [Test]
+ public void RunCommandOnWhenCommandExists()
+ {
+ string commandString = "my-command with arguments -and=many -f -l -a -g -s";
+
+ // GIVEN a command with a handler
+ Command command = new Command("my-command", "xyz", "abc", (sender, e) =>
+ {
+ // THEN the command handler was invoked with the correct args
+ Assert.IsInstanceOf(sender);
+ Assert.IsInstanceOf(e);
+ Assert.AreEqual(e.OriginalCommand, commandString);
+ Assert.AreEqual(e.Arguments.Length, 2);
+ Assert.AreEqual(e.Arguments[1], "arguments");
+ Assert.AreEqual(e.Flags.Count, 6);
+ Assert.AreEqual(e.Flags.Get("and"), "many");
+ Assert.AreEqual(e.RawArguments.Length, 8);
+ Assert.AreEqual(e.RawArguments[3], "-f");
+ });
+
+ // AND a mock plugin with that command
+ MockPlugin mockPlugin = new MockPlugin(new PluginLoadData(null, null, null, null, (Logger)null, null));
+ mockPlugin.SetCommands(new Command[] { command });
+
+ // WHEN the command is run on the plugin through the test util
+ PluginTestUtil pluginTestUtil = new PluginTestUtil();
+ pluginTestUtil.RunCommandOn(commandString, mockPlugin);
+ }
+
+ [Test]
+ public void RunCommandOnWhenCommandDoesNotExists()
+ {
+ // AND a command with a different name
+ Command command = new Command("not-this", "xyz", "abc", (sender, e) =>
+ {
+ Assert.IsInstanceOf(sender);
+ Assert.IsInstanceOf(e);
+ });
+
+ // AND a mock plugin with that command
+ MockPlugin mockPlugin = new MockPlugin(new PluginLoadData(null, null, null, null, (Logger)null, null));
+ mockPlugin.SetCommands(new Command[] { command });
+
+ // THEN an exception is thrown
+ // TODO DR3 this is a poor choice of exception
+ Assert.Throws(() =>
+ {
+ // WHEN the command is run on the plugin through the test util
+ PluginTestUtil pluginTestUtil = new PluginTestUtil();
+ pluginTestUtil.RunCommandOn("my-command with arguments -and=many -f -l -a -g -s", mockPlugin);
+ });
+ }
+ }
+}
diff --git a/DarkRift.Server.Testing/Plugins/Chat/BadWordFilterTests.cs b/DarkRift.Server.Tests/Plugins/Chat/BadWordFilterTests.cs
similarity index 71%
rename from DarkRift.Server.Testing/Plugins/Chat/BadWordFilterTests.cs
rename to DarkRift.Server.Tests/Plugins/Chat/BadWordFilterTests.cs
index a66d338..cc2a851 100644
--- a/DarkRift.Server.Testing/Plugins/Chat/BadWordFilterTests.cs
+++ b/DarkRift.Server.Tests/Plugins/Chat/BadWordFilterTests.cs
@@ -5,23 +5,19 @@
*/
using System;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-
using System.Text.RegularExpressions;
-using DarkRift.Server.Plugins.Chat;
using System.Collections.Specialized;
-using DarkRift.Server;
using System.IO;
+using NUnit.Framework;
-namespace DarkRift.Server.Plugins.Chat.Testing
+namespace DarkRift.Server.Plugins.Chat.Tests
{
- [TestClass]
public class BadWordFilterTests
{
private BadWordFilter filter;
- [TestInitialize]
- public void Initialize()
+ [SetUp]
+ public void SetUp()
{
filter = new BadWordFilter(new PluginLoadData("BadWordFilter", new NameValueCollection(), new DarkRiftInfo(DateTime.Now), new DarkRiftThreadHelper(false, null), (Logger)null, Path.GetTempPath()));
@@ -29,32 +25,32 @@ public void Initialize()
filter.PopulateBadWords(new string[] { "poop", "crap" });
}
- [TestMethod]
- public void ContainsTest()
+ [Test]
+ public void Contains()
{
Assert.IsTrue(filter.ContainsBadWords("poop"));
}
- [TestMethod]
- public void ContainsCaseInsensitiveTest()
+ [Test]
+ public void ContainsCaseInsensitive()
{
Assert.IsTrue(filter.ContainsBadWords("pOOp"));
}
- [TestMethod]
- public void FilterToCharTest()
+ [Test]
+ public void FilterToChar()
{
Assert.AreEqual("You smell like ~~~~.", filter.FilterToChar("You smell like crap.", '~'));
}
- [TestMethod]
- public void FilterToSymbolsTest()
+ [Test]
+ public void FilterToSymbols()
{
Assert.IsTrue(Regex.IsMatch(filter.FilterToSymbols("Poop you."), @"^[\$#@%&\*!]{4} you."));
}
- [TestMethod]
- public void FilterToRandomStringTest()
+ [Test]
+ public void FilterToRandomString()
{
string a = filter.FilterToRandomString("Crap's going down.", new string[] { "Australia", "Gravity" });
Assert.IsTrue(a == "Australia's going down." || a == "Gravity's going down.");
diff --git a/DarkRift.Server.Testing/Plugins/Matchmaking/MatchmakerRankingBuilderTests.cs b/DarkRift.Server.Tests/Plugins/Matchmaking/MatchmakerRankingBuilderTests.cs
similarity index 81%
rename from DarkRift.Server.Testing/Plugins/Matchmaking/MatchmakerRankingBuilderTests.cs
rename to DarkRift.Server.Tests/Plugins/Matchmaking/MatchmakerRankingBuilderTests.cs
index 7b7e038..c418b50 100644
--- a/DarkRift.Server.Testing/Plugins/Matchmaking/MatchmakerRankingBuilderTests.cs
+++ b/DarkRift.Server.Tests/Plugins/Matchmaking/MatchmakerRankingBuilderTests.cs
@@ -4,29 +4,23 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
-using DarkRift.Server.Plugins.Matchmaking;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
+using NUnit.Framework;
-namespace DarkRift.Server.Plugins.Rooms.Tests.Plugins.Matchmaking
+namespace DarkRift.Server.Plugins.Matchmaking.Tests
{
- [TestClass]
public class MatchmakerRankingBuilderTests
{
private MatchmakerRankingBuilder builder;
- [TestInitialize]
- public void Initialize()
+ [SetUp]
+ public void SetUp()
{
builder = new MatchmakerRankingBuilder();
}
- [TestMethod]
- public void TestMinimiseDifferenceLinearFloat()
+ [Test]
+ public void MinimiseDifferenceLinearFloat()
{
//Zero difference
builder.MinimiseDifferenceLinear(0.5f, 0.5f, 1f, 0.5f);
@@ -44,8 +38,8 @@ public void TestMinimiseDifferenceLinearFloat()
Assert.AreEqual(0.6f, builder.Ranking);
}
- [TestMethod]
- public void TestMinimiseDifferenceLinearDouble()
+ [Test]
+ public void MinimiseDifferenceLinearDouble()
{
//Zero difference
builder.MinimiseDifferenceLinear(0.5, 0.5, 1.0, 0.5f);
@@ -63,8 +57,8 @@ public void TestMinimiseDifferenceLinearDouble()
Assert.AreEqual(0.6f, builder.Ranking);
}
- [TestMethod]
- public void TestMinimiseDifferenceLinearInt()
+ [Test]
+ public void MinimiseDifferenceLinearInt()
{
//Zero difference
builder.MinimiseDifferenceLinear(5, 5, 10, 0.5f);
@@ -82,8 +76,8 @@ public void TestMinimiseDifferenceLinearInt()
Assert.AreEqual(0.6f, builder.Ranking);
}
- [TestMethod]
- public void TestMinimiseDifferenceLinearLong()
+ [Test]
+ public void MinimiseDifferenceLinearLong()
{
//Zero difference
builder.MinimiseDifferenceLinear(5L, 5L, 10L, 0.5f);
@@ -101,8 +95,8 @@ public void TestMinimiseDifferenceLinearLong()
Assert.AreEqual(0.6f, builder.Ranking);
}
- [TestMethod]
- public void TestMaximiseDifferenceLinearFloat()
+ [Test]
+ public void MaximiseDifferenceLinearFloat()
{
//Maximum difference
builder.MaximiseDifferenceLinear(0f, 1f, 1f, 0.5f);
@@ -120,8 +114,8 @@ public void TestMaximiseDifferenceLinearFloat()
Assert.AreEqual(0.6f, builder.Ranking);
}
- [TestMethod]
- public void TestMaximiseDifferenceLinearDouble()
+ [Test]
+ public void MaximiseDifferenceLinearDouble()
{
//Maximum difference
builder.MaximiseDifferenceLinear(0, 1, 1, 0.5f);
@@ -139,8 +133,8 @@ public void TestMaximiseDifferenceLinearDouble()
Assert.AreEqual(0.6f, builder.Ranking);
}
- [TestMethod]
- public void TestMaximiseDifferenceLinearInt()
+ [Test]
+ public void MaximiseDifferenceLinearInt()
{
//Maximum difference
builder.MaximiseDifferenceLinear(0, 10, 10, 0.5f);
@@ -158,8 +152,8 @@ public void TestMaximiseDifferenceLinearInt()
Assert.AreEqual(0.6f, builder.Ranking);
}
- [TestMethod]
- public void TestMaximiseDifferenceLinearLong()
+ [Test]
+ public void MaximiseDifferenceLinearLong()
{
//Maximum difference
builder.MaximiseDifferenceLinear(0L, 10L, 10L, 0.5f);
@@ -177,8 +171,8 @@ public void TestMaximiseDifferenceLinearLong()
Assert.AreEqual(0.6f, builder.Ranking);
}
- [TestMethod]
- public void TestEqualFloat()
+ [Test]
+ public void EqualFloat()
{
//Equal
builder.Equal(1f, 1f, 0.5f);
@@ -191,8 +185,8 @@ public void TestEqualFloat()
Assert.AreEqual(0.5f, builder.Ranking);
}
- [TestMethod]
- public void TestEqualDouble()
+ [Test]
+ public void EqualDouble()
{
//Equal
builder.Equal(1.0, 1.0, 0.5f);
@@ -205,8 +199,8 @@ public void TestEqualDouble()
Assert.AreEqual(0.5f, builder.Ranking);
}
- [TestMethod]
- public void TestEqualInt()
+ [Test]
+ public void EqualInt()
{
//Equal
builder.Equal(1, 1, 0.5f);
@@ -219,8 +213,8 @@ public void TestEqualInt()
Assert.AreEqual(0.5f, builder.Ranking);
}
- [TestMethod]
- public void TestEqualLong()
+ [Test]
+ public void EqualLong()
{
//Equal
builder.Equal(1L, 1L, 0.5f);
@@ -233,8 +227,8 @@ public void TestEqualLong()
Assert.AreEqual(0.5f, builder.Ranking);
}
- [TestMethod]
- public void TestEqualIEquatable()
+ [Test]
+ public void EqualIEquatable()
{
//Equal
builder.Equal((IEquatable)1, (IEquatable)1, 0.5f);
@@ -247,8 +241,8 @@ public void TestEqualIEquatable()
Assert.AreEqual(0.5f, builder.Ranking);
}
- [TestMethod]
- public void TestNotEqualFloat()
+ [Test]
+ public void NotEqualFloat()
{
//Not equal
builder.NotEqual(0f, 1f, 0.5f);
@@ -261,8 +255,8 @@ public void TestNotEqualFloat()
Assert.AreEqual(0.5f, builder.Ranking);
}
- [TestMethod]
- public void TestNotEqualDouble()
+ [Test]
+ public void NotEqualDouble()
{
//Not equal
builder.NotEqual(0.0, 1.0, 0.5f);
@@ -275,8 +269,8 @@ public void TestNotEqualDouble()
Assert.AreEqual(0.5f, builder.Ranking);
}
- [TestMethod]
- public void TestNotEqualInt()
+ [Test]
+ public void NotEqualInt()
{
//Not equal
builder.NotEqual(0, 1, 0.5f);
@@ -289,8 +283,8 @@ public void TestNotEqualInt()
Assert.AreEqual(0.5f, builder.Ranking);
}
- [TestMethod]
- public void TestNotEqualLong()
+ [Test]
+ public void NotEqualLong()
{
//Not equal
builder.NotEqual(0L, 1L, 0.5f);
@@ -303,8 +297,8 @@ public void TestNotEqualLong()
Assert.AreEqual(0.5f, builder.Ranking);
}
- [TestMethod]
- public void TestNotEqualIEquatable()
+ [Test]
+ public void NotEqualIEquatable()
{
//Not equal
builder.NotEqual((IEquatable)0, (IEquatable)1, 0.5f);
@@ -317,8 +311,8 @@ public void TestNotEqualIEquatable()
Assert.AreEqual(0.5f, builder.Ranking);
}
- [TestMethod]
- public void TestIsTrue()
+ [Test]
+ public void IsTrue()
{
//True
builder.IsTrue(true, 0.5f);
@@ -331,8 +325,8 @@ public void TestIsTrue()
Assert.AreEqual(0.5f, builder.Ranking);
}
- [TestMethod]
- public void TestIsFalse()
+ [Test]
+ public void IsFalse()
{
//False
builder.IsFalse(false, 0.5f);
@@ -344,15 +338,15 @@ public void TestIsFalse()
Assert.AreEqual(0.5f, builder.Ranking);
}
-
- [TestMethod]
- public void TestFail()
+
+ [Test]
+ public void Fail()
{
Assert.AreEqual(false, builder.Failed);
//Fail
builder.Fail();
-
+
Assert.AreEqual(true, builder.Failed);
//Add ranking as should always return 0
@@ -361,8 +355,8 @@ public void TestFail()
Assert.AreEqual(0.0f, builder.Ranking);
}
- [TestMethod]
- public void TestClear()
+ [Test]
+ public void Clear()
{
//Fail and give ranking
builder.Fail();
diff --git a/DarkRift.Server.Testing/Plugins/Matchmaking/RankingMatchmakerTests.cs b/DarkRift.Server.Tests/Plugins/Matchmaking/RankingMatchmakerTests.cs
similarity index 68%
rename from DarkRift.Server.Testing/Plugins/Matchmaking/RankingMatchmakerTests.cs
rename to DarkRift.Server.Tests/Plugins/Matchmaking/RankingMatchmakerTests.cs
index 3a28c45..d15f9c2 100644
--- a/DarkRift.Server.Testing/Plugins/Matchmaking/RankingMatchmakerTests.cs
+++ b/DarkRift.Server.Tests/Plugins/Matchmaking/RankingMatchmakerTests.cs
@@ -7,18 +7,53 @@
using System;
using System.Collections.Specialized;
using System.Linq;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Moq;
+using NUnit.Framework;
namespace DarkRift.Server.Plugins.Matchmaking.Tests
{
- [TestClass]
public class MatchmakerTests
{
- private Mock> matchmaker;
+ public class TestEntity
+ {
+ public float Mmr { get; }
+
+ public TestEntity(float mmr)
+ {
+ if (mmr < 0 || mmr > 1)
+ {
+ throw new ArgumentException("Invalid MMR.");
+ }
+
+ Mmr = mmr;
+ }
+ }
+
+ public class MockMatchRankingContext : MatchRankingContext
+ {
+ internal MockMatchRankingContext(float discardThreshold) : base(discardThreshold)
+ {
+ }
+ }
- [TestInitialize]
- public void Initialize()
+ public class MockRankingMatchmaker : RankingMatchmaker
+ {
+ public MockRankingMatchmaker(PluginLoadData pluginLoadData) : base(pluginLoadData)
+ {
+ }
+
+ public override bool ThreadSafe => throw new NotImplementedException();
+ public override Version Version => throw new NotImplementedException();
+
+ public override float GetSuitabilityMetric(TestEntity entity1, TestEntity entity2, MatchRankingContext context)
+ {
+ return 1 - (Math.Abs(entity1.Mmr - entity2.Mmr) / 1);
+ }
+ }
+
+ private RankingMatchmaker matchmaker;
+
+ [SetUp]
+ public void SetUp()
{
NameValueCollection settings = new NameValueCollection()
{
@@ -32,26 +67,21 @@ public void Initialize()
PluginLoadData loadData = new PluginLoadData("Matchmaker", settings, null, threadHelper, (Logger)null, null);
- matchmaker = new Mock>(loadData)
- {
- CallBase = true
- };
-
- //Setup suitability metric function to be a simple minimization of MMRs
- matchmaker.Setup(m => m.GetSuitabilityMetric(It.IsAny(), It.IsAny(), It.IsAny>()))
- .Returns((TestEntity e1, TestEntity e2, MatchRankingContext context) => 1 - Math.Abs(e1.Mmr - e2.Mmr) / 1);
+ matchmaker = new MockRankingMatchmaker(loadData);
}
- [TestMethod]
- public void TestMatchmakerAllPerfect()
+ [Test]
+ public void MatchmakerAllPerfect()
{
TestEntity[] entities = { new TestEntity(1f), new TestEntity(1f), new TestEntity(1f), new TestEntity(1f) };
foreach (TestEntity entity in entities)
- matchmaker.Object.Enqueue(entity, null);
+ {
+ matchmaker.Enqueue(entity, null);
+ }
bool invoked = false;
- matchmaker.Object.GroupFormed += (object sender, GroupFormedEventArgs args) =>
+ matchmaker.GroupFormed += (object sender, GroupFormedEventArgs args) =>
{
invoked = true;
@@ -64,21 +94,23 @@ public void TestMatchmakerAllPerfect()
Assert.IsTrue(args.Group.Contains(entities[3]));
};
- matchmaker.Object.PerformFullSearch();
+ matchmaker.PerformFullSearch();
Assert.IsTrue(invoked);
}
- [TestMethod]
- public void TestMatchmakerMostlyPerfect()
+ [Test]
+ public void MatchmakerMostlyPerfect()
{
TestEntity[] entities = { new TestEntity(1f), new TestEntity(0.25f), new TestEntity(1f), new TestEntity(1f), new TestEntity(1f) };
foreach (TestEntity entity in entities)
- matchmaker.Object.Enqueue(entity, null);
-
+ {
+ matchmaker.Enqueue(entity, null);
+ }
+
bool invoked = false;
- matchmaker.Object.GroupFormed += (object sender, GroupFormedEventArgs args) =>
+ matchmaker.GroupFormed += (object sender, GroupFormedEventArgs args) =>
{
invoked = true;
@@ -91,40 +123,44 @@ public void TestMatchmakerMostlyPerfect()
Assert.IsTrue(args.Group.Contains(entities[4]));
};
- matchmaker.Object.PerformFullSearch();
+ matchmaker.PerformFullSearch();
Assert.IsTrue(invoked);
}
- [TestMethod]
+ [Test]
public void TestMatchmakerTooFew()
{
TestEntity[] entities = { new TestEntity(1f), new TestEntity(1f), new TestEntity(1f) };
foreach (TestEntity entity in entities)
- matchmaker.Object.Enqueue(entity, null);
+ {
+ matchmaker.Enqueue(entity, null);
+ }
bool invoked = false;
- matchmaker.Object.GroupFormed += (object sender, GroupFormedEventArgs args) =>
+ matchmaker.GroupFormed += (object sender, GroupFormedEventArgs args) =>
{
invoked = true;
};
- matchmaker.Object.PerformFullSearch();
+ matchmaker.PerformFullSearch();
Assert.IsFalse(invoked);
}
- [TestMethod]
+ [Test]
public void TestMatchmakerMetrics()
{
TestEntity[] entities = { new TestEntity(1f), new TestEntity(0f), new TestEntity(0.5f), new TestEntity(0.25f), new TestEntity(0.75f), new TestEntity(0.6f), new TestEntity(0.55f), new TestEntity(0.45f) };
foreach (TestEntity entity in entities)
- matchmaker.Object.Enqueue(entity, null);
+ {
+ matchmaker.Enqueue(entity, null);
+ }
bool invoked = false;
- matchmaker.Object.GroupFormed += (object sender, GroupFormedEventArgs args) =>
+ matchmaker.GroupFormed += (object sender, GroupFormedEventArgs args) =>
{
invoked = true;
@@ -137,12 +173,12 @@ public void TestMatchmakerMetrics()
Assert.IsTrue(args.Group.Contains(entities[7]));
};
- matchmaker.Object.PerformFullSearch();
+ matchmaker.PerformFullSearch();
Assert.IsTrue(invoked);
}
- [TestMethod]
+ [Test]
public void TestMatchmakerGroups()
{
TestEntity[][] entities = {
@@ -151,10 +187,12 @@ public void TestMatchmakerGroups()
};
foreach (TestEntity[] group in entities)
- matchmaker.Object.EnqueueGroup(group, null);
+ {
+ matchmaker.EnqueueGroup(group, null);
+ }
bool invoked = false;
- matchmaker.Object.GroupFormed += (object sender, GroupFormedEventArgs args) =>
+ matchmaker.GroupFormed += (object sender, GroupFormedEventArgs args) =>
{
invoked = true;
@@ -167,7 +205,7 @@ public void TestMatchmakerGroups()
Assert.IsTrue(args.Group.Contains(entities[1][1]));
};
- matchmaker.Object.PerformFullSearch();
+ matchmaker.PerformFullSearch();
Assert.IsTrue(invoked);
}
@@ -180,30 +218,32 @@ public void TestMatchmakerGroupsTooMany()
};
foreach (TestEntity[] group in entities)
- matchmaker.Object.EnqueueGroup(group, null);
+ {
+ matchmaker.EnqueueGroup(group, null);
+ }
bool invoked = false;
- matchmaker.Object.GroupFormed += (object sender, GroupFormedEventArgs args) =>
+ matchmaker.GroupFormed += (object sender, GroupFormedEventArgs args) =>
{
invoked = true;
};
- matchmaker.Object.PerformFullSearch();
+ matchmaker.PerformFullSearch();
Assert.IsFalse(invoked);
}
- [TestMethod]
+ [Test]
public void TestMatchmakerMixed()
{
TestEntity[] group = new TestEntity[] { new TestEntity(1f), new TestEntity(1f), new TestEntity(1f) };
TestEntity individual = new TestEntity(1f);
- matchmaker.Object.EnqueueGroup(group, null);
- matchmaker.Object.Enqueue(individual, null);
+ matchmaker.EnqueueGroup(group, null);
+ matchmaker.Enqueue(individual, null);
bool invoked = false;
- matchmaker.Object.GroupFormed += (object sender, GroupFormedEventArgs args) =>
+ matchmaker.GroupFormed += (object sender, GroupFormedEventArgs args) =>
{
invoked = true;
@@ -216,30 +256,9 @@ public void TestMatchmakerMixed()
Assert.IsTrue(args.Group.Contains(group[2]));
};
- matchmaker.Object.PerformFullSearch();
+ matchmaker.PerformFullSearch();
Assert.IsTrue(invoked);
}
-
- public class TestEntity
- {
- public float Mmr { get; }
-
- public TestEntity(float mmr)
- {
- if (mmr < 0 || mmr > 1)
- throw new ArgumentException("Invalid MMR.");
-
- this.Mmr = mmr;
- }
- }
-
- private class TestRankingProvider
- {
- public float GetSuitabilityMetric(TestEntity entity1, TestEntity entity2, MatchRankingContext context)
- {
- return entity1.Mmr + entity2.Mmr / 2;
- }
- }
}
}
diff --git a/DarkRift.Server.Console/Properties/AssemblyInfo.cs b/DarkRift.Server/AssemblyInfo.cs
similarity index 58%
rename from DarkRift.Server.Console/Properties/AssemblyInfo.cs
rename to DarkRift.Server/AssemblyInfo.cs
index cf577cc..000bc8a 100644
--- a/DarkRift.Server.Console/Properties/AssemblyInfo.cs
+++ b/DarkRift.Server/AssemblyInfo.cs
@@ -4,4 +4,8 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
+using System.Reflection;
+using System.Runtime.CompilerServices;
+[assembly: DarkRift.Preserve]
+[assembly: InternalsVisibleTo("DarkRift.Server.Tests")]
diff --git a/DarkRift.Server.Testing/Properties/AssemblyInfo.cs b/DarkRift.Server/AssemblyInfo.gen.cs
similarity index 53%
rename from DarkRift.Server.Testing/Properties/AssemblyInfo.cs
rename to DarkRift.Server/AssemblyInfo.gen.cs
index 4b4a452..47dbff7 100644
--- a/DarkRift.Server.Testing/Properties/AssemblyInfo.cs
+++ b/DarkRift.Server/AssemblyInfo.gen.cs
@@ -4,3 +4,7 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
+//
+// Do not modify this file manually
+// This file is is updated based on the version found on package.json
+[assembly: System.Reflection.AssemblyVersion("2.10.1")]
diff --git a/DarkRift.Server/DarkRift.Server.asmdef b/DarkRift.Server/DarkRift.Server.asmdef
new file mode 100644
index 0000000..bf106d0
--- /dev/null
+++ b/DarkRift.Server/DarkRift.Server.asmdef
@@ -0,0 +1,19 @@
+{
+ "name": "DarkRift.Server",
+ "rootNamespace": "",
+ "references": [
+ "GUID:74b22b8f1e899468c828514608b766c6",
+ "GUID:76832b94ba439479ca17ebb829c50a03"
+ ],
+ "includePlatforms": [],
+ "excludePlatforms": [],
+ "allowUnsafeCode": false,
+ "overrideReferences": false,
+ "precompiledReferences": [],
+ "autoReferenced": false,
+ "defineConstraints": [
+ "!DARKRIFT_NO_SERVER"
+ ],
+ "versionDefines": [],
+ "noEngineReferences": true
+}
\ No newline at end of file
diff --git a/DarkRift.SystemTesting/Clustering.feature b/DarkRift.SystemTesting/Clustering.feature
deleted file mode 100644
index 99f136d..0000000
--- a/DarkRift.SystemTesting/Clustering.feature
+++ /dev/null
@@ -1,62 +0,0 @@
-Feature: ISC
- AS A game developer
- I WANT to be able to connect servers together
- SO THAT I can scale my system
-
-Scenario: I can connect two servers together
- Given I have a running server from ServerInGroup1.config and ClusterWithTwoGroups.config
- And I have a running server from ServerInGroup2.config and ClusterWithTwoGroups.config
- Then server 0 should synchronise to have 1 server in Group2
- And server 1 should synchronise to have 1 server in Group1
- And there are no recycling issues
- And the ServerConnected event has been fired 2 times
-
-Scenario Outline: I can send a message to an upstream server
- Given I have a running server from ServerInGroup1.config and ClusterWithTwoGroups.config
- And I have a running server from ServerInGroup2.config and ClusterWithTwoGroups.config
- Then server 0 should synchronise to have 1 server in Group2
- And server 1 should synchronise to have 1 server in Group1
- When server 0 sends 'Hello World' to server 1 in Group2 with tag 7
- And server 1 has received 1 message
- Then all messages are accounted for
- And there are no recycling issues
-
- Examples:
- | mode |
- | reliably |
- | unreliably |
-
-Scenario Outline: I can send a message to a downstream server
- Given I have a running server from ServerInGroup1.config and ClusterWithTwoGroups.config
- And I have a running server from ServerInGroup2.config and ClusterWithTwoGroups.config
- Then server 0 should synchronise to have 1 server in Group2
- And server 1 should synchronise to have 1 server in Group1
- When server 1 sends 'Hello World' to server 0 in Group1 with tag 7
- And server 0 has received 1 message
- Then all messages are accounted for
- And there are no recycling issues
-
- Examples:
- | mode |
- | reliably |
- | unreliably |
-
-Scenario: Servers can join during a scenario
- Given I have a running server from ServerInGroup1.config and ClusterWithTwoGroups.config
- And I have a running server from ServerInGroup2.config and ClusterWithTwoGroups.config
- Then server 0 should synchronise to have 1 server in Group2
- And server 1 should synchronise to have 1 server in Group1
- And the ServerConnected event has been fired 2 times
- When I have a running server from ServerInGroup2.config and ClusterWithTwoGroups.config
- Then server 0 should synchronise to have 2 servers in Group2
- And server 2 should synchronise to have 1 server in Group1
- And the ServerConnected event has been fired 4 times
-
-Scenario: Servers can leave during a scenario
- Given I have a running server from ServerInGroup1.config and ClusterWithTwoGroups.config
- And I have a running server from ServerInGroup2.config and ClusterWithTwoGroups.config
- Then server 0 should synchronise to have 1 server in Group2
- And server 1 should synchronise to have 1 server in Group1
- When I close server 0
- Then server 1 should synchronise to have 0 servers in Group1
- And the ServerDisconnected event has been fired 1 time
diff --git a/DarkRift.SystemTesting/Configurations/Cluster/ClusterWithTwoGroups.config b/DarkRift.SystemTesting/Configurations/Cluster/ClusterWithTwoGroups.config
deleted file mode 100644
index 3348aa2..0000000
--- a/DarkRift.SystemTesting/Configurations/Cluster/ClusterWithTwoGroups.config
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
diff --git a/DarkRift.SystemTesting/Configurations/Server/Server.config b/DarkRift.SystemTesting/Configurations/Server/Server.config
deleted file mode 100644
index 5b7a10b..0000000
--- a/DarkRift.SystemTesting/Configurations/Server/Server.config
+++ /dev/null
@@ -1,29 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/DarkRift.SystemTesting/Configurations/Server/ServerInGroup1.config b/DarkRift.SystemTesting/Configurations/Server/ServerInGroup1.config
deleted file mode 100644
index 4441b6a..0000000
--- a/DarkRift.SystemTesting/Configurations/Server/ServerInGroup1.config
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/DarkRift.SystemTesting/Configurations/Server/ServerInGroup2.config b/DarkRift.SystemTesting/Configurations/Server/ServerInGroup2.config
deleted file mode 100644
index 6ed4bd2..0000000
--- a/DarkRift.SystemTesting/Configurations/Server/ServerInGroup2.config
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/DarkRift.SystemTesting/Configurations/Server/ServerOnIPv6.config b/DarkRift.SystemTesting/Configurations/Server/ServerOnIPv6.config
deleted file mode 100644
index 7eae378..0000000
--- a/DarkRift.SystemTesting/Configurations/Server/ServerOnIPv6.config
+++ /dev/null
@@ -1,29 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/DarkRift.SystemTesting/Configurations/Server/ServerWithDifferentUdpPort.config b/DarkRift.SystemTesting/Configurations/Server/ServerWithDifferentUdpPort.config
deleted file mode 100644
index 6265919..0000000
--- a/DarkRift.SystemTesting/Configurations/Server/ServerWithDifferentUdpPort.config
+++ /dev/null
@@ -1,29 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/DarkRift.SystemTesting/Configurations/Server/ServerWithHealthCheck.config b/DarkRift.SystemTesting/Configurations/Server/ServerWithHealthCheck.config
deleted file mode 100644
index 73d1691..0000000
--- a/DarkRift.SystemTesting/Configurations/Server/ServerWithHealthCheck.config
+++ /dev/null
@@ -1,31 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/DarkRift.SystemTesting/Configurations/Server/ServerWithNoCache.config b/DarkRift.SystemTesting/Configurations/Server/ServerWithNoCache.config
deleted file mode 100644
index 2bf02ad..0000000
--- a/DarkRift.SystemTesting/Configurations/Server/ServerWithNoCache.config
+++ /dev/null
@@ -1,44 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/DarkRift.SystemTesting/Configurations/Server/ServerWithPrometheusEndpoint.config b/DarkRift.SystemTesting/Configurations/Server/ServerWithPrometheusEndpoint.config
deleted file mode 100644
index ad47ba9..0000000
--- a/DarkRift.SystemTesting/Configurations/Server/ServerWithPrometheusEndpoint.config
+++ /dev/null
@@ -1,35 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/DarkRift.SystemTesting/Connecting.feature b/DarkRift.SystemTesting/Connecting.feature
deleted file mode 100644
index 19bfc3a..0000000
--- a/DarkRift.SystemTesting/Connecting.feature
+++ /dev/null
@@ -1,68 +0,0 @@
-Feature: Connecting
- AS A game developer
- I WANT to be able to connect clients to my servers
- SO THAT I can make multiplayer games
-
-Scenario: I can connect a single client to a server
- Given I have a running server from Server.config
- And 1 client connected
- Then all clients should be connected
- And server 0 should have 1 client
- And there are no recycling issues
-
-Scenario: I can connect multiple clients to a server
- Given I have a running server from Server.config
- And 5 clients connected
- Then all clients should be connected
- And server 0 should have 5 clients
- And there are no recycling issues
-
-Scenario: I can disconnect from a server
- Given I have a running server from Server.config
- And 1 client connected
- Then all clients should be connected
- And server 0 should have 1 client
- When I disconnect client 0
- Then 0 clients should be connected
- And 1 client should be disconnected
- And server 0 should have 0 clients
-
-Scenario: I receive an ID from the server
- Given I have a running server from Server.config
- And 2 clients connected
- Then all clients should be connected
- And server 0 should have 2 clients
- And client 1 has an ID of 1
- And there are no recycling issues
-
-Scenario: I can start and stop multiple servers on the same address/port
- Given I have a running server from Server.config
- When I close and forget server 0
- Then I can start a new server from Server.config
-
-Scenario: I can connect a single client to a server with differing UDP and TCP ports
- Given I have a running server from ServerWithDifferentUdpPort.config
- And 1 client connected
- Then all clients should be connected
- And server 0 should have 1 client
-
-Scenario: I can connect a single client to a server over IPv6
- Given I have a running server from ServerOnIPv6.config
- And 1 client connected over IPv6
- Then all clients should be connected
- And server 0 should have 1 client
- And there are no recycling issues
-
-Scenario: I can query the server's health check
- Given I have a running server from ServerWithHealthCheck.config
- When I query the health check port
- Then the server returns the expected fields
-
-Scenario: I can start and stop multiple servers with health checks
- Given I have a running server from ServerWithHealthCheck.config
- When I close and forget server 0
- Then I can start a new server from ServerWithHealthCheck.config
-
-Scenario: Issue #81 Being unable to connect does not stop the client from closing
- Given 1 client that fails to connect
- Then I can close client 0
diff --git a/DarkRift.SystemTesting/ConnectingSteps.cs b/DarkRift.SystemTesting/ConnectingSteps.cs
deleted file mode 100644
index 0a75fc8..0000000
--- a/DarkRift.SystemTesting/ConnectingSteps.cs
+++ /dev/null
@@ -1,381 +0,0 @@
-/*
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
- */
-
-using DarkRift.Client;
-using DarkRift.Server;
-using DarkRift.Server.Configuration;
-using DarkRift.Server.Plugins.Listeners.Bichannel;
-using DarkRift.SystemTesting.Plugins;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using System.Collections.Specialized;
-using System.Linq;
-using System.Net;
-using System.Net.Sockets;
-using System.Threading;
-using TechTalk.SpecFlow;
-
-namespace DarkRift.SystemTesting
-{
- ///
- /// Steps for basic DarkRift client/server connection operations.
- ///
- [Binding]
- public class ConnectingSteps
- {
- ///
- /// The world to store state in.
- ///
- private readonly World world;
-
- ///
- /// The performance related test steps.
- ///
- private readonly PerformanceSteps performanceSteps;
-
- ///
- /// The thread executing dispatcher tasks.
- ///
- private Thread dispatcherThread;
-
- public ConnectingSteps(World world, PerformanceSteps performanceSteps)
- {
- this.world = world;
- this.performanceSteps = performanceSteps;
- world.ServerJoined += ServerJoined;
- world.ServerLeft += ServerLeft;
- }
-
- private void ServerJoined(object sender, ServerJoinedEventArgs e) {
-#if DEBUG
- // We've just requested a load of objects that wont be returned until we disconnect the servers again
- // UDP receive TCP receive in the connecting server; TCP receive in listening server
- // Only do this once, this event will be fired from both the upstream and downstream server
- if (e.ServerGroup.Direction == ServerConnectionDirection.Downstream)
- performanceSteps.ExpectedUnaccountedForSocketAsyncEventArgs += 3;
-#endif
- }
-
- private void ServerLeft(object sender, ServerLeftEventArgs e)
- {
-#if DEBUG
- // We've just returned a load of objects that we don't normally expect
- // UDP receive TCP receive in the connecting server; TCP receive in listening server
- // Only do this once, this event will be fired from both the upstream and downstream server
- if (e.ServerGroup.Direction == ServerConnectionDirection.Downstream)
- performanceSteps.ExpectedUnaccountedForSocketAsyncEventArgs -= 3;
-#endif
- }
-
- ///
- /// Starts a server.
- ///
- /// The configuration file for the server.
- [Given(@"I have a running server from ([\w\.]+)")]
- public void GivenIHaveARunningServer(string serverConfig)
- {
- NameValueCollection parameters = new NameValueCollection {
- { "port", GetFreePort().ToString() }
- };
-
- DarkRiftServer server = new DarkRiftServer(ServerSpawnData.CreateFromXml("Configurations/Server/" + serverConfig, parameters));
- server.StartServer();
-
- world.AddServer(server);
-
-#if DEBUG
- // We've just requested a load of objects that wont be returned until we close
- // UDP receive TCP accept
- performanceSteps.ExpectedUnaccountedForSocketAsyncEventArgs += 2;
-#endif
- }
-
- ///
- /// Starts a server inside a cluster.
- ///
- /// The configuration file for the server.
- /// The configuration file for the cluster.
- [Given(@"I have a running server from ([\w\.]+) and ([\w\.]+)")]
- [When(@"I have a running server from ([\w\.]+) and ([\w\.]+)")]
- public void GivenIHaveARunningServer(string serverConfig, string clusterConfig)
- {
- NameValueCollection parameters = new NameValueCollection {
- { "port", GetFreePort().ToString() }
- };
-
- DarkRiftServerConfigurationBuilder serverConfigurationBuilder = DarkRiftServerConfigurationBuilder.CreateFromXml("Configurations/Server/" + serverConfig, parameters);
- serverConfigurationBuilder.AddPluginType(typeof(InMemoryServerRegistryConnector));
-
- DarkRiftServer server = new DarkRiftServer(
- serverConfigurationBuilder.ServerSpawnData,
- ClusterSpawnData.CreateFromXml("Configurations/Cluster/" + clusterConfig, new NameValueCollection())
- );
-
- server.StartServer();
-
- world.AddServer(server);
-
-#if DEBUG
- // We've just requested a load of objects that wont be returned until we close
- // UDP receive TCP accept
- performanceSteps.ExpectedUnaccountedForSocketAsyncEventArgs += 2;
-#endif
- }
-
- ///
- /// The specified server is using the dispatcher.
- ///
- [Given(@"server (\d+) is using the dispatcher")]
- public void GivenTheServerIsUsingTheDispatcher(ushort serverID)
- {
- world.GetServer(serverID).ThreadHelper.EventsFromDispatcher = true;
-
- // Create a snapshot view of the server so we have a consistent reference to it between tests
- DarkRiftServer server = world.GetServer(serverID);
- dispatcherThread = new Thread(() =>
- {
- while (!server.Disposed)
- {
- server.DispatcherWaitHandle.WaitOne();
-
- server.ExecuteDispatcherTasks();
- }
- });
- dispatcherThread.Start();
- }
-
- ///
- /// Connects a given number of clients to the server.
- ///
- /// The number of clients to connect.
- [Given(@"(\d+) clients? connected")]
- public void GivenConnectedClients(int numberOfClients)
- {
- for (int i = 0; i < numberOfClients; i++)
- {
- DarkRiftClient client = new DarkRiftClient();
- client.Connect(
- new BichannelClientConnection(
- IPAddress.Loopback,
- world.GetServer(0).ClientManager.Port,
- world.GetServer(0).NetworkListenerManager.GetNetworkListenersByType()[0].UdpPort,
- true
- )
- );
- world.AddClient(client);
-
-#if DEBUG
- // We've just requested a load of objects that wont be returned until we close
- // UDP receive TCP receive in client; TCP receive in server
- performanceSteps.ExpectedUnaccountedForSocketAsyncEventArgs += 3;
-#endif
- }
- }
-
- ///
- /// Connects a given number of clients to the server expecting them to fail to connect.
- ///
- /// The number of clients to fail to connect.
- [Given(@"(\d+) clients? that fails? to connect")]
- public void GivenClientsThatFailToConnect(int numberOfClients)
- {
- for (int i = 0; i < numberOfClients; i++)
- {
- DarkRiftClient client = new DarkRiftClient();
- try
- {
- client.Connect(
- new BichannelClientConnection(
- IPAddress.Loopback,
- 4296, // Don't want to be able to connect so any port is fine
- true
- )
- );
-
- Assert.Fail("Did not expect client to connect successfully.");
- }
- catch (SocketException)
- {
- // Expected
- }
-
- world.AddClient(client);
- }
- }
-
- ///
- /// Connects a given number of clients to the server over IPv6.
- ///
- /// The number of clients to connect.
- [Given(@"^(\d+) clients? connected over IPv6$")]
- public void GivenConnectedClientsOverIPv6(int numberOfClients)
- {
- for (int i = 0; i < numberOfClients; i++)
- {
- DarkRiftClient client = new DarkRiftClient();
- client.Connect(
- new BichannelClientConnection(
- IPAddress.IPv6Loopback,
- world.GetServer(0).ClientManager.Port,
- world.GetServer(0).NetworkListenerManager.GetNetworkListenersByType()[0].UdpPort,
- true
- )
- );
-
- world.AddClient(client);
-#if DEBUG
- // We've just requested a load of objects that wont be returned until we close
- // UDP receive TCP receive in client; TCP receive in server
- performanceSteps.ExpectedUnaccountedForSocketAsyncEventArgs += 3;
-#endif
- }
- }
-
- ///
- /// Checks that all clients created so far are connected to the server.
- ///
- [Then(@"all clients should be (connected|connecting|disconnected|disconnecting|interrupted)")]
- public void AllClientsShouldBe(string expectedState)
- {
- ThenClientsShouldBe(world.GetClients().Count(), expectedState);
- }
-
- ///
- /// Checks that the given number of clients are connected to the server.
- ///
- /// The ID of the server to query.
- /// The number of clients to check for.
- [Then(@"server (\d+) should have (\d+) clients?")]
- public void ThenTheServerShouldHaveClients(ushort serverID, int numberOfClients)
- {
- WaitUtility.WaitUntil("Expected server " + serverID + " to have " + numberOfClients + " clients connected.", () =>
- {
- Assert.AreEqual(numberOfClients, world.GetServer(serverID).ClientManager.Count);
- });
- }
-
- ///
- /// Disconnects the specified client.
- ///
- /// The client to disconnect.
- [When(@"I disconnect client (\d+)")]
- public void WhenIDisconnectClient(ushort client)
- {
- world.GetClient(client).Disconnect();
-
-#if DEBUG
- // We've just returned a load of objects that we don't normally expect
- // UDP receive TCP receive in client; TCP receive in server
- performanceSteps.ExpectedUnaccountedForSocketAsyncEventArgs -= 3;
-#endif
- }
-
- [Then(@"(\d+) clients? should be (connected|connecting|disconnected|disconnecting|interrupted)")]
- public void ThenClientsShouldBe(int numberOfClients, string state)
- {
- ConnectionState expectedState;
- if (state == "connected")
- expectedState = ConnectionState.Connected;
- else if (state == "connecting")
- expectedState = ConnectionState.Connecting;
- else if (state == "disconnected")
- expectedState = ConnectionState.Disconnected;
- else if (state == "disconnecting")
- expectedState = ConnectionState.Disconnecting;
- else if (state == "interrupted")
- expectedState = ConnectionState.Interrupted;
- else
- throw new ArgumentException("Invalid expected state");
-
- int count = world.GetClients().Count(c => c.ConnectionState == expectedState);
- Assert.AreEqual(numberOfClients, count);
- }
-
- //TODO the below step is pointless as we access by ID
- [Then(@"client (\d+) has an ID of (\d+)")]
- public void ThenClientHasAnIDOf(ushort client, int id)
- {
- Assert.AreEqual(id, world.GetClient(client).ID);
- }
-
- [Then(@"I can start a new server from ([\w\.]+)")]
- public void ThenICanStartANewServerFrom(string config)
- {
- GivenIHaveARunningServer(config);
- }
-
- [Then(@"server (\d)+ should synchronise to have (\d+) servers? in (\w+)")]
- public void ThenServerShouldSynchroniseToHaveServersInGroup(ushort serverID, ushort numberOfServers, string group)
- {
- // 30 second wait as we only update every 10
- WaitUtility.WaitUntil("Incorrect number of servers present in group " + group + ".", () =>
- {
- Assert.AreEqual(numberOfServers, world.GetServer(serverID).RemoteServerManager.GetGroup(group).Count);
- }, TimeSpan.FromSeconds(30));
-
- WaitUtility.WaitUntil("Servers in group " + group + " are not all connected.", () =>
- {
- Assert.IsTrue(
- world.GetServer(serverID)
- .RemoteServerManager.GetGroup(group)
- .GetAllRemoteServers()
- .All(s => s.ConnectionState == ConnectionState.Connected)
- );
- });
- }
-
- [When(@"I close (and forget )?server (\d+)")]
- public void WhenICloseServer(string andForget, ushort server)
- {
- world.GetServer(server).Dispose();
-
- if (andForget != "")
- world.RemoveServer(server);
-
-#if DEBUG
- // We've just returned a load of objects that we don't normally expect
- // UDP receive, TCP accept
- performanceSteps.ExpectedUnaccountedForSocketAsyncEventArgs -= 2;
-#endif
- }
-
- [Then(@"the ServerConnected event has been fired (\d) times?$")]
- public void ThenTheServerConnectedEventHasBeenFired(int times)
- {
- Assert.AreEqual(times, world.ServerConnectedEvents);
- }
-
- [Then(@"the ServerDisconnected event has been fired (\d) times?$")]
- public void ThenTheServerDisconnectedEventHasBeenFired(int times)
- {
- Assert.AreEqual(times, world.ServerDisconnectedEvents);
- }
-
- [Then(@"I can close client (\d+)")]
- public void ThenICanClose(ushort client)
- {
- world.GetClient(client).Dispose();
- }
-
- [Given(@"a delay of (\d+)ms when a client connects before assigning message handlers")]
- public void GivenADelayWhenAClientConnectsBeforeAssigningMessageHandlers(int delayMs)
- {
- world.ClientConnectionDelay = delayMs;
- }
-
- ///
- /// Returns a port that is unallocated.
- ///
- /// The port found.
- private ushort GetFreePort()
- {
- using Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
-
- socket.Bind(new IPEndPoint(IPAddress.Any, 0));
- return (ushort)((IPEndPoint)socket.LocalEndPoint).Port;
- }
- }
-}
diff --git a/DarkRift.SystemTesting/DarkRift.SystemTesting.csproj b/DarkRift.SystemTesting/DarkRift.SystemTesting.csproj
deleted file mode 100644
index f12deb4..0000000
--- a/DarkRift.SystemTesting/DarkRift.SystemTesting.csproj
+++ /dev/null
@@ -1,64 +0,0 @@
-
-
-
-
-
- net6.0
- Debug;Release
- true
- true
- false
-
-
-
-
-
-
-
-
-
-
-
-
- TRACE;DEBUG
-
-
-
-
-
-
-
-
-
-
- Always
-
-
- Always
-
-
- Always
-
-
- Always
-
-
- Always
-
-
- Always
-
-
- Always
-
-
- Always
-
-
- Always
-
-
- Always
-
-
-
diff --git a/DarkRift.SystemTesting/ExpectedPrometheusMetrics.txt b/DarkRift.SystemTesting/ExpectedPrometheusMetrics.txt
deleted file mode 100644
index f65bd58..0000000
--- a/DarkRift.SystemTesting/ExpectedPrometheusMetrics.txt
+++ /dev/null
@@ -1,51 +0,0 @@
-# HELP client_connected_event_failures The number of failures executing the ClientConnected event.
-# TYPE client_connected_event_failures counter
-darkrift_client_manager_client_connected_event_failures 0
-
-# HELP client_disconnected_event_failures The number of failures executing the ClientDisconnected event.
-# TYPE client_disconnected_event_failures counter
-darkrift_client_manager_client_disconnected_event_failures 0
-
-# HELP connection_attempt_timeouts The number of connection attempts made to this listener that timed out.
-# TYPE connection_attempt_timeouts counter
-darkrift_default_network_listener_connection_attempt_timeouts 0
-
-# HELP clients_connected The number of clients connected to the server.
-# TYPE clients_connected gauge
-darkrift_client_manager_clients_connected 0
-
-# HELP client_connected_event_time The time taken to execute the ClientConnected event.
-# TYPE client_connected_event_time histogram
-darkrift_client_manager_client_connected_event_time_bucket{le="0.005"} 0
-darkrift_client_manager_client_connected_event_time_bucket{le="0.01"} 0
-darkrift_client_manager_client_connected_event_time_bucket{le="0.02"} 0
-darkrift_client_manager_client_connected_event_time_bucket{le="0.04"} 0
-darkrift_client_manager_client_connected_event_time_bucket{le="0.08"} 0
-darkrift_client_manager_client_connected_event_time_bucket{le="0.16"} 0
-darkrift_client_manager_client_connected_event_time_bucket{le="0.5"} 0
-darkrift_client_manager_client_connected_event_time_bucket{le="1"} 0
-darkrift_client_manager_client_connected_event_time_bucket{le="2"} 0
-darkrift_client_manager_client_connected_event_time_bucket{le="5"} 0
-darkrift_client_manager_client_connected_event_time_bucket{le="10"} 0
-darkrift_client_manager_client_connected_event_time_bucket{le="+Inf"} 0
-darkrift_client_manager_client_connected_event_time_sum 0
-darkrift_client_manager_client_connected_event_time_count 0
-
-# HELP client_disconnected_event_time The time taken to execute the ClientDisconnected event.
-# TYPE client_disconnected_event_time histogram
-darkrift_client_manager_client_disconnected_event_time_bucket{le="0.005"} 0
-darkrift_client_manager_client_disconnected_event_time_bucket{le="0.01"} 0
-darkrift_client_manager_client_disconnected_event_time_bucket{le="0.02"} 0
-darkrift_client_manager_client_disconnected_event_time_bucket{le="0.04"} 0
-darkrift_client_manager_client_disconnected_event_time_bucket{le="0.08"} 0
-darkrift_client_manager_client_disconnected_event_time_bucket{le="0.16"} 0
-darkrift_client_manager_client_disconnected_event_time_bucket{le="0.5"} 0
-darkrift_client_manager_client_disconnected_event_time_bucket{le="1"} 0
-darkrift_client_manager_client_disconnected_event_time_bucket{le="2"} 0
-darkrift_client_manager_client_disconnected_event_time_bucket{le="5"} 0
-darkrift_client_manager_client_disconnected_event_time_bucket{le="10"} 0
-darkrift_client_manager_client_disconnected_event_time_bucket{le="+Inf"} 0
-darkrift_client_manager_client_disconnected_event_time_sum 0
-darkrift_client_manager_client_disconnected_event_time_count 0
-
-
diff --git a/DarkRift.SystemTesting/HealthCheckSteps.cs b/DarkRift.SystemTesting/HealthCheckSteps.cs
deleted file mode 100644
index 46774b4..0000000
--- a/DarkRift.SystemTesting/HealthCheckSteps.cs
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
- */
-
-using System;
-using System.Net;
-using System.Net.Http;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Newtonsoft.Json;
-using TechTalk.SpecFlow;
-using static DarkRift.Server.DarkRiftInfo;
-
-namespace DarkRift.SystemTesting
-{
- ///
- /// Steps for testing the server's health check
- ///
- [Binding]
- internal class HealthCheckSteps
- {
- ///
- /// The world to store state in.
- ///
- private readonly World world;
-
- ///
- /// The downloaded health check data.
- ///
- private string jsonString;
-
- public HealthCheckSteps(World world)
- {
- this.world = world;
- }
-
- [When("I query the health check port")]
- public void WhenIQueryTheHealthCheckPort()
- {
- using HttpClient httpClient = new HttpClient();
- HttpResponseMessage response = httpClient.GetAsync("http://localhost:10666/health").Result;
- Assert.IsTrue(response.IsSuccessStatusCode);
- jsonString = response.Content.ReadAsStringAsync().Result;
- }
-
- [Then("the server returns the expected fields")]
- public void ThenTheServerReturnsTheExpectedFields()
- {
- HealthCheckObject healthcheckObject = JsonConvert.DeserializeObject(jsonString);
-
- Assert.IsTrue(healthcheckObject.Listening, "Expected the health check to report the server is listening.");
- Assert.AreEqual(0, (world.GetServer(0).ServerInfo.StartTime - healthcheckObject.StartTime).TotalSeconds, 1, "Expected the health check start time to be within a second of the actual.");
-
-#pragma warning disable CS0618 // Testing obsolete functionality
- Assert.AreEqual(world.GetServer(0).ServerInfo.Type, healthcheckObject.Type, "Expected the health check to report the correct DarkRift tier.");
-#pragma warning restore CS0618
- Assert.AreEqual(world.GetServer(0).ServerInfo.Version, healthcheckObject.Version, "Expected the health check to report the correct DarkRift version.");
- }
-
- private class HealthCheckObject
- {
- public bool Listening { get; set; }
- public DateTime StartTime { get; set; }
- public ServerType Type { get; set; }
- public Version Version { get; set; }
- }
- }
-}
diff --git a/DarkRift.SystemTesting/MessageAssertions.cs b/DarkRift.SystemTesting/MessageAssertions.cs
deleted file mode 100644
index 24a15b7..0000000
--- a/DarkRift.SystemTesting/MessageAssertions.cs
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
- */
-
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using System.Collections.Concurrent;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using TechTalk.SpecFlow;
-
-namespace DarkRift.SystemTesting
-{
- [Binding]
- public class MessageAssertions
- {
- ///
- /// The messages received by the server so far.
- ///
- private ConcurrentQueue messagesToServer;
-
- ///
- /// The messages received by the clients so far.
- ///
- private ConcurrentQueue messagesToClients;
-
- ///
- /// The messages expected to be received by the server.
- ///
- private ConcurrentBag expectedToServer;
-
- ///
- /// The messages expected to be received by the clients.
- ///
- private ConcurrentBag expectedToClients;
-
- ///
- /// Sets up the assertions.
- ///
- [BeforeScenario]
- public void BeforeScenario()
- {
- messagesToServer = new ConcurrentQueue();
- messagesToClients = new ConcurrentQueue();
-
- expectedToServer = new ConcurrentBag();
- expectedToClients = new ConcurrentBag();
- }
-
- ///
- /// Adds a message expected to be received on the client.
- ///
- /// The message expected to be recieved.
- public void ExpectMessageOnClient(ReceivedMessage message)
- {
- expectedToClients.Add(message);
- }
-
- ///
- /// Adds a message expected to be received on the server.
- ///
- /// The message expected to be recieved.
- public void ExpectMessageOnServer(ReceivedMessage message)
- {
- expectedToServer.Add(message);
- }
-
- ///
- /// Adds a message received on the client.
- ///
- /// The message recieved.
- public void AddMessageOnClient(ReceivedMessage message)
- {
- messagesToClients.Enqueue(message);
- }
-
- ///
- /// Adds a message received on the server.
- ///
- /// The message recieved.
- public void AddMessageOnServer(ReceivedMessage message)
- {
- messagesToServer.Enqueue(message);
- }
-
- ///
- /// Asserts that all messages exected to be received from other steps have been received, and no more.
- ///
- [Then(@"all messages are accounted for")]
- public void ThenAllMessagesAreAccountedFor()
- {
- WaitUtility.WaitUntil("Not all messages received by the server in the given time.",
- () => Assert.AreEqual(0, expectedToServer.Except(messagesToServer).Count()),
- TimeSpan.FromMinutes(1));
- WaitUtility.WaitUntil("Not all messages received by the clients in the given time.",
- () => Assert.AreEqual(0, expectedToClients.Except(messagesToClients).Count()),
- TimeSpan.FromMinutes(1));
-
- Assert.AreEqual(0, messagesToServer.Except(expectedToServer).Count(), "Additional, unexpected messages received by the server.");
- Assert.AreEqual(0, messagesToClients.Except(expectedToClients).Count(), "Additional, unexpected messages received by the clients.");
- }
-
- ///
- /// Waits for the specified client to have recieved the specified number of messages.
- ///
- /// The client to wait on.
- /// The number of messages to wait for.
- [When(@"client (\d+) has received (\d+) messages?")]
- public void WhenTheClientHasReceivedMessages(ushort client, int numberOfMessages)
- {
- WaitUtility.WaitUntil($"Not enough messages were received on the client within the time limit. Expected at least <{numberOfMessages}> Actual <{messagesToClients.Where(m => m.Source == client).Count()}>",
- () => messagesToClients.Where(m => m.Destination == client).Count() >= numberOfMessages);
- }
-
- ///
- /// Waits for the server to receive the given number of messages.
- ///
- /// The sever to wait on.
- /// The number of messages to wait for.
- [When(@"^server (\d+) has received (\d+) messages?$")]
- public void WhenTheServerHasReceivedMessage(ushort server, int numberOfMessages)
- {
- WaitUtility.WaitUntil($"Not enough messages were received on the server within the time limit. Expected as least <{numberOfMessages}> Actual <{messagesToServer.Where(m => m.Destination == server).Count()}>",
- () => messagesToServer.Where(m => m.Destination == server).Count() >= numberOfMessages);
- }
- }
-}
diff --git a/DarkRift.SystemTesting/Messaging.feature b/DarkRift.SystemTesting/Messaging.feature
deleted file mode 100644
index 8af7b55..0000000
--- a/DarkRift.SystemTesting/Messaging.feature
+++ /dev/null
@@ -1,189 +0,0 @@
-Feature: Messaging
- AS A game developer
- I WANT to be able to send messages between server and client
- SO THAT I can exchange game data
-
-Scenario Outline: I can send a message from client to server
- Given I have a running server from Server.config
- And 1 client connected
- When client 0 sends 'Hello World' with tag 5
- And server 0 has received 1 message
- Then all messages are accounted for
- And there are no recycling issues
-
- Examples:
- | mode |
- | reliably |
- | unreliably |
-
-Scenario Outline: I can send a message from server to client
- Given I have a running server from Server.config
- And 1 client connected
- When server 0 sends 'Hello World' to client 0 with tag 6
- And client 0 has received 1 message
- Then all messages are accounted for
- And there are no recycling issues
-
- Examples:
- | mode |
- | reliably |
- | unreliably |
-
-Scenario Outline: I can get ping the from the client
- Given I have a running server from Server.config
- And the server acknowledges ping messages after 55ms
- And 1 client connected
- When client 0 sends 'Hello World' with tag 5 as a ping
- And server 0 has received 1 message
- And client 0 has received 1 message
- Then all messages are accounted for
- And client 0 has a ping of around 50ms to the server
-
- Examples:
- | mode |
- | reliably |
- | unreliably |
-
-Scenario Outline: I can get the ping from the server
- Given I have a running server from Server.config
- And 1 client connected
- And client 0 acknowledges ping messages after 55ms
- When server 0 sends 'Hello World' to client 0 with tag 6 as a ping
- And client 0 has received 1 message
- And server 0 has received 1 message
- Then all messages are accounted for
- And server 0 has a ping of around 50ms to client 0
-
- Examples:
- | mode |
- | reliably |
- | unreliably |
-
-Scenario Outline: I can stress test client to server
- Given I have a running server from Server.config
- And clients connected
- When I stress test client to server with per client
- Then all messages are accounted for
- And there are no recycling issues
-
- Examples:
- | clients | messages |
- | 5 | 100 |
- | 5 | 1000 |
- | 5 | 10000 |
- | 50 | 100 |
- | 50 | 1000 |
- | 50 | 10000 |
-
-Scenario Outline: I can stress test client to server with dispatcher enabled on server
- Given I have a running server from Server.config
- And server 0 is using the dispatcher
- And clients connected
- When I stress test client to server with per client
- Then all messages are accounted for
- And there are no recycling issues
-
- Examples:
- | clients | messages |
- | 5 | 100 |
- | 5 | 1000 |
- | 5 | 10000 |
- | 50 | 100 |
- | 50 | 1000 |
- | 50 | 10000 |
-
-Scenario Outline: I can stress test server to client
- Given I have a running server from Server.config
- And clients connected
- When I stress test server to client with per client
- Then all messages are accounted for
- And there are no recycling issues
-
- Examples:
- | clients | messages |
- | 5 | 100 |
- | 5 | 1000 |
- | 5 | 10000 |
- | 50 | 100 |
- | 50 | 1000 |
- | 50 | 10000 |
-
-Scenario Outline: I can stress test server to client with dispatcher enabled on server
- Given I have a running server from Server.config
- And server 0 is using the dispatcher
- And clients connected
- When I stress test server to client with per client
- Then all messages are accounted for
- And there are no recycling issues
-
- Examples:
- | clients | messages |
- | 5 | 100 |
- | 5 | 1000 |
- | 5 | 10000 |
- | 50 | 100 |
- | 50 | 1000 |
- | 50 | 10000 |
-
-Scenario Outline: I can stress test both
- Given I have a running server from Server.config
- And clients connected
- When I stress test both with per client
- Then all messages are accounted for
- And there are no recycling issues
-
- Examples:
- | clients | messages |
- | 5 | 100 |
- | 5 | 1000 |
- | 5 | 10000 |
- | 50 | 100 |
- | 50 | 1000 |
- | 50 | 10000 |
-
-Scenario Outline: I can stress test both with dispatcher enabled on server
- Given I have a running server from Server.config
- And server 0 is using the dispatcher
- And clients connected
- When I stress test both with per client
- Then all messages are accounted for
- And there are no recycling issues
-
- Examples:
- | clients | messages |
- | 5 | 100 |
- | 5 | 1000 |
- | 5 | 10000 |
- | 50 | 100 |
- | 50 | 1000 |
- | 50 | 10000 |
-
-# TODO add stress test with client dispatchers enabled
-
-Scenario: Issue #75 messages being corrupted
- Given I have a running server from Server.config
- And server 0 is using the dispatcher
- And 1 client connected
- When I send 5000 messages reliably
- Then all messages are accounted for
-
-Scenario: Partial TCP headers do not disconnect client
- Given I have a running server from Server.config
- And TCP and UDP sockets connected
- And no delay is enabled
- And the handshake has completed
- When bytes are sent via TCP 0, 0
- Then the TCP socket is connected
- When bytes are sent via TCP 0, 11
- Then the TCP socket is connected
- # TODO DR3 sort the fact that strings are little endian while DR is big endian
- When bytes are sent via TCP 0, 0, 0, 0, 0, 0, 4, 72, 0, 105, 0
- Then the TCP socket is connected
- And I receive string on the server from TCP 'Hi'
- And the TCP socket is connected
-
-Scenario: Clients can send messages as soon as they are connected
- Given I have a running server from Server.config
- And a delay of 100ms when a client connects before assigning message handlers
- When a client connects and immediately sends a message
- Then all messages are accounted for
diff --git a/DarkRift.SystemTesting/MessagingSteps.cs b/DarkRift.SystemTesting/MessagingSteps.cs
deleted file mode 100644
index 6f2a59a..0000000
--- a/DarkRift.SystemTesting/MessagingSteps.cs
+++ /dev/null
@@ -1,378 +0,0 @@
-/*
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
- */
-
-using System;
-using System.Collections.Concurrent;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Net;
-using System.Text.RegularExpressions;
-using System.Threading;
-using DarkRift.Client;
-using DarkRift.Server;
-using DarkRift.Server.Plugins.Listeners.Bichannel;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using TechTalk.SpecFlow;
-
-namespace DarkRift.SystemTesting
-{
- ///
- /// Steps for basic message sending/receiveing.
- ///
- [Binding]
- public class MessagingSteps
- {
- ///
- /// The world to store state in.
- ///
- private readonly World world;
-
- ///
- /// The delay the server should acknowledge ping messages after, or -1 if not.
- ///
- private int serverAcknowledgesPingsAfter = -1;
-
- ///
- /// Class for asserting messages received.
- ///
- private readonly MessageAssertions messageAssertions;
-
-
- ///
- /// The performance related test steps.
- ///
- private readonly PerformanceSteps performanceSteps;
-
- public MessagingSteps(World world, MessageAssertions messageAssertions, PerformanceSteps performanceSteps)
- {
- this.world = world;
- this.messageAssertions = messageAssertions;
- this.performanceSteps = performanceSteps;
-
- world.ServerMessageReceived += ServerMessageReceived;
- }
-
- private void ServerMessageReceived(object sender, Server.MessageReceivedEventArgs args)
- {
- // Make sure any ping messages get acknowledged
- using Message message = args.GetMessage();
- if (serverAcknowledgesPingsAfter != -1 && message.IsPingMessage)
- {
- using Message acknowledgment = Message.CreateEmpty(message.Tag);
- acknowledgment.MakePingAcknowledgementMessage(message);
-
- Thread.Sleep(serverAcknowledgesPingsAfter);
-
- bool success = args.Client.SendMessage(acknowledgment, args.SendMode);
- Assert.IsTrue(success);
- messageAssertions.ExpectMessageOnClient(new ReceivedMessage(null, ushort.MaxValue, args.Client.ID, message.Tag, args.SendMode));
- }
- }
-
- ///
- /// Sends a message from a client.
- ///
- /// The client to send from.
- /// The message to send as a string.
- /// The tag to send the message with.
- [When(@"client (\d+) sends '([\w\s]+)' with tag (\d+) (reliably|unreliably)( as a ping)?")]
- public void WhenClientSendsWithTag(ushort client, string str, ushort tag, string mode, string isPing)
- {
- SendMode sendMode = mode == "reliably" ? SendMode.Reliable : SendMode.Unreliable;
-
- using (DarkRiftWriter writer = DarkRiftWriter.Create())
- {
- writer.Write(str);
- using Message message = Message.Create(tag, writer);
- if (!string.IsNullOrEmpty(isPing))
- message.MakePingMessage();
-
- bool success = this.world.GetClient(client).SendMessage(message, sendMode);
- Assert.IsTrue(success);
- }
-
- messageAssertions.ExpectMessageOnServer(new ReceivedMessage(str, client, 0, tag, sendMode));
- }
-
- ///
- /// Sends a message from a client with a specific length.
- ///
- /// The client to send from.
- /// The number of characters to send.
- /// The tag to send the message with.
- [When(@"^client (\d+) sends (\d+) characters with tag (\d+) (reliably|unreliably)( as a ping)?$")]
- public void WhenClientSendsBytesWithTag(ushort client, int length, ushort tag, string mode, string isPing)
- {
- SendMode sendMode = mode == "reliably" ? SendMode.Reliable : SendMode.Unreliable;
- string str = new string('*', length);
-
- using (DarkRiftWriter writer = DarkRiftWriter.Create())
- {
- writer.Write(str);
- using Message message = Message.Create(tag, writer);
- if (!string.IsNullOrEmpty(isPing))
- message.MakePingMessage();
-
- this.world.GetClient(client).SendMessage(message, sendMode);
- }
-
- messageAssertions.ExpectMessageOnServer(new ReceivedMessage(str, client, 0, tag, sendMode));
- }
-
- ///
- /// Sends a message from the server to a client.
- ///
- /// The ID of the server to send from.
- /// The string to send the client.
- /// The client to send to.
- /// The tag to send the message with.
- /// The send mode to send the message via.
- [When(@"server (\d+) sends '([\w\s]+)' to client (\d+) with tag (\d+) (reliably|unreliably)( as a ping)?")]
- public void WhenTheServerSendsToClientWithTag(ushort serverID, string str, ushort client, ushort tag, string mode, string isPing)
- {
- SendMode sendMode = mode == "reliably" ? SendMode.Reliable : SendMode.Unreliable;
-
- using (DarkRiftWriter writer = DarkRiftWriter.Create())
- {
- writer.Write(str);
- using Message message = Message.Create(tag, writer);
- if (!string.IsNullOrEmpty(isPing))
- message.MakePingMessage();
-
- bool success = this.world.GetServer(serverID).ClientManager[client].SendMessage(message, sendMode);
- Assert.IsTrue(success);
- }
-
- messageAssertions.ExpectMessageOnClient(new ReceivedMessage(str, ushort.MaxValue, client, tag, sendMode));
- }
-
- ///
- /// Sends a message from a server to another server.
- ///
- /// The server to send from.
- /// The message to send as a string.
- /// The server to send to.
- /// The group of the server to send to. //TODO We should be able to send without this?
- /// The tag to send the message with.
- [When(@"server (\d+) sends '([\w\s]+)' to server (\d+) in (.+) with tag (\d+) (reliably|unreliably)")]
- public void WhenServerSendsToServerInWithTag(ushort server, string str, ushort remoteServer, string group, ushort tag, string mode)
- {
- SendMode sendMode = mode == "reliably" ? SendMode.Reliable : SendMode.Unreliable;
-
- using (DarkRiftWriter writer = DarkRiftWriter.Create())
- {
- writer.Write(str);
- using Message message = Message.Create(tag, writer);
- bool success = this.world.GetServer(server).RemoteServerManager.GetGroup(group).GetRemoteServer(remoteServer).SendMessage(message, sendMode);
- Assert.IsTrue(success);
-
- }
-
- messageAssertions.ExpectMessageOnServer(new ReceivedMessage(str, server, remoteServer, tag, sendMode));
- }
-
- ///
- /// Instructs the server to send a ping acknowledgment for any ping messages received.
- ///
- [Given(@"the server acknowledges ping messages after ([0-9]+)ms")]
- public void GivenTheServerAcknowledgesPingMessages(int delay)
- {
- serverAcknowledgesPingsAfter = delay;
- }
-
- ///
- /// Instructs the specified client to send a ping acknowledgment for any ping messages received.
- ///
- /// The client to setup for.
- [Given(@"client ([0-9]+) acknowledges ping messages after ([0-9]+)ms")]
- public void GivenClientAcknowledgesPingMessages(ushort client, int delay)
- {
- world.GetClient(client).MessageReceived += (sender, args) =>
- {
- using Message message = args.GetMessage();
- if (message.IsPingMessage)
- {
- using Message acknowledgment = message.Clone();
- acknowledgment.MakePingAcknowledgementMessage(message);
-
- Thread.Sleep(delay);
-
- string str;
- using (DarkRiftReader reader = message.GetReader())
- str = reader.ReadString();
-
- bool success = ((DarkRiftClient)sender).SendMessage(acknowledgment, args.SendMode);
- Assert.IsTrue(success);
- messageAssertions.ExpectMessageOnServer(new ReceivedMessage(str, 0, client, message.Tag, args.SendMode));
- }
- };
- }
-
- ///
- /// Checks that the server has a correct ping to the specified client.
- ///
- /// The server to query.
- /// The expected ping.
- /// The client to check against.
- [Then(@"server (\d+) has a ping of around ([0-9]+)ms to client ([0-9]+)")]
- public void ThenServerHasAPingOfAroundToClient(ushort serverID, float expectedPing, ushort client)
- {
- float actualPing = world.GetServer(serverID).ClientManager.GetClient(client).RoundTripTime.LatestRtt * 1000;
- float delta = expectedPing / 2;
-
- Assert.AreEqual(expectedPing, actualPing, delta, $"Expected a ping of {expectedPing}ms +/- {delta}ms but was actually {Math.Round(actualPing)}ms.");
- }
-
- ///
- /// Checks that the given client has a correct ping to the server.
- ///
- /// The expected ping.
- /// The client to query.
- [Then(@"client ([0-9]+) has a ping of around ([0-9]+)ms to the server")]
- public void ThenClientHasAPingOfAroundToTheServer(ushort client, float expectedPing)
- {
- float actualPing = world.GetClient(client).RoundTripTime.LatestRtt * 1000;
- float delta = expectedPing / 2;
-
- Assert.AreEqual(expectedPing, actualPing, delta, $"Expected a ping of {expectedPing}ms +/- {delta}ms but was actually {Math.Round(actualPing)}ms.");
- }
-
- ///
- /// Sends a number of random messages from both server and client all simultaniously.
- ///
- /// The number of messages to send.
- [When(@"I stress test (server to client|client to server|both) with (\d+) per client")]
- public void WhenIStressTestWithPerClient(string direction, int count)
- {
- List threads = new List();
-
- // Send from clients
- if (direction == "client to server" || direction == "both")
- {
- foreach (DarkRiftClient client in world.GetClients())
- {
- threads.Add(new Thread(() =>
- {
- Random random = new Random();
-
- for (int i = 0; i < count; i++)
- {
- string value = random.NextDouble().ToString();
- ushort tag = (ushort)random.Next(65536);
- //SendMode sendMode = random.Next(2) == 0 ? SendMode.Reliable : SendMode.Unreliable;
- SendMode sendMode = SendMode.Reliable; //TODO test unreliable but with less data
-
- using DarkRiftWriter writer = DarkRiftWriter.Create();
- writer.Write(value);
-
- using Message message = Message.Create(tag, writer);
- bool success = client.SendMessage(message, sendMode);
- Assert.IsTrue(success);
- messageAssertions.ExpectMessageOnServer(new ReceivedMessage(value, client.ID, 0, tag, sendMode));
- }
- }));
- }
- }
-
- // Send from server
- if (direction == "server to client" || direction == "both")
- {
- foreach (IClient client in world.GetServer(0).ClientManager.GetAllClients())
- {
- threads.Add(new Thread(() =>
- {
- Random random = new Random();
-
- for (int i = 0; i < count; i++)
- {
- string value = random.NextDouble().ToString();
- ushort tag = (ushort)random.Next(65536);
- //SendMode sendMode = random.Next(2) == 0 ? SendMode.Reliable : SendMode.Unreliable;
- SendMode sendMode = SendMode.Reliable; //TODO test unreliable but with less data
-
- using DarkRiftWriter writer = DarkRiftWriter.Create();
- writer.Write(value);
-
- using Message message = Message.Create(tag, writer);
- bool success = client.SendMessage(message, sendMode);
- Assert.IsTrue(success);
- messageAssertions.ExpectMessageOnClient(new ReceivedMessage(value, ushort.MaxValue, client.ID, tag, sendMode));
- }
- }));
- }
- }
-
- // Start all the threads
- foreach (Thread thread in threads)
- thread.Start();
-
- // Join all the threads
- foreach (Thread thread in threads)
- thread.Join();
- }
-
- ///
- /// Sends lots of reliable data in reproduction of issue #75.
- ///
- [When(@"I send (\d+) messages reliably")]
- public void WhenISendMessagesReliably(int noMessages)
- {
- for (int i = 0; i < noMessages; i++)
- {
- using DarkRiftWriter writer = DarkRiftWriter.Create();
- ushort tag = (ushort)i;
- string value = i.ToString();
- for (int j = 0; j < 30; j++)
- writer.Write(value);
-
- using Message message = Message.Create(tag, writer);
- bool success = world.GetClient(0).SendMessage(message, SendMode.Reliable);
- Assert.IsTrue(success);
-
- messageAssertions.ExpectMessageOnServer(new ReceivedMessage(value, 0, 0, tag, SendMode.Reliable));
- }
- }
-
- ///
- /// Connects client to the server and instantly sends a message.
- ///
- /// The number of clients to connect.
- [When(@"a client connects and immediately sends a message")]
- public void WhenAClientConnectsAndImmedtiatelySendsAMessages()
- {
- DarkRiftClient client = new DarkRiftClient();
- using (DarkRiftWriter writer = DarkRiftWriter.Create())
- {
- writer.Write("Hello");
- using Message message = Message.Create(0, writer);
-
- client.Connect(
- new BichannelClientConnection(
- IPAddress.Loopback,
- world.GetServer(0).ClientManager.Port,
- world.GetServer(0).NetworkListenerManager.GetNetworkListenersByType()[0].UdpPort,
- true
- )
- );
-
- bool success = client.SendMessage(message, SendMode.Reliable);
- Assert.IsTrue(success);
- }
-
-
- world.AddClient(client);
-
-#if DEBUG
- // We've just requested a load of objects that wont be returned until we close
- // UDP receive TCP receive in client; TCP receive in server
- performanceSteps.ExpectedUnaccountedForSocketAsyncEventArgs += 3;
-#endif
-
- messageAssertions.ExpectMessageOnServer(new ReceivedMessage("Hello", client.ID, 0, 0, SendMode.Reliable));
- }
- }
-}
diff --git a/DarkRift.SystemTesting/Metrics.feature b/DarkRift.SystemTesting/Metrics.feature
deleted file mode 100644
index f8bbe82..0000000
--- a/DarkRift.SystemTesting/Metrics.feature
+++ /dev/null
@@ -1,34 +0,0 @@
-Feature: Metric
- AS AN OPS team
- I WANT to monitor DarkRift and our game through industry standard tools
- SO THAT I have visibility into our servers alongside our existing infrastructure
-
-Scenario: I can query the server's Prometheus endpoint
- Given I have a running server from ServerWithPrometheusEndpoint.config
- # TODO connect a client here to get additional metrics
- When I query the Prometheus endpoint
- Then the server returns the metrics in ExpectedPrometheusMetrics.txt
-
-Scenario: I can start and stop multiple servers with Prometheus endpoints
- Given I have a running server from ServerWithPrometheusEndpoint.config
- When I close and forget server 0
- Then I can start a new server from ServerWithPrometheusEndpoint.config
-
-# TODO Add a test that Prometheus exports are Culture independent #106
-
-Scenario: I can query the server's Prometheus endpoint for the correct client count
- Given I have a running server from ServerWithPrometheusEndpoint.config
-
- When I query the Prometheus endpoint
- Then the metric 'darkrift_client_manager_clients_connected' has value 0
-
- Given 1 client connected
- Then server 0 should have 1 client
-
- When I query the Prometheus endpoint
- Then the metric 'darkrift_client_manager_clients_connected' has value 1
-
- When I disconnect client 0
- Then server 0 should have 0 clients
- When I query the Prometheus endpoint
- Then the metric 'darkrift_client_manager_clients_connected' has value 0
diff --git a/DarkRift.SystemTesting/PartialMessagingSteps.cs b/DarkRift.SystemTesting/PartialMessagingSteps.cs
deleted file mode 100644
index e7a6251..0000000
--- a/DarkRift.SystemTesting/PartialMessagingSteps.cs
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
- */
-
-using DarkRift.Server.Plugins.Listeners.Bichannel;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Net;
-using System.Net.Sockets;
-using System.Text;
-using TechTalk.SpecFlow;
-
-namespace DarkRift.SystemTesting
-{
- ///
- /// Steps for sending partial messages and gettting finer control.
- ///
- [Binding]
- public class PartialMessagingSteps
- {
- ///
- /// The TCP socket.
- ///
- private Socket tcpSocket;
-
- ///
- /// The UDP socket.
- ///
- private Socket udpSocket;
-
- ///
- /// The world to store state in.
- ///
- private readonly World world;
-
- ///
- /// Way of asserting messages.
- ///
- private readonly MessageAssertions messageAssertions;
-
- public PartialMessagingSteps(World world, MessageAssertions messageAssertions)
- {
- this.world = world;
- this.messageAssertions = messageAssertions;
- }
-
- ///
- /// Connects raw socket to the server.
- ///
- [Given(@"TCP and UDP sockets connected")]
- public void GivenTCPSocketConnected()
- {
- tcpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- tcpSocket.Connect(new IPEndPoint(IPAddress.Loopback, world.GetServer(0).ClientManager.Port));
-
- udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
- udpSocket.Bind(new IPEndPoint(((IPEndPoint)tcpSocket.LocalEndPoint).Address, 0));
- udpSocket.Connect(new IPEndPoint(IPAddress.Loopback, world.GetServer(0).NetworkListenerManager.GetNetworkListenersByType()[0].UdpPort));
- }
-
- ///
- /// Completes the DR bichannel handshake down this socket.
- ///
- [Given(@"the handshake has completed")]
- public void GivenTheHandshakeHasCompeleted()
- {
- // Receive token
- byte[] tcpBuffer = new byte[9];
- int receivedTcp = tcpSocket.Receive(tcpBuffer);
-
- Assert.AreEqual(9, receivedTcp);
- Assert.AreEqual(0, tcpBuffer[0]);
-
- // Return token
- udpSocket.Send(tcpBuffer);
-
- // Receive punchthrough
- byte[] udpBuffer = new byte[8];
- int receivedUdp = udpSocket.Receive(udpBuffer);
-
- Assert.AreEqual(8, receivedUdp);
- for (int i = 0; i < 8; ++i)
- Assert.AreEqual(tcpBuffer[i + 1], udpBuffer[i], $"Token byte {i} mismatch");
-
- // Stupid race condition to attach the MessageReceived handler
- System.Threading.Thread.Sleep(100);
- }
-
- ///
- /// Enables NoDelay on the TCP socket.
- ///
- [Given(@"no delay is enabled")]
- public void GivenNoDelayIsEnabled()
- {
- tcpSocket.NoDelay = true;
- }
-
- ///
- /// Sends bytes down the TCP socket.
- ///
- [When(@"bytes are sent via TCP (.+)")]
- public void WhenBytesAreSentViaTcp(string byteLine)
- {
- tcpSocket.Send(byteLine.Split(", ").Select(b => byte.Parse(b)).ToArray());
- }
-
- ///
- /// Checks the TCP socket is connected.
- ///
- [Then(@"the TCP socket is connected")]
- public void ThenTheTcpSocketIsConnected()
- {
- Assert.IsTrue(tcpSocket.Connected);
- }
-
- ///
- /// Checks string received in a message on the server.
- ///
- [Then(@"I receive string on the server from TCP '(.+)'")]
- public void ThenIReceiveStringOnTheServerFromTCP(string text)
- {
- messageAssertions.ExpectMessageOnServer(new ReceivedMessage(text, 0, 0, 0, SendMode.Reliable));
- messageAssertions.ThenAllMessagesAreAccountedFor();
- }
- }
-}
diff --git a/DarkRift.SystemTesting/PerformanceSteps.cs b/DarkRift.SystemTesting/PerformanceSteps.cs
deleted file mode 100644
index 08156be..0000000
--- a/DarkRift.SystemTesting/PerformanceSteps.cs
+++ /dev/null
@@ -1,203 +0,0 @@
-/*
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
- */
-
-using System;
-using System.Threading;
-using DarkRift.Client;
-using DarkRift.Server;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using TechTalk.SpecFlow;
-
-namespace DarkRift.SystemTesting
-{
- [Binding]
- public class PerformanceSteps
- {
-
- ///
- /// The number of objects that are allowed to be unaccounted for.
- ///
- public int ExpectedUnaccountedForAutoRecyclingArrays { get; set; } = 0;
-
- ///
- /// The number of objects that are allowed to be unaccounted for.
- ///
- public int ExpectedUnaccountedForDarkRiftReaders { get; set; } = 0;
-
- ///
- /// The number of objects that are allowed to be unaccounted for.
- ///
- public int ExpectedUnaccountedForDarkRiftWriters { get; set; } = 0;
-
- ///
- /// The number of objects that are allowed to be unaccounted for.
- ///
- public int ExpectedUnaccountedForMessages { get; set; } = 0;
-
- ///
- /// The number of objects that are allowed to be unaccounted for.
- ///
- public int ExpectedUnaccountedForMessageBuffers { get; set; } = 0;
-
- ///
- /// The number of objects that are allowed to be unaccounted for.
- ///
- public int ExpectedUnaccountedForSocketAsyncEventArgs { get; set; } = 0;
-
- ///
- /// The number of objects that are allowed to be unaccounted for.
- ///
- public int ExpectedUnaccountedForActionDispatcherTasks { get; set; } = 0;
-
- ///
- /// The number of objects that are allowed to be unaccounted for.
- ///
- public int ExpectedUnaccountedForServerMessageReceviedEventArgs { get; set; } = 0;
-
- ///
- /// The number of objects that are allowed to be unaccounted for.
- ///
- public int ExpectedUnaccountedForServerServerMessageReceviedEventArgs { get; set; } = 0;
-
- ///
- /// The number of objects that are allowed to be unaccounted for.
- ///
- public int ExpectedUnaccountedForClientMessageReceviedEventArgs { get; set; } = 0;
-
- ///
- /// The number of memory segments that are allowed to be unaccounted for.
- ///
- public int ExpectedUnaccountedForMemory { get; set; } = 0;
-
- [BeforeScenario]
- public void BeforeScenario()
- {
-#if DEBUG
- // Ensure recycling issues are not carried over
- ObjectCacheTestHelper.ResetCounters();
- ServerObjectCacheTestHelper.ResetCounters();
- ClientObjectCacheTestHelper.ResetCounters();
-
- ObjectCacheHelper.ResetCounters();
- ServerObjectCacheHelper.ResetCounters();
- ClientObjectCacheHelper.ResetCounters();
-
- ExpectedUnaccountedForAutoRecyclingArrays = 0;
- ExpectedUnaccountedForDarkRiftReaders = 0;
- ExpectedUnaccountedForDarkRiftWriters = 0;
- ExpectedUnaccountedForMessages = 0;
- ExpectedUnaccountedForMessageBuffers = 0;
- ExpectedUnaccountedForSocketAsyncEventArgs = 0;
- ExpectedUnaccountedForActionDispatcherTasks = 0;
- ExpectedUnaccountedForServerMessageReceviedEventArgs = 0;
- ExpectedUnaccountedForServerServerMessageReceviedEventArgs = 0;
- ExpectedUnaccountedForClientMessageReceviedEventArgs = 0;
- ExpectedUnaccountedForMemory = 0;
-#endif
- }
-
- ///
- /// Make sure there are no recycling issues.
- ///
- [Then(@"there are no recycling issues")]
- public void ThenThereAreNoRecyclingWarnings()
- {
- AssertNoRecyclingIssues();
- AssertNoFinalizations();
- }
-
- ///
- /// Asserts that all objects that were allowedUnaccountedFor from the were returned.
- ///
- private void AssertNoRecyclingIssues()
- {
-#if DEBUG
- WaitUtility.WaitUntil("Objects unacounted for.", () => {
- //Check each metric
- int readers = ObjectCacheTestHelper.RetrievedDarkRiftReaders - ObjectCacheTestHelper.ReturnedDarkRiftReaders;
- if (readers != ExpectedUnaccountedForDarkRiftReaders)
- Assert.Fail(readers + " DarkRiftReader objects are unaccounted for. Expected only " + ExpectedUnaccountedForDarkRiftReaders + ".");
-
- int writers = ObjectCacheTestHelper.ReturnedDarkRiftWriters - ObjectCacheTestHelper.ReturnedDarkRiftWriters;
- if (writers != ExpectedUnaccountedForDarkRiftWriters)
- Assert.Fail(writers + " DarkRiftWriter objects are unaccounted for. Expected only " + ExpectedUnaccountedForDarkRiftWriters + ".");
-
- int messages = ObjectCacheTestHelper.ReturnedMessages - ObjectCacheTestHelper.ReturnedMessages;
- if (messages != ExpectedUnaccountedForMessages)
- Assert.Fail(messages + " Message objects are unaccounted for. Expected only " + ExpectedUnaccountedForMessages + ".");
-
- int messageBuffers = ObjectCacheTestHelper.ReturnedMessageBuffers - ObjectCacheTestHelper.ReturnedMessageBuffers;
- if (messageBuffers != ExpectedUnaccountedForMessageBuffers)
- Assert.Fail(messageBuffers + " MessageBuffer objects are unaccounted for. Expected only " + ExpectedUnaccountedForMessageBuffers + ".");
-
- int actionDispatcherTasks = ObjectCacheTestHelper.ReturnedActionDispatcherTasks - ObjectCacheTestHelper.ReturnedActionDispatcherTasks;
- if (actionDispatcherTasks != ExpectedUnaccountedForActionDispatcherTasks)
- Assert.Fail(actionDispatcherTasks + " ActionDispatcherTask objects are unaccounted for. Expected only " + ExpectedUnaccountedForActionDispatcherTasks + ".");
-
- int autoRecyclingArrays = ObjectCacheTestHelper.ReturnedAutoRecyclingArrays - ObjectCacheTestHelper.ReturnedAutoRecyclingArrays;
- if (autoRecyclingArrays != ExpectedUnaccountedForAutoRecyclingArrays)
- Assert.Fail(autoRecyclingArrays + " AutoRecyclingArray objects are unaccounted for. Expected only " + ExpectedUnaccountedForAutoRecyclingArrays + ".");
-
- int socketAsyncEventArgs = ObjectCacheTestHelper.RetrievedSocketAsyncEventArgs - ObjectCacheTestHelper.ReturnedSocketAsyncEventArgs;
- if (socketAsyncEventArgs != ExpectedUnaccountedForSocketAsyncEventArgs)
- Assert.Fail(socketAsyncEventArgs + " SocketAsyncEventArgs objects are unaccounted for. Expected only " + ExpectedUnaccountedForSocketAsyncEventArgs + ".");
-
- int serverMessageReceivedEventArgs = ServerObjectCacheTestHelper.RetrievedMessageReceivedEventArgs - ServerObjectCacheTestHelper.ReturnedMessageReceivedEventArgs;
- if (serverMessageReceivedEventArgs != ExpectedUnaccountedForServerMessageReceviedEventArgs)
- Assert.Fail(serverMessageReceivedEventArgs + " MessageReceivedEventArgs (server) objects are unaccounted for. Expected only " + ExpectedUnaccountedForServerMessageReceviedEventArgs + ".");
-
- int serverServerMessageReceivedEventArgs = ServerObjectCacheTestHelper.RetrievedServerMessageReceivedEventArgs - ServerObjectCacheTestHelper.ReturnedServerMessageReceivedEventArgs;
- if (serverServerMessageReceivedEventArgs != ExpectedUnaccountedForServerMessageReceviedEventArgs)
- Assert.Fail(serverServerMessageReceivedEventArgs + " ServerMessageReceivedEventArgs (server) objects are unaccounted for. Expected only " + ExpectedUnaccountedForServerServerMessageReceviedEventArgs + ".");
-
- int clientMessageReceivedEventArgs = ClientObjectCacheTestHelper.RetrievedMessageReceivedEventArgs - ClientObjectCacheTestHelper.ReturnedMessageReceivedEventArgs;
- if (clientMessageReceivedEventArgs != ExpectedUnaccountedForClientMessageReceviedEventArgs)
- Assert.Fail(clientMessageReceivedEventArgs + " MessageReceivedEventArgs (client) objects are unaccounted for. Expected only " + ExpectedUnaccountedForClientMessageReceviedEventArgs + ".");
-
- int memory = ObjectCacheTestHelper.ReturnedMemory - ObjectCacheTestHelper.ReturnedMemory;
- if (memory != ExpectedUnaccountedForMemory)
- Assert.Fail(memory + " memory segments are unaccounted for. Expected only " + ExpectedUnaccountedForMemory + ".");
- });
-#endif
- }
-
- ///
- /// Asserts that no finalizations on recyclable objects occurred.
- ///
- private void AssertNoFinalizations()
- {
- // Now everything's disposed we can assert that all objects are accounted for
- GC.Collect();
- GC.WaitForPendingFinalizers();
- GC.Collect();
- GC.WaitForPendingFinalizers();
-
- if (ObjectCacheHelper.FinalizedDarkRiftReaders > 0)
- Assert.Fail(ObjectCacheHelper.FinalizedDarkRiftReaders + " DarkRiftReader objects were finalized last period.");
-
- if (ObjectCacheHelper.FinalizedDarkRiftWriters > 0)
- Assert.Fail(ObjectCacheHelper.FinalizedDarkRiftWriters + " DarkRiftWriter objects were finalized last period.");
-
- if (ObjectCacheHelper.FinalizedMessages > 0)
- Assert.Fail(ObjectCacheHelper.FinalizedMessages + " Message objects were finalized last period.");
-
- if (ObjectCacheHelper.FinalizedMessageBuffers > 0)
- Assert.Fail(ObjectCacheHelper.FinalizedMessageBuffers + " MessageBuffer objects were finalized last period.");
-
- if (ObjectCacheHelper.FinalizedAutoRecyclingArrays > 0)
- Assert.Fail(ObjectCacheHelper.FinalizedAutoRecyclingArrays + " AutoRecyclingArray objects were finalized last period.");
-
- if (ServerObjectCacheHelper.FinalizedMessageReceivedEventArgs > 0)
- Assert.Fail(ServerObjectCacheHelper.FinalizedMessageReceivedEventArgs + " MessageReceivedEventArgs (server) objects were finalized last period.");
-
- if (ServerObjectCacheHelper.FinalizedServerMessageReceivedEventArgs > 0)
- Assert.Fail(ServerObjectCacheHelper.FinalizedServerMessageReceivedEventArgs + " ServeMessageReceivedEventArgs (server) objects were finalized last period.");
-
- if (ClientObjectCacheHelper.FinalizedMessageReceivedEventArgs > 0)
- Assert.Fail(ClientObjectCacheHelper.FinalizedMessageReceivedEventArgs + " MessageReceivedEventArgs (client) objects were finalized last period.");
- }
- }
-}
diff --git a/DarkRift.SystemTesting/Plugins/InMemoryServerRegistryConnector.cs b/DarkRift.SystemTesting/Plugins/InMemoryServerRegistryConnector.cs
deleted file mode 100644
index 3a093f2..0000000
--- a/DarkRift.SystemTesting/Plugins/InMemoryServerRegistryConnector.cs
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
- */
-
-using System;
-using System.Collections.Concurrent;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using DarkRift.Server;
-using Timer = DarkRift.Server.Timer;
-
-namespace DarkRift.SystemTesting.Plugins
-{
- ///
- /// Simple server registry that operates in static memory.
- ///
- internal class InMemoryServerRegistryConnector : ServerRegistryConnector
- {
- public override bool ThreadSafe => true;
-
- public override Version Version => new Version(1, 0, 0);
-
- ///
- /// The lookup of servers in the registry.
- ///
- private static readonly ConcurrentDictionary registry = new ConcurrentDictionary();
-
- ///
- /// The last ID allocated.
- ///
- private static int lastId = -1;
-
- ///
- /// The timer this plugin is polling with.
- ///
- private readonly Timer timer;
-
- public InMemoryServerRegistryConnector(ServerRegistryConnectorLoadData serverRegistryConnectorLoadData) : base(serverRegistryConnectorLoadData)
- {
- timer = CreateTimer(1000, 1000, FetchServices);
- }
-
- private void FetchServices(Timer obj)
- {
- var knownServices = RemoteServerManager.GetAllGroups().SelectMany(g => g.GetAllRemoteServers()).Select(s => s.ID);
- var joined = registry.Keys.Except(knownServices);
- var left = knownServices.Except(registry.Keys);
-
- foreach (ushort joinedID in joined)
- {
- if (joinedID != RemoteServerManager.ServerID)
- {
- RegistryEntry service = registry[joinedID];
- string group = service.Group;
-
- Logger.Trace($"Discovered server {joinedID} from group '{group}'.");
-
- HandleServerJoin(joinedID, group, service.Host, service.Port, new Dictionary(service.Properties));
- }
- }
-
- //TODO consider just a set method instead of/as well as join/leave
- foreach (ushort leftID in left)
- {
- if (leftID != RemoteServerManager.ServerID)
- {
- Logger.Trace($"Server {leftID} has left the cluster.");
-
- HandleServerLeave(leftID);
- }
- }
- }
-
- protected override void DeregisterServer()
- {
- bool success = registry.TryRemove(RemoteServerManager.ServerID, out _);
- if (!success)
- throw new InvalidOperationException("Failed to add an entry into the server registry as the ID already existed.");
- }
-
- protected override ushort RegisterServer(string group, string host, ushort port, IDictionary properties)
- {
- ushort id = (ushort)Interlocked.Increment(ref lastId);
-
- bool success = registry.TryAdd(id, new RegistryEntry(group, host, port, properties));
- if (!success)
- throw new InvalidOperationException("Failed to remove entry in the server registry as the ID does not exist.");
-
- return id;
- }
-
- ///
- /// Resets the registry back to its original state ready for the next test.
- ///
- public static void Reset()
- {
- registry.Clear();
- Interlocked.Exchange(ref lastId, -1);
- }
-
- ///
- /// An entry in the server registry.
- ///
- private class RegistryEntry
- {
- public string Group { get; }
- public string Host { get; }
- public ushort Port { get; }
- public IReadOnlyDictionary Properties { get; }
-
- public RegistryEntry(string group, string address, ushort port, IDictionary properties)
- {
- this.Group = group;
- this.Host = address;
- this.Port = port;
- this.Properties = new Dictionary(properties);
- }
- }
-
- protected override void Dispose(bool disposing)
- {
- base.Dispose(disposing);
- timer.Dispose();
- }
- }
-}
diff --git a/DarkRift.SystemTesting/PrometheusSteps.cs b/DarkRift.SystemTesting/PrometheusSteps.cs
deleted file mode 100644
index 3e073d2..0000000
--- a/DarkRift.SystemTesting/PrometheusSteps.cs
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
- */
-
-using System;
-using System.IO;
-using System.Net;
-using System.Net.Http;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Newtonsoft.Json;
-using TechTalk.SpecFlow;
-using static DarkRift.Server.DarkRiftInfo;
-
-namespace DarkRift.SystemTesting
-{
- ///
- /// Steps for testing the server's health check
- ///
- [Binding]
- internal class PrometheusSteps
- {
- ///
- /// The world to store state in.
- ///
- private readonly World world;
-
- ///
- /// The downloaded Prometheus metric data.
- ///
- private string prometheusString;
-
- public PrometheusSteps(World world)
- {
- this.world = world;
- }
-
- [When("I query the Prometheus endpoint")]
- public void WhenIQueryThePrometheusEndpoint()
- {
- using HttpClient httpClient = new HttpClient();
- HttpResponseMessage response = httpClient.GetAsync("http://localhost:9796/metrics").Result;
- Assert.IsTrue(response.IsSuccessStatusCode);
- prometheusString = response.Content.ReadAsStringAsync().Result;
- }
-
- [Then("the server returns the metrics in (.*)")]
- public void ThenTheServerReturnsTheExpectedMetrics(string expectedMetricsFile)
- {
- // Assert line by line for better debugging
- string[] expectedLines = File.ReadAllLines(expectedMetricsFile);
- string[] actualLines = prometheusString.Split('\n');
-
- Assert.AreEqual(expectedLines.Length, actualLines.Length);
- for (int i = 0; i < expectedLines.Length; i++)
- Assert.AreEqual(expectedLines[i], actualLines[i], $"Expected line {i + 1} to match.");
- }
-
- [Then("the metric '(.*)' has value (.*)")]
- public void ThenTheMetricHasValue(string metricName, string value)
- {
- // Assert line by line for better debugging
- string[] lines = prometheusString.Split('\n');
- bool found = false;
- foreach (string line in lines)
- {
- if (line.StartsWith("#") || string.IsNullOrWhiteSpace(line))
- continue;
-
- string[] parts = line.Split(' ');
- Assert.AreEqual(2, parts.Length, $"Metric line '{line}' is invalid.");
- if (parts[0] == metricName)
- {
- if (!found)
- Assert.AreEqual(value, parts[1], $"Value for metric '{metricName}' was unexpected.");
- else
- Assert.Fail($"Duplicate metric '{metricName}' found.");
-
- found = true;
- }
- }
-
- if (!found)
- Assert.Fail($"Metric '{metricName}' was not found.");
- }
- }
-}
diff --git a/DarkRift.SystemTesting/ReceivedMessage.cs b/DarkRift.SystemTesting/ReceivedMessage.cs
deleted file mode 100644
index 0d9a866..0000000
--- a/DarkRift.SystemTesting/ReceivedMessage.cs
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
- */
-
-namespace DarkRift.SystemTesting
-{
- ///
- /// Holder for messages.
- ///
- public struct ReceivedMessage
- {
- public string Message { get; set; }
- public ushort Source { get; set; }
- public ushort Destination { get; set; }
- public ushort Tag { get; set; }
- public SendMode SendMode { get; set; }
-
- public ReceivedMessage(string message, ushort source, ushort destination, ushort tag, SendMode sendMode)
- {
- this.Message = message;
- this.Source = source;
- this.Destination = destination;
- this.Tag = tag;
- this.SendMode = sendMode;
- }
- }
-}
diff --git a/DarkRift.SystemTesting/ReliableOrderTest.cs b/DarkRift.SystemTesting/ReliableOrderTest.cs
deleted file mode 100644
index d424344..0000000
--- a/DarkRift.SystemTesting/ReliableOrderTest.cs
+++ /dev/null
@@ -1,125 +0,0 @@
-using System;
-using System.Collections.Specialized;
-using System.Linq;
-using System.Net;
-using System.Threading;
-using System.Xml.Schema;
-using DarkRift.Client;
-using DarkRift.Server;
-using DarkRift.Server.Plugins.Listeners.Bichannel;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-
-namespace DarkRift.SystemTesting
-{
- [TestClass]
- public class ReliableOrderTest
- {
- [TestMethod]
- public void SendBunchOfMessagesAndExpectOrderedArrivalAtClient()
- {
- void SetupReceiver(DarkRiftClient client, DarkRiftServer server, Action handler)
- {
- void MessageReceived(object sender, Client.MessageReceivedEventArgs e)
- {
- using var message = e.GetMessage();
- handler(message);
- }
-
- client.MessageReceived += MessageReceived;
- }
-
- void Send(DarkRiftClient client, DarkRiftServer server, Message message)
- {
- server.ClientManager.GetAllClients()[0].SendMessage(message, SendMode.Reliable);
- }
-
- SendBunchOfMessagesAndExpectOrderedArrival(SetupReceiver, Send);
- }
-
- [TestMethod]
- public void SendBunchOfMessagesAndExpectOrderedArrivalAtServer()
- {
- void SetupReceiver(DarkRiftClient client, DarkRiftServer server, Action handler)
- {
- void ClientConnected(object sender, ClientConnectedEventArgs e)
- {
- void MessageReceived(object sender, Server.MessageReceivedEventArgs e)
- {
- using var message = e.GetMessage();
- handler(message);
- }
-
- e.Client.MessageReceived += MessageReceived;
- }
-
- server.ClientManager.ClientConnected += ClientConnected;
- }
-
- void Send(DarkRiftClient client, DarkRiftServer server, Message message)
- {
- client.SendMessage(message, SendMode.Reliable);
- }
-
- SendBunchOfMessagesAndExpectOrderedArrival(SetupReceiver, Send);
- }
-
- private void SendBunchOfMessagesAndExpectOrderedArrival(Action> setupReceiver, Action send)
- {
- var spawnData = ServerSpawnData.CreateFromXml("Configurations/Server/Server.config", new NameValueCollection());
- spawnData.EventsFromDispatcher = false;
-
- using var client = new DarkRiftClient();
- using var server = new DarkRiftServer(spawnData);
-
- const int NoDiff = -1;
-
- int receiveCount = 0;
- int sendCount = 0;
- int diffAt = NoDiff;
-
- void MessageReceived(Message message)
- {
- using var reader = message.GetReader();
-
- int receivedNumber = reader.ReadInt32();
- int expectedReceive = receiveCount;
-
- if (expectedReceive != receivedNumber && diffAt == NoDiff)
- {
- //can't do asserts on other thread so defer to main thread
- diffAt = expectedReceive;
- }
-
- Interlocked.Increment(ref receiveCount);
- }
-
- setupReceiver(client, server, MessageReceived);
-
- server.StartServer();
- var listener = (AbstractBichannelListener)server.NetworkListenerManager.GetAllNetworkListeners().First();
- int port = listener.Port;
- int udpPort = listener.UdpPort;
- client.Connect(IPAddress.Parse("127.0.0.1"), port, udpPort, true);
-
- Assert.AreEqual(ConnectionState.Connected, client.ConnectionState);
- Assert.AreEqual(1, server.ClientManager.Count);
-
- for (int i = 0; i < 100000; ++i)
- {
- using var writer = DarkRiftWriter.Create(40);
-
- writer.Write(sendCount);
- Interlocked.Increment(ref sendCount);
-
- using var message = Message.Create(0, writer);
-
- send(client, server, message);
- }
-
- Thread.Sleep(2000); //give receiver time to catch up
-
- Assert.AreEqual(sendCount, receiveCount, "Not all messages sent!");
- Assert.AreEqual(NoDiff, diffAt, "Received in different order");
- }
- }
-}
diff --git a/DarkRift.SystemTesting/Security.feature b/DarkRift.SystemTesting/Security.feature
deleted file mode 100644
index 88c88e1..0000000
--- a/DarkRift.SystemTesting/Security.feature
+++ /dev/null
@@ -1,11 +0,0 @@
-Feature: Security
- AS A game developer
- I WANT no exploitable vulnerablities in my server
- SO THAT users cannot cuase danage to my server
-
-Scenario: large TCP body buffer allocations cause clients to be kicked
- Given I have a running server from Server.config
- And 1 client connected
- When client 0 sends 70000 characters with tag 6 reliably
- Then server 0 should have 0 clients
- # TODO verify strike event was called
diff --git a/DarkRift.SystemTesting/WaitUtility.cs b/DarkRift.SystemTesting/WaitUtility.cs
deleted file mode 100644
index d770c85..0000000
--- a/DarkRift.SystemTesting/WaitUtility.cs
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
- */
-
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using System.Collections.Concurrent;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace DarkRift.SystemTesting
-{
- internal static class WaitUtility
- {
- ///
- /// Waits until the given predicate returns true, failing if it does not return true within 10 seconds.
- ///
- /// The failure message to assert.
- /// The predicate to wait for.
- internal static void WaitUntil(string message, Func predicate)
- {
- WaitUntil(message, predicate, TimeSpan.FromSeconds(10));
- }
-
- ///
- /// Waits until the given predicate returns true, failing if it does not return true within the timeout.
- ///
- /// The failure message to assert.
- /// The predicate to wait for.
- /// The maximum time to wait.
- internal static void WaitUntil(string message, Func predicate, TimeSpan timeout)
- {
- DateTime failAt = DateTime.Now.Add(timeout);
- do
- {
- if (predicate.Invoke())
- return;
-
- Thread.Sleep(100);
- }
- while (DateTime.Now < failAt);
-
- Assert.Fail(message);
- }
-
- ///
- /// Waits until the given assertion passes, failing if it does not pass within 10 seconds.
- ///
- /// The failure message to assert.
- /// The assertion function to wait for.
- internal static void WaitUntil(string message, Action assertion)
- {
- WaitUntil(message, assertion, TimeSpan.FromSeconds(10));
- }
-
- ///
- /// Waits until the given assertion passes, failing if it does not pass within the timeout.
- ///
- /// The failure message to assert.
- /// The assertion function to wait for.
- /// The maximum time to wait.
- internal static void WaitUntil(string message, Action assertion, TimeSpan timeout)
- {
- DateTime failAt = DateTime.Now.Add(timeout);
- Exception lastException = null;
- do
- {
- try
- {
- assertion.Invoke();
- return;
- }
- catch (AssertFailedException e)
- {
- lastException = e;
- }
-
- Thread.Sleep(100);
- }
- while (DateTime.Now < failAt);
-
- Assert.Fail(message + "\nLast failure was:\n" + lastException);
- }
-
- ///
- /// Waits until an element is dequeued from a queue, failing if it does not return a value within 10 seconds.
- ///
- /// The type of element to dequeue.
- /// The queue to dequeue from.
- /// The failure message to assert.
- /// The element dequeued.
- internal static T DequeueFrom(ConcurrentQueue queue, string message)
- {
- return DequeueFrom(queue, message, TimeSpan.FromSeconds(10));
- }
-
- ///
- /// Waits until an element is dequeued from a queue, failing if it does not return a value within the timeout.
- ///
- /// The type of element to dequeue.
- /// The queue to dequeue from.
- /// The failure message to assert.
- /// The maximum time to wait.
- /// The element dequeued.
- internal static T DequeueFrom(ConcurrentQueue queue, string message, TimeSpan timeout)
- {
- T result = default;
-
- WaitUntil(message, () => queue.TryDequeue(out result), timeout);
-
- return result;
- }
- }
-}
diff --git a/DarkRift.SystemTesting/World.cs b/DarkRift.SystemTesting/World.cs
deleted file mode 100644
index d4a3418..0000000
--- a/DarkRift.SystemTesting/World.cs
+++ /dev/null
@@ -1,320 +0,0 @@
-/*
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
- */
-
-using DarkRift.Client;
-using DarkRift.Server;
-using DarkRift.SystemTesting.Plugins;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using System.Collections.Concurrent;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using TechTalk.SpecFlow;
-
-namespace DarkRift.SystemTesting
-{
- ///
- /// General place to hold test data.
- ///
- [Binding]
- public class World
- {
- ///
- /// Event fired whenever the server receives a message.
- ///
- public event EventHandler ServerMessageReceived;
-
- ///
- /// Event fired whenever a server connects to another.
- ///
- public event EventHandler ServerJoined;
-
- ///
- /// Event fired whenever a server disconnects from another.
- ///
- public event EventHandler ServerLeft;
-
- ///
- /// The number of times the ServerConnected event has been fired.
- ///
- public int ServerConnectedEvents => Volatile.Read(ref serverConnectedEvents);
- private int serverConnectedEvents;
-
- ///
- /// The number of times the ServerDisconnected event has been fired.
- ///
- public int ServerDisconnectedEvents => Volatile.Read(ref serverDisconnectedEvents);
- private int serverDisconnectedEvents;
-
- ///
- /// The delay between a client connecting and message handlers being assigned on the server.
- ///
- public int ClientConnectionDelay { get; internal set; }
-
- ///
- /// The servers in use.
- ///
- private readonly Dictionary servers = new Dictionary();
-
- ///
- /// The clients in use.
- ///
- private readonly Dictionary clients = new Dictionary();
-
- ///
- /// Class for asserting messages received.
- ///
- private readonly MessageAssertions messageAssertions;
-
- public World(MessageAssertions messageAssertions)
- {
- this.messageAssertions = messageAssertions;
- }
-
- ///
- /// Clears up the world data.
- ///
- [AfterScenario]
- public void AfterScenario()
- {
- foreach (DarkRiftServer server in servers.Values)
- {
- try
- {
- server.Dispose();
- }
- catch (Exception e)
- {
- Console.WriteLine("An Exception was thrown while disposing the server.\n" + e);
- }
- }
-
- foreach (DarkRiftClient client in clients.Values)
- client.Dispose();
-
- clients.Clear();
- servers.Clear();
-
- Interlocked.Exchange(ref serverConnectedEvents, 0);
- Interlocked.Exchange(ref serverDisconnectedEvents, 0);
-
- // Reset server registry
- InMemoryServerRegistryConnector.Reset();
-
- ClientConnectionDelay = 0;
- }
-
- ///
- /// Adds a new client to the world.
- ///
- /// The client to add.
- public void AddClient(DarkRiftClient client)
- {
- clients.Add(client.ID, client);
-
- client.MessageReceived += ClientMessageReceived;
- }
-
- ///
- /// Adds a new server to the world.
- ///
- /// The serverto add.
- public void AddServer(DarkRiftServer server)
- {
- servers.Add(server.RemoteServerManager.ServerID, server);
-
- server.ClientManager.ClientConnected += (s, a) => ClientConnected(s, a, server.RemoteServerManager.ServerID);
-
- foreach (IServerGroup group in server.RemoteServerManager.GetAllGroups())
- {
- group.ServerJoined += (s, a) => ServerJoinedGroup(s, a, server.RemoteServerManager.ServerID);
- group.ServerLeft += (s, a) => ServerLeftGroup(s, a, server.RemoteServerManager.ServerID);
- }
- }
-
- ///
- /// Gets a client by ID.
- ///
- /// The ID to get.
- public DarkRiftClient GetClient(ushort id)
- {
- return clients[id];
- }
-
- ///
- /// Gets an enumerable of all clienst.
- ///
- /// All clients.
- public IEnumerable GetClients()
- {
- return clients.Values;
- }
-
- ///
- /// Gets a server by ID.
- ///
- /// The ID to get.
- public DarkRiftServer GetServer(ushort id)
- {
- return servers[id];
- }
-
- ///
- /// Gets an enumerable of all servers.
- ///
- /// All servers.
- public IEnumerable GetServers()
- {
- return servers.Values;
- }
-
- ///
- /// Removes the specified server.
- ///
- /// The server to remove.
- public void RemoveServer(ushort id)
- {
- servers.Remove(id);
- }
-
- ///
- /// Event handler for new clients connecting.
- ///
- /// The client manager.
- /// The event args.
- /// The ID of the server the client connected to.
- private void ClientConnected(object _, ClientConnectedEventArgs args, ushort serverID)
- {
- if (ClientConnectionDelay > 0)
- Thread.Sleep(ClientConnectionDelay);
-
- args.Client.MessageReceived += (s, a) => ServerMessageReceivedFromClient(s, a, serverID);
- }
-
- ///
- /// Event handler for messages arriving at a client.
- ///
- /// The client.
- /// The event args.
- private void ClientMessageReceived(object sender, Client.MessageReceivedEventArgs args)
- {
- using Message message = args.GetMessage();
- string str;
- using (DarkRiftReader reader = message.GetReader())
- {
- if (reader.Length > 0)
- str = reader.ReadString();
- else
- str = null;
- }
-
- messageAssertions.AddMessageOnClient(new ReceivedMessage(str, ushort.MaxValue, ((DarkRiftClient)sender).ID, message.Tag, args.SendMode));
-
- }
-
- ///
- /// Event handler for messages arriving at the server from a client.
- ///
- /// The client that sent.
- /// The event args.
- /// The ID of the server that received this message.
- private void ServerMessageReceivedFromClient(object sender, Server.MessageReceivedEventArgs args, ushort serverID)
- {
- // Record message
- using (Message message = args.GetMessage())
- {
- string str;
- using (DarkRiftReader reader = message.GetReader())
- {
- if (reader.Length > 0)
- str = reader.ReadString();
- else
- str = null;
- }
-
- messageAssertions.AddMessageOnServer(new ReceivedMessage(str, args.Client.ID, serverID, message.Tag, args.SendMode));
- }
-
- // Call to other event handlers
- ServerMessageReceived.Invoke(sender, args);
- }
-
- ///
- /// Handles a server joining a group.
- ///
- /// The
- /// The event args.
- /// The ID of the server the server connected to.
- private void ServerJoinedGroup(object sender, ServerJoinedEventArgs e, ushort serverID)
- {
- e.RemoteServer.MessageReceived += (s, a) => ServerMessageReceivedFromServer(s, a, serverID);
- e.RemoteServer.ServerConnected += (s, a) => ServerConnected(s, a, serverID);
- e.RemoteServer.ServerDisconnected += ServerDisconnected;
-
- ServerJoined.Invoke(sender, e);
- }
-
- ///
- /// Handles a server leaving a group.
- ///
- /// The
- /// The event args.
- /// The ID of the server the server connected to.
- private void ServerLeftGroup(object sender, ServerLeftEventArgs e, ushort _)
- {
- // Can't unsubscribe MessageReceived as we're using a lambda, would need to assign it to a reference
- //e.RemoteServer.ServerConnected -= ServerConnected;
- e.RemoteServer.ServerDisconnected -= ServerDisconnected;
-
- ServerLeft.Invoke(sender, e);
- }
-
- ///
- /// Handles a server connecting.
- ///
- /// The
- /// The event args.
- private void ServerConnected(object sender, ServerConnectedEventArgs e, int serverID)
- {
- Interlocked.Increment(ref serverConnectedEvents);
- }
-
- ///
- /// Handles a server disconnecting.
- ///
- /// The
- /// The event args.
- private void ServerDisconnected(object sender, ServerDisconnectedEventArgs e)
- {
- Interlocked.Increment(ref serverDisconnectedEvents);
- }
-
- ///
- /// Event handler for messages arriving at the server from another server.
- ///
- /// The remote server that sent.
- /// The event args.
- /// The ID of the server that received this message.
- private void ServerMessageReceivedFromServer(object _, Server.ServerMessageReceivedEventArgs args, ushort serverID)
- {
- // Record message
- using Message message = args.GetMessage();
-
- string str;
- using (DarkRiftReader reader = message.GetReader()) {
- if (reader.Length > 0)
- str = reader.ReadString();
- else
- str = null;
- }
-
- messageAssertions.AddMessageOnServer(new ReceivedMessage(str, args.RemoteServer.ID, serverID, message.Tag, args.SendMode));
- }
- }
-}
diff --git a/DarkRift.Testing/DarkRift.Testing.csproj b/DarkRift.Testing/DarkRift.Testing.csproj
deleted file mode 100644
index d1a6792..0000000
--- a/DarkRift.Testing/DarkRift.Testing.csproj
+++ /dev/null
@@ -1,29 +0,0 @@
-
-
-
-
-
- net4.5;net6.0
- net6.0
- Debug;Release
- true
-
- NU1701
- false
-
-
-
-
-
-
-
-
-
-
- TRACE;DEBUG
-
-
-
-
-
-
diff --git a/DarkRift.Testing/packages.config b/DarkRift.Testing/packages.config
deleted file mode 100644
index de82217..0000000
--- a/DarkRift.Testing/packages.config
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/DarkRift.Testing/AssertExtensions.cs b/DarkRift.Tests/AssertExtensions.cs
similarity index 58%
rename from DarkRift.Testing/AssertExtensions.cs
rename to DarkRift.Tests/AssertExtensions.cs
index 5894dd0..80bd290 100644
--- a/DarkRift.Testing/AssertExtensions.cs
+++ b/DarkRift.Tests/AssertExtensions.cs
@@ -5,40 +5,46 @@
*/
using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
+using NUnit.Framework;
-namespace DarkRift.Testing
+namespace DarkRift.Tests
{
internal static class AssertExtensions
{
public static void AreEqualAndNotShorter(T[] expected, T[] actual) where T : IEquatable
{
if (actual.Length < expected.Length)
- throw new AssertFailedException("Actual array was too short.");
+ {
+ Assert.Fail("Actual array was too short.");
+ }
for (int i = 0; i < expected.Length; i++)
{
if (!actual[i].Equals(expected[i]))
- throw new AssertFailedException($"Element {i} was incorrect. Exepected: '{expected[i]}', actual: '{actual[i]}'");
+ {
+ Assert.Fail($"Element {i} was incorrect. Exepected: '{expected[i]}', actual: '{actual[i]}'");
+ }
}
}
public static void AreEqualAndSameLength(T[] expected, T[] actual) where T : IEquatable
{
if (actual.Length < expected.Length)
- throw new AssertFailedException("Actual array was too short.");
+ {
+ Assert.Fail("Actual array was too short.");
+ }
if (actual.Length > expected.Length)
- throw new AssertFailedException("Actual array was too long.");
+ {
+ Assert.Fail("Actual array was too long.");
+ }
for (int i = 0; i < expected.Length; i++)
{
if (!actual[i].Equals(expected[i]))
- throw new AssertFailedException($"Element {i} was incorrect. Exepected: '{expected[i]}', actual: '{actual[i]}'");
+ {
+ Assert.Fail($"Element {i} was incorrect. Exepected: '{expected[i]}', actual: '{actual[i]}'");
+ }
}
}
}
diff --git a/DarkRift.Tests/DarkRift.Tests.asmdef b/DarkRift.Tests/DarkRift.Tests.asmdef
new file mode 100644
index 0000000..a0324f2
--- /dev/null
+++ b/DarkRift.Tests/DarkRift.Tests.asmdef
@@ -0,0 +1,24 @@
+{
+ "name": "DarkRift.Tests",
+ "rootNamespace": "",
+ "references": [
+ "GUID:27619889b8ba8c24980f49ee34dbb44a",
+ "GUID:0acc523941302664db1f4e527237feb3",
+ "GUID:74b22b8f1e899468c828514608b766c6"
+ ],
+ "includePlatforms": [
+ "Editor"
+ ],
+ "excludePlatforms": [],
+ "allowUnsafeCode": false,
+ "overrideReferences": true,
+ "precompiledReferences": [
+ "nunit.framework.dll"
+ ],
+ "autoReferenced": true,
+ "defineConstraints": [
+ "UNITY_INCLUDE_TESTS"
+ ],
+ "versionDefines": [],
+ "noEngineReferences": false
+}
\ No newline at end of file
diff --git a/DarkRift.Testing/DarkRiftReaderTests.cs b/DarkRift.Tests/DarkRiftReaderTests.cs
similarity index 50%
rename from DarkRift.Testing/DarkRiftReaderTests.cs
rename to DarkRift.Tests/DarkRiftReaderTests.cs
index 1d4fe3b..2d547b1 100644
--- a/DarkRift.Testing/DarkRiftReaderTests.cs
+++ b/DarkRift.Tests/DarkRiftReaderTests.cs
@@ -4,89 +4,83 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Moq;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace DarkRift.Testing
+using NUnit.Framework;
+
+namespace DarkRift.Tests
{
// TODO test exceptions and exception messages
- [TestClass]
public class DarkRiftReaderTests
{
- private Mock mockMessageBuffer = new Mock();
-
+ private MockMessageBuffer messageBuffer;
private DarkRiftReader reader;
- [TestInitialize]
- public void Initialize()
+ [SetUp]
+ public void SetUp()
{
+ messageBuffer = new MockMessageBuffer();
+
// GIVEN the object cache is disabled
#pragma warning disable CS0618 // We don't care about using Server/Client specific cache settings
ObjectCache.Initialize(ObjectCacheSettings.DontUseCache);
#pragma warning restore CS0618
// AND a DarkRiftReader under test
- reader = DarkRiftReader.Create(mockMessageBuffer.Object);
+ reader = DarkRiftReader.Create(messageBuffer);
}
- [TestMethod]
- public void ReadByteTest()
+ [Test]
+ public void ReadByte()
{
// GIVEN a buffer of serialized data
- mockMessageBuffer.Setup(m => m.Buffer).Returns(new byte[] { 5 });
- mockMessageBuffer.Setup(m => m.Offset).Returns(0);
- mockMessageBuffer.Setup(m => m.Count).Returns(1);
+ messageBuffer.Buffer = new byte[] { 5 };
+ messageBuffer.Offset = 0;
+ messageBuffer.Count = 1;
// WHEN I read a byte from the reader
byte result = reader.ReadByte();
-
+
// THEN the value is as expected
Assert.AreEqual((byte)5, result);
}
- [TestMethod]
- public void ReadCharTest()
+ [Test]
+ public void ReadChar()
{
// GIVEN a buffer of serialized data
- mockMessageBuffer.Setup(m => m.Buffer).Returns(new byte[] { 0, 0, 0, 2, 65, 0 });
- mockMessageBuffer.Setup(m => m.Offset).Returns(0);
- mockMessageBuffer.Setup(m => m.Count).Returns(6);
+ messageBuffer.Buffer = new byte[] { 0, 0, 0, 2, 65, 0 };
+ messageBuffer.Offset = 0;
+ messageBuffer.Count = 6;
// WHEN I read a char from the reader
char result = reader.ReadChar();
-
+
// THEN the value is as expected
Assert.AreEqual('A', result);
}
- [TestMethod]
- public void ReadBooleanTest()
+ [Test]
+ public void ReadBoolean()
{
// GIVEN a buffer of serialized data
- mockMessageBuffer.Setup(m => m.Buffer).Returns(new byte[] { 1 });
- mockMessageBuffer.Setup(m => m.Offset).Returns(0);
- mockMessageBuffer.Setup(m => m.Count).Returns(1);
+ messageBuffer.Buffer = new byte[] { 1 };
+ messageBuffer.Offset = 0;
+ messageBuffer.Count = 1;
// WHEN I read a boolean from the reader
bool result = reader.ReadBoolean();
-
+
// THEN the value is as expected
Assert.AreEqual(true, result);
}
- [TestMethod]
- public void ReadDoubleTest()
+ [Test]
+ public void ReadDouble()
{
// GIVEN a buffer of serialized data
- mockMessageBuffer.Setup(m => m.Buffer).Returns(new byte[] { 0x3f, 0xE8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
- mockMessageBuffer.Setup(m => m.Offset).Returns(0);
- mockMessageBuffer.Setup(m => m.Count).Returns(10);
+ messageBuffer.Buffer = new byte[] { 0x3f, 0xE8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
+ messageBuffer.Offset = 0;
+ messageBuffer.Count = 10;
// WHEN I read a double from the reader
double result = reader.ReadDouble();
@@ -94,14 +88,14 @@ public void ReadDoubleTest()
// THEN the value is as expected
Assert.AreEqual(0.75d, result);
}
-
- [TestMethod]
- public void ReadInt16Test()
+
+ [Test]
+ public void ReadInt16()
{
// GIVEN a buffer of serialized data
- mockMessageBuffer.Setup(m => m.Buffer).Returns(new byte[] { 0xE8, 0xA2 });
- mockMessageBuffer.Setup(m => m.Offset).Returns(0);
- mockMessageBuffer.Setup(m => m.Count).Returns(2);
+ messageBuffer.Buffer = new byte[] { 0xE8, 0xA2 };
+ messageBuffer.Offset = 0;
+ messageBuffer.Count = 2;
// WHEN I read a short from the reader
short result = reader.ReadInt16();
@@ -110,13 +104,13 @@ public void ReadInt16Test()
Assert.AreEqual((short)-5982, result);
}
- [TestMethod]
- public void ReadInt32Test()
+ [Test]
+ public void ReadInt32()
{
// GIVEN a buffer of serialized data
- mockMessageBuffer.Setup(m => m.Buffer).Returns(new byte[] { 0x23, 0x24, 0x30, 0x5C });
- mockMessageBuffer.Setup(m => m.Offset).Returns(0);
- mockMessageBuffer.Setup(m => m.Count).Returns(4);
+ messageBuffer.Buffer = new byte[] { 0x23, 0x24, 0x30, 0x5C };
+ messageBuffer.Offset = 0;
+ messageBuffer.Count = 4;
// WHEN I read an int from the reader
int result = reader.ReadInt32();
@@ -125,13 +119,13 @@ public void ReadInt32Test()
Assert.AreEqual(589574236, result);
}
- [TestMethod]
- public void ReadInt64Test()
+ [Test]
+ public void ReadInt64()
{
// GIVEN a buffer of serialized data
- mockMessageBuffer.Setup(m => m.Buffer).Returns(new byte[] { 0x51, 0xD1, 0xE2, 0x71, 0xCA, 0x29, 0x58, 0x08 });
- mockMessageBuffer.Setup(m => m.Offset).Returns(0);
- mockMessageBuffer.Setup(m => m.Count).Returns(8);
+ messageBuffer.Buffer = new byte[] { 0x51, 0xD1, 0xE2, 0x71, 0xCA, 0x29, 0x58, 0x08 };
+ messageBuffer.Offset = 0;
+ messageBuffer.Count = 8;
// WHEN I read a long from the reader
long result = reader.ReadInt64();
@@ -140,13 +134,13 @@ public void ReadInt64Test()
Assert.AreEqual(5895742365555578888L, result);
}
- [TestMethod]
- public void ReadSByteTest()
+ [Test]
+ public void ReadSByte()
{
// GIVEN a buffer of serialized data
- mockMessageBuffer.Setup(m => m.Buffer).Returns(new byte[] { 0xD3 });
- mockMessageBuffer.Setup(m => m.Offset).Returns(0);
- mockMessageBuffer.Setup(m => m.Count).Returns(1);
+ messageBuffer.Buffer = new byte[] { 0xD3 };
+ messageBuffer.Offset = 0;
+ messageBuffer.Count = 1;
// WHEN I read an sbyte from the reader
sbyte result = reader.ReadSByte();
@@ -155,13 +149,13 @@ public void ReadSByteTest()
Assert.AreEqual((sbyte)-45, result);
}
- [TestMethod]
- public void ReadSingleTest()
+ [Test]
+ public void ReadSingle()
{
// GIVEN a buffer of serialized data
- mockMessageBuffer.Setup(m => m.Buffer).Returns(new byte[] { 0x3f, 0x40, 0x00, 0x00 });
- mockMessageBuffer.Setup(m => m.Offset).Returns(0);
- mockMessageBuffer.Setup(m => m.Count).Returns(4);
+ messageBuffer.Buffer = new byte[] { 0x3f, 0x40, 0x00, 0x00 };
+ messageBuffer.Offset = 0;
+ messageBuffer.Count = 4;
// WHEN I read a float from the reader
float result = reader.ReadSingle();
@@ -170,13 +164,13 @@ public void ReadSingleTest()
Assert.AreEqual(0.75f, result);
}
- [TestMethod]
- public void ReadUInt16Test()
+ [Test]
+ public void ReadUInt16()
{
// GIVEN a buffer of serialized data
- mockMessageBuffer.Setup(m => m.Buffer).Returns(new byte[] { 0xE8, 0xA2 });
- mockMessageBuffer.Setup(m => m.Offset).Returns(0);
- mockMessageBuffer.Setup(m => m.Count).Returns(2);
+ messageBuffer.Buffer = new byte[] { 0xE8, 0xA2 };
+ messageBuffer.Offset = 0;
+ messageBuffer.Count = 2;
// WHEN I read a ushort from the reader
ushort result = reader.ReadUInt16();
@@ -185,13 +179,13 @@ public void ReadUInt16Test()
Assert.AreEqual((ushort)59554, result);
}
- [TestMethod]
- public void ReadUInt32Test()
+ [Test]
+ public void ReadUInt32()
{
// GIVEN a buffer of serialized data
- mockMessageBuffer.Setup(m => m.Buffer).Returns(new byte[] { 0x23, 0x24, 0x30, 0x5C });
- mockMessageBuffer.Setup(m => m.Offset).Returns(0);
- mockMessageBuffer.Setup(m => m.Count).Returns(4);
+ messageBuffer.Buffer = new byte[] { 0x23, 0x24, 0x30, 0x5C };
+ messageBuffer.Offset = 0;
+ messageBuffer.Count = 4;
// WHEN I read a uint from the reader
uint result = reader.ReadUInt32();
@@ -200,13 +194,13 @@ public void ReadUInt32Test()
Assert.AreEqual((uint)589574236, result);
}
- [TestMethod]
- public void ReadUInt64Test()
+ [Test]
+ public void ReadUInt64()
{
// GIVEN a buffer of serialized data
- mockMessageBuffer.Setup(m => m.Buffer).Returns(new byte[] { 0x51, 0xD1, 0xE2, 0x71, 0xCA, 0x29, 0x58, 0x08 });
- mockMessageBuffer.Setup(m => m.Offset).Returns(0);
- mockMessageBuffer.Setup(m => m.Count).Returns(8);
+ messageBuffer.Buffer = new byte[] { 0x51, 0xD1, 0xE2, 0x71, 0xCA, 0x29, 0x58, 0x08 };
+ messageBuffer.Offset = 0;
+ messageBuffer.Count = 8;
// WHEN I read a ulong from the reader
ulong result = reader.ReadUInt64();
@@ -215,13 +209,13 @@ public void ReadUInt64Test()
Assert.AreEqual((ulong)5895742365555578888, result);
}
- [TestMethod]
- public void ReadStringTest()
+ [Test]
+ public void ReadString()
{
// GIVEN a buffer of serialized data
- mockMessageBuffer.Setup(m => m.Buffer).Returns(new byte[] { 0, 0, 0, 6, 65, 0, 66, 0, 67, 0 });
- mockMessageBuffer.Setup(m => m.Offset).Returns(0);
- mockMessageBuffer.Setup(m => m.Count).Returns(10);
+ messageBuffer.Buffer = new byte[] { 0, 0, 0, 6, 65, 0, 66, 0, 67, 0 };
+ messageBuffer.Offset = 0;
+ messageBuffer.Count = 10;
// WHEN I read a string from the reader
string result = reader.ReadString();
@@ -230,13 +224,13 @@ public void ReadStringTest()
Assert.AreEqual("ABC", result);
}
- [TestMethod]
- public void ReadBooleansTest()
+ [Test]
+ public void ReadBooleans()
{
// GIVEN a buffer of serialized data
- mockMessageBuffer.Setup(m => m.Buffer).Returns(new byte[] { 0, 0, 0, 9, 0b11001010, 0b10000000 });
- mockMessageBuffer.Setup(m => m.Offset).Returns(0);
- mockMessageBuffer.Setup(m => m.Count).Returns(6);
+ messageBuffer.Buffer = new byte[] { 0, 0, 0, 9, 0b11001010, 0b10000000 };
+ messageBuffer.Offset = 0;
+ messageBuffer.Count = 6;
// WHEN I read a boolean array from the reader
bool[] result = reader.ReadBooleans();
diff --git a/DarkRift.Testing/DarkRiftWriterTests.cs b/DarkRift.Tests/DarkRiftWriterTests.cs
similarity index 90%
rename from DarkRift.Testing/DarkRiftWriterTests.cs
rename to DarkRift.Tests/DarkRiftWriterTests.cs
index b399653..a3b8bf2 100644
--- a/DarkRift.Testing/DarkRiftWriterTests.cs
+++ b/DarkRift.Tests/DarkRiftWriterTests.cs
@@ -4,22 +4,16 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
-using System;
-using System.Diagnostics;
-using System.Linq;
-using System.Threading;
-using DarkRift.Dispatching;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-
-namespace DarkRift.Testing
+using NUnit.Framework;
+
+namespace DarkRift.Tests
{
- [TestClass]
public class DarkRiftWriterTests
{
private DarkRiftWriter writer;
- [TestInitialize]
- public void Initialize()
+ [SetUp]
+ public void SetUp()
{
// GIVEN the object cache is disabled
#pragma warning disable CS0618 // We don't care about using Server/Client specific cache settings
@@ -30,8 +24,8 @@ public void Initialize()
writer = DarkRiftWriter.Create();
}
- [TestMethod]
- public void WriteByteTest()
+ [Test]
+ public void WriteByte()
{
// WHEN I write a byte to the writer
writer.Write((byte)5);
@@ -49,8 +43,8 @@ public void WriteByteTest()
Assert.AreEqual(1, writer.Length);
}
- [TestMethod]
- public void WriteCharTest()
+ [Test]
+ public void WriteChar()
{
// WHEN I write a char to the writer
writer.Write('A');
@@ -68,8 +62,8 @@ public void WriteCharTest()
Assert.AreEqual(6, writer.Length);
}
- [TestMethod]
- public void WriteBooleanTest()
+ [Test]
+ public void WriteBoolean()
{
// WHEN I write a boolean to the writer
writer.Write(true);
@@ -87,8 +81,8 @@ public void WriteBooleanTest()
Assert.AreEqual(1, writer.Length);
}
- [TestMethod]
- public void WriteDoubleTest()
+ [Test]
+ public void WriteDouble()
{
// WHEN I write a double to the writer
writer.Write(0.75d);
@@ -106,8 +100,8 @@ public void WriteDoubleTest()
Assert.AreEqual(8, writer.Length);
}
- [TestMethod]
- public void WriteInt16Test()
+ [Test]
+ public void WriteInt16()
{
// WHEN I write a short to the writer
writer.Write((short)-5982);
@@ -125,8 +119,8 @@ public void WriteInt16Test()
Assert.AreEqual(2, writer.Length);
}
- [TestMethod]
- public void WriteInt32Test()
+ [Test]
+ public void WriteInt32()
{
// WHEN I write an int to the writer
writer.Write(589574236);
@@ -144,8 +138,8 @@ public void WriteInt32Test()
Assert.AreEqual(4, writer.Length);
}
- [TestMethod]
- public void WriteInt64Test()
+ [Test]
+ public void WriteInt64()
{
// WHEN I write a long to the writer
writer.Write(5895742365555578888);
@@ -163,8 +157,8 @@ public void WriteInt64Test()
Assert.AreEqual(8, writer.Length);
}
- [TestMethod]
- public void WriteSByteTest()
+ [Test]
+ public void WriteSByte()
{
// WHEN I write an sbyte to the writer
writer.Write((sbyte)-45);
@@ -182,8 +176,8 @@ public void WriteSByteTest()
Assert.AreEqual(1, writer.Length);
}
- [TestMethod]
- public void WriteFloatTest()
+ [Test]
+ public void WriteFloat()
{
// WHEN I write a float to the writer
writer.Write(0.75f);
@@ -201,8 +195,8 @@ public void WriteFloatTest()
Assert.AreEqual(4, writer.Length);
}
- [TestMethod]
- public void WriteUInt16Test()
+ [Test]
+ public void WriteUInt16()
{
// WHEN I write a ushort to the writer
writer.Write((ushort)59554);
@@ -220,8 +214,8 @@ public void WriteUInt16Test()
Assert.AreEqual(2, writer.Length);
}
- [TestMethod]
- public void WriteUInt32Test()
+ [Test]
+ public void WriteUInt32()
{
// WHEN I write a uint to the writer
writer.Write((uint)589574236);
@@ -239,8 +233,8 @@ public void WriteUInt32Test()
Assert.AreEqual(4, writer.Length);
}
- [TestMethod]
- public void WriteUInt64Test()
+ [Test]
+ public void WriteUInt64()
{
// WHEN I write a ulong to the writer
writer.Write((ulong)5895742365555578888);
@@ -258,8 +252,8 @@ public void WriteUInt64Test()
Assert.AreEqual(8, writer.Length);
}
- [TestMethod]
- public void WriteStringTest()
+ [Test]
+ public void WriteString()
{
// WHEN I write a string to the writer
writer.Write("ABC");
@@ -277,8 +271,8 @@ public void WriteStringTest()
Assert.AreEqual(10, writer.Length);
}
- [TestMethod]
- public void WriteBooleansTest()
+ [Test]
+ public void WriteBooleans()
{
// WHEN I write a boolean array to the writer
writer.Write(new bool[] { true, true, false, false, true, false, true, false, true });
@@ -296,8 +290,8 @@ public void WriteBooleansTest()
Assert.AreEqual(6, writer.Length);
}
- [TestMethod]
- public void ToArrayTest()
+ [Test]
+ public void ToArray()
{
// WHEN I write a string to the writer
writer.Write("ABC");
@@ -309,7 +303,7 @@ public void ToArrayTest()
AssertExtensions.AreEqualAndSameLength(new byte[] { 0, 0, 0, 6, 65, 0, 66, 0, 67, 0 }, array);
}
- [TestMethod]
+ [Test]
public void ToArrayWithCountAndOffsetTest()
{
// WHEN I write a string to the writer
@@ -322,7 +316,7 @@ public void ToArrayWithCountAndOffsetTest()
AssertExtensions.AreEqualAndSameLength(new byte[] { 65, 0, 66, 0 }, array);
}
- [TestMethod]
+ [Test]
public void CopyToWithOffsetTest()
{
// WHEN I write a string to the writer
@@ -337,7 +331,7 @@ public void CopyToWithOffsetTest()
AssertExtensions.AreEqualAndSameLength(new byte[] { 9, 0, 0, 0, 6, 65, 0, 66, 0, 67, 0 }, array);
}
- [TestMethod]
+ [Test]
public void CopyToWithCountTest()
{
// WHEN I write a string to the writer
@@ -352,7 +346,7 @@ public void CopyToWithCountTest()
AssertExtensions.AreEqualAndSameLength(new byte[] { 9, 0, 0, 0, 6, 65, 0, 66, 0, 67 }, array);
}
- [TestMethod]
+ [Test]
public void CopyToWithCountAndOffsetsTest()
{
// WHEN I write a string to the writer
diff --git a/DarkRift.Testing/DataStructures/CircularDictionaryTests.cs b/DarkRift.Tests/DataStructures/CircularDictionaryTests.cs
similarity index 66%
rename from DarkRift.Testing/DataStructures/CircularDictionaryTests.cs
rename to DarkRift.Tests/DataStructures/CircularDictionaryTests.cs
index fd285f4..45dee7d 100644
--- a/DarkRift.Testing/DataStructures/CircularDictionaryTests.cs
+++ b/DarkRift.Tests/DataStructures/CircularDictionaryTests.cs
@@ -4,31 +4,25 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
-using DarkRift.DataStructures;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
+using NUnit.Framework;
using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-namespace DarkRift.DataStructures.Testing
+namespace DarkRift.DataStructures.Tests
{
- [TestClass]
public class CircularDictionaryTests
{
private CircularDictionary dictionary;
- [TestInitialize]
- public void Initialize()
+ [SetUp]
+ public void SetUp()
{
dictionary = new CircularDictionary(4);
}
- [TestMethod]
- public void LookupTest()
+ [Test]
+ public void Lookup()
{
- Assert.ThrowsException(() => dictionary[9]);
+ Assert.Throws(() => _ = dictionary[9]);
//Initial population
dictionary.Add(10, 5);
@@ -44,7 +38,7 @@ public void LookupTest()
//Should push off first 10
dictionary.Add(18, 9);
- Assert.ThrowsException(() => dictionary[10]);
+ Assert.Throws(() => _ = dictionary[10]);
Assert.AreEqual(9, dictionary[18]);
}
diff --git a/DarkRift.Testing/DataStructures/MovingAverageFilterTests.cs b/DarkRift.Tests/DataStructures/MovingAverageFilterTests.cs
similarity index 77%
rename from DarkRift.Testing/DataStructures/MovingAverageFilterTests.cs
rename to DarkRift.Tests/DataStructures/MovingAverageFilterTests.cs
index f13aeb6..34938eb 100644
--- a/DarkRift.Testing/DataStructures/MovingAverageFilterTests.cs
+++ b/DarkRift.Tests/DataStructures/MovingAverageFilterTests.cs
@@ -4,27 +4,22 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
-using DarkRift.DataStructures;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using System.Collections.Generic;
-using System.Text;
+using NUnit.Framework;
-namespace DarkRift.DataStructures.Testing
+namespace DarkRift.DataStructures.Tests
{
- [TestClass]
public class MovingAverageFilterTests
{
private MovingAverageFilter filter;
- [TestInitialize]
- public void Initialize()
+ [SetUp]
+ public void SetUp()
{
filter = new MovingAverageFilter(4);
}
- [TestMethod]
- public void AverageTest()
+ [Test]
+ public void Average()
{
Assert.AreEqual(0, filter.Average);
@@ -42,8 +37,8 @@ public void AverageTest()
Assert.AreEqual(8, filter.Average);
}
- [TestMethod]
- public void ResetTest()
+ [Test]
+ public void Reset()
{
Assert.AreEqual(0, filter.Average);
diff --git a/DarkRift.Testing/Dispatching/ActionDispatcherTaskTests.cs b/DarkRift.Tests/Dispatching/ActionDispatcherTaskTests.cs
similarity index 75%
rename from DarkRift.Testing/Dispatching/ActionDispatcherTaskTests.cs
rename to DarkRift.Tests/Dispatching/ActionDispatcherTaskTests.cs
index 3cbf543..6d6dcf6 100644
--- a/DarkRift.Testing/Dispatching/ActionDispatcherTaskTests.cs
+++ b/DarkRift.Tests/Dispatching/ActionDispatcherTaskTests.cs
@@ -5,17 +5,14 @@
*/
using System;
-using DarkRift.Dispatching;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Moq;
+using NUnit.Framework;
-namespace DarkRift.Testing.Dispatching
+namespace DarkRift.Dispatching.Tests
{
- [TestClass]
public class ActionDispatcherTaskTests
{
- [TestInitialize]
- public void Initialize()
+ [SetUp]
+ public void SetUp()
{
//Object cache needs to be initialized for create
#pragma warning disable CS0618 // We don't care about using Server/Client specific cache settings
@@ -23,8 +20,8 @@ public void Initialize()
#pragma warning restore CS0618
}
- [TestMethod]
- public void TestExecuteSynchronous()
+ [Test]
+ public void ExecuteSynchronous()
{
bool set = false;
ActionDispatcherTask task = ActionDispatcherTask.Create(() => set = true);
@@ -37,8 +34,8 @@ public void TestExecuteSynchronous()
Assert.AreEqual(DispatcherTaskState.CompletedImmediate, task.TaskState);
}
- [TestMethod]
- public void TestExecuteAsynchronous()
+ [Test]
+ public void ExecuteAsynchronous()
{
bool set = false;
ActionDispatcherTask task = ActionDispatcherTask.Create(() => set = true);
@@ -51,18 +48,15 @@ public void TestExecuteAsynchronous()
Assert.AreEqual(DispatcherTaskState.CompletedQueued, task.TaskState);
}
- [TestMethod]
- public void TestExecuteException()
+ [Test]
+ public void ExecuteException()
{
Exception exception = new Exception();
ActionDispatcherTask task = ActionDispatcherTask.Create(() => throw exception);
Assert.AreEqual(DispatcherTaskState.Queued, task.TaskState);
- Assert.ThrowsException(() =>
- {
- task.Execute(true);
- });
+ Assert.Throws(() => task.Execute(true));
Assert.AreEqual(DispatcherTaskState.Failed, task.TaskState);
Assert.AreEqual(exception, task.Exception);
diff --git a/DarkRift.Testing/Dispatching/DispatcherTests.cs b/DarkRift.Tests/Dispatching/DispatcherTests.cs
similarity index 78%
rename from DarkRift.Testing/Dispatching/DispatcherTests.cs
rename to DarkRift.Tests/Dispatching/DispatcherTests.cs
index 2a0e029..6f3d0e0 100644
--- a/DarkRift.Testing/Dispatching/DispatcherTests.cs
+++ b/DarkRift.Tests/Dispatching/DispatcherTests.cs
@@ -6,24 +6,25 @@
using System;
using System.Threading;
-using DarkRift.Dispatching;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
+using NUnit.Framework;
-namespace DarkRift.Testing.Dispatching
+namespace DarkRift.Dispatching.Tests
{
- [TestClass]
public class DispatcherTests
{
private Dispatcher dispatcher;
- [TestInitialize]
- public void Initialize()
+ [SetUp]
+ public void SetUp()
{
-
+ //Object cache needs to be initialized for create
+#pragma warning disable CS0618 // We don't care about using Server/Client specific cache settings
+ ObjectCache.Initialize(ObjectCacheSettings.DontUseCache);
+#pragma warning restore CS0618
}
- [TestMethod]
- public void InvokeAsyncTests()
+ [Test]
+ public void InvokeAsync()
{
dispatcher = new Dispatcher(true);
int executed = 0;
@@ -38,17 +39,14 @@ public void InvokeAsyncTests()
Assert.AreEqual(DispatcherTaskState.CompletedImmediate, task.TaskState);
//Should invoke asynchronously
- Thread t = new Thread(() =>
- {
- task = dispatcher.InvokeAsync(() => { executed++; return; });
- });
+ Thread t = new Thread(() => task = dispatcher.InvokeAsync(() => { executed++; return; }));
t.Start();
t.Join();
Assert.AreEqual(1, dispatcher.Count);
Assert.AreEqual(1, executed);
Assert.AreEqual(DispatcherTaskState.Queued, task.TaskState);
-
+
dispatcher.ExecuteDispatcherTasks();
Assert.AreEqual(0, dispatcher.Count);
@@ -56,8 +54,8 @@ public void InvokeAsyncTests()
Assert.AreEqual(DispatcherTaskState.CompletedQueued, task.TaskState);
}
- [TestMethod]
- public void InvokeAsyncFuncTests()
+ [Test]
+ public void InvokeAsyncFunc()
{
dispatcher = new Dispatcher(true);
int executed = 0;
@@ -73,10 +71,7 @@ public void InvokeAsyncFuncTests()
Assert.AreEqual(DispatcherTaskState.CompletedImmediate, task.TaskState);
//Should invoke asynchronously
- Thread t = new Thread(() =>
- {
- task = dispatcher.InvokeAsync(() => ++executed);
- });
+ Thread t = new Thread(() => task = dispatcher.InvokeAsync(() => ++executed));
t.Start();
t.Join();
@@ -92,11 +87,11 @@ public void InvokeAsyncFuncTests()
Assert.AreEqual(DispatcherTaskState.CompletedQueued, task.TaskState);
}
- [TestMethod]
- public void ExecuteDispatcherTasksTests()
+ [Test]
+ public void ExecuteDispatcherTasks()
{
dispatcher = new Dispatcher(false);
-
+
//Should execute all current tasks, exception suppressed
int executed = 0;
Thread t = new Thread(() =>
@@ -114,11 +109,11 @@ public void ExecuteDispatcherTasksTests()
Assert.AreEqual(3, executed);
}
- [TestMethod]
- public void ExecuteDispatcherTasksExceptionsTests()
+ [Test]
+ public void ExecuteDispatcherTasksExceptions()
{
dispatcher = new Dispatcher(true);
-
+
//Should execute 1st task then raise second task exception
int executed = 0;
Thread t = new Thread(() =>
@@ -130,10 +125,7 @@ public void ExecuteDispatcherTasksExceptionsTests()
t.Start();
t.Join();
- Assert.ThrowsException(() =>
- {
- dispatcher.ExecuteDispatcherTasks();
- });
+ Assert.Throws(() => dispatcher.ExecuteDispatcherTasks());
Assert.AreEqual(1, executed);
}
diff --git a/DarkRift.Testing/MemoryPoolTests.cs b/DarkRift.Tests/MemoryPoolTests.cs
similarity index 83%
rename from DarkRift.Testing/MemoryPoolTests.cs
rename to DarkRift.Tests/MemoryPoolTests.cs
index 2219136..dd30014 100644
--- a/DarkRift.Testing/MemoryPoolTests.cs
+++ b/DarkRift.Tests/MemoryPoolTests.cs
@@ -4,16 +4,10 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace DarkRift.Testing
+using NUnit.Framework;
+
+namespace DarkRift.Tests
{
- [TestClass]
public class MemoryPoolTests
{
// TODO This test should DI mock ObjectPool instances and assert on them
@@ -23,14 +17,14 @@ public class MemoryPoolTests
///
private MemoryPool memoryPool;
- [TestInitialize]
- public void Initialize()
+ [SetUp]
+ public void SetUp()
{
memoryPool = new MemoryPool(16, 4, 64, 4, 256, 4, 1024, 4, 4096, 4);
}
- [TestMethod]
- public void GetExtraSmallMemoryTest()
+ [Test]
+ public void GetExtraSmallMemory()
{
// GIVEN a memory pool with no previously pooled memory
@@ -42,8 +36,8 @@ public void GetExtraSmallMemoryTest()
Assert.AreEqual(16, result.Length);
}
- [TestMethod]
- public void GetSmallMemoryTest()
+ [Test]
+ public void GetSmallMemory()
{
// GIVEN a memory pool with no previously pooled memory
@@ -55,8 +49,8 @@ public void GetSmallMemoryTest()
Assert.AreEqual(64, result.Length);
}
- [TestMethod]
- public void GetMediumMemoryTest()
+ [Test]
+ public void GetMediumMemory()
{
// GIVEN a memory pool with no previously pooled memory
@@ -68,8 +62,8 @@ public void GetMediumMemoryTest()
Assert.AreEqual(256, result.Length);
}
- [TestMethod]
- public void GetLargeMemoryTest()
+ [Test]
+ public void GetLargeMemory()
{
// GIVEN a memory pool with no previously pooled memory
@@ -81,8 +75,8 @@ public void GetLargeMemoryTest()
Assert.AreEqual(1024, result.Length);
}
- [TestMethod]
- public void GetExtraLargeMemoryTest()
+ [Test]
+ public void GetExtraLargeMemory()
{
// GIVEN a memory pool with no previously pooled memory
@@ -94,8 +88,8 @@ public void GetExtraLargeMemoryTest()
Assert.AreEqual(4096, result.Length);
}
- [TestMethod]
- public void GetLargerThanExtraLargeMemoryTest()
+ [Test]
+ public void GetLargerThanExtraLargeMemory()
{
// GIVEN a memory pool with no previously pooled memory
@@ -107,8 +101,8 @@ public void GetLargerThanExtraLargeMemoryTest()
Assert.AreEqual(10000, result.Length);
}
- [TestMethod]
- public void ReturnSmallerThanExtraSmallMemoryTest()
+ [Test]
+ public void ReturnSmallerThanExtraSmallMemory()
{
// GIVEN a memory pool with no previously pooled memory
@@ -124,8 +118,8 @@ public void ReturnSmallerThanExtraSmallMemoryTest()
Assert.AreEqual(16, newBlock.Length);
}
- [TestMethod]
- public void ReturnExtraSmallMemoryTest()
+ [Test]
+ public void ReturnExtraSmallMemory()
{
// GIVEN a memory pool with no previously pooled memory
@@ -140,8 +134,8 @@ public void ReturnExtraSmallMemoryTest()
Assert.AreSame(oldBlock, newBlock);
}
- [TestMethod]
- public void ReturnSmallMemoryTest()
+ [Test]
+ public void ReturnSmallMemory()
{
// GIVEN a memory pool with no previously pooled memory
@@ -156,8 +150,8 @@ public void ReturnSmallMemoryTest()
Assert.AreSame(oldBlock, newBlock);
}
- [TestMethod]
- public void ReturnMediumMemoryTest()
+ [Test]
+ public void ReturnMediumMemory()
{
// GIVEN a memory pool with no previously pooled memory
@@ -172,8 +166,8 @@ public void ReturnMediumMemoryTest()
Assert.AreSame(oldBlock, newBlock);
}
- [TestMethod]
- public void ReturnLargeMemoryTest()
+ [Test]
+ public void ReturnLargeMemory()
{
// GIVEN a memory pool with no previously pooled memory
@@ -188,8 +182,8 @@ public void ReturnLargeMemoryTest()
Assert.AreSame(oldBlock, newBlock);
}
- [TestMethod]
- public void ReturnExtraLargeMemoryTest()
+ [Test]
+ public void ReturnExtraLargeMemory()
{
// GIVEN a memory pool with no previously pooled memory
diff --git a/DarkRift.Tests/MockMessageBuffer.cs b/DarkRift.Tests/MockMessageBuffer.cs
new file mode 100644
index 0000000..0681a86
--- /dev/null
+++ b/DarkRift.Tests/MockMessageBuffer.cs
@@ -0,0 +1,21 @@
+using System;
+
+namespace DarkRift.Tests
+{
+ public class MockMessageBuffer : IMessageBuffer
+ {
+ public byte[] Buffer { get; set; }
+ public int Count { get; set; }
+ public int Offset { get; set; }
+
+ public IMessageBuffer Clone()
+ {
+ throw new NotImplementedException();
+ }
+
+ public void Dispose()
+ {
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/DarkRift.Testing/ObjectPoolTests.cs b/DarkRift.Tests/ObjectPoolTests.cs
similarity index 78%
rename from DarkRift.Testing/ObjectPoolTests.cs
rename to DarkRift.Tests/ObjectPoolTests.cs
index 44da41a..00f947c 100644
--- a/DarkRift.Testing/ObjectPoolTests.cs
+++ b/DarkRift.Tests/ObjectPoolTests.cs
@@ -4,16 +4,10 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace DarkRift.Testing
+using NUnit.Framework;
+
+namespace DarkRift.Tests
{
- [TestClass]
public class ObjectPoolTests
{
///
@@ -26,19 +20,16 @@ public class ObjectPoolTests
///
private object newInstance;
- [TestInitialize]
- public void Initialize()
+ [SetUp]
+ public void SetUp()
{
newInstance = null;
- objectPool = new ObjectPool